//---------------------------
function BildPopup(link,name,toolbar,menubar,width,height)
{
	window.open(link,name,'toolbar=' + toolbar +',location=no,directories=no,status=no, menubar=' + menubar + ',scrollbars=no,resizable=no,copyhistory=no,width=' + width +',height=' +height);
}
function Popup(link,toolbar,menubar,width,height)
{
	BildPopup(link,'popup',toolbar,menubar,width,height);
}
//---------------------------
function showmenu(elmnt,elm_addr)
{
	the_menu = document.getElementById(elmnt);
	if(the_menu) the_menu.style.visibility = 'visible';
	//the_menu.style.top = 100;
	//the_menu.style.left = 100;
	//document.all(elmnt).style.visibility="visible";
	elm_addr.style.color = "#FFFFFF";
	elm_addr.style.backgroundColor = "#000000";
}
function hidemenu(elmnt,elm_addr)
{
	the_menu = document.getElementById(elmnt);
	if(the_menu) the_menu.style.visibility = 'hidden';
	//document.all(elmnt).style.visibility="hidden";
	elm_addr.style.color = "#606060";
	elm_addr.style.backgroundColor = "#FFFFFF";
}
//---------------------------
function do_select(elmnt)
{
	elmnt.style.color = "#FFFFFF";
	elmnt.style.backgroundColor = "#000000";
}
function do_deselect(elmnt)
{
	elmnt.style.color = "#606060";
	elmnt.style.backgroundColor = "#FFFFFF";
}
function do_click(elmnt,thelink)
{
	elmnt.style.color = "#FFFFFF";
	elmnt.style.backgroundColor = "#FF0000";
	//alert(thelink);
	if(thelink!='') window.location = thelink;
}
//----------------------------------
// pentru selectia liniilor in tabel
//----------------------------------
var elem_url;
// mouseout si mouseover
function mouseout(elem, old_back_color)
{
	elem.style.backgroundColor = old_back_color;
	elem.style.color           = '#000';
//	elem.style.border          = '1 solid #CCC';
}
function mouseover(elem, new_back_color)
{
	elem.style.backgroundColor = new_back_color;
	elem.style.color           = '#FFF';
//	elem.style.border          = '1 solid #CCC';
}
function sel_elem()
{
	window.location = elem_url;
}
function click_table_elem(elem, new_back_color, elemurl)
{
	elem.style.backgroundColor = new_back_color;
	elem.style.color           = '#FFF';
//	elem.style.border          = '1 solid #CCC';
	elem_url = elemurl;
	window.setTimeout('sel_elem()',100);
}
//--------------------------------
//---------------------------
//---------------------------
//---------------------------
function checkform_eventregister(form)
{
    if(form.inp_firstname.value=="")
    {
        alert("Introduceti prenumele !");
        form.inp_firstname.focus();
        return false;
    }
    if(form.inp_lastname.value=="")
    {
        alert("Introduceti numele !");
        form.inp_lastname.focus();
        return false;
    }
    if(form.inp_email.value.length<6)
    {
        alert("Introduceti email-ul !");
        form.inp_email.focus();
        return false;
    }
    if(form.inp_phone.value.length<10)
    {
        alert("Introduceti telefonul !");
        form.inp_phone.focus();
        return false;
    }
	return true;
}
//---------------------------
function checkform_changepass2(form)
{
	if(form.inp_pass.value.length<3)
	{
		alert("Introduceti parola veche !\n\nDaca nu va amintiti parola veche, faceti Logout si apoi utilizati functia 'Recuperare parola' din sectiunea Login");
		form.inp_pass.focus();
		return false;
	}
	if(form.inp_pass1.value.length<6)
	{
		alert("Parola trebuie sa aiba cel putin 6 caractere !");
		form.inp_pass1.focus();
		return false;
	}
	if(form.inp_pass1.value!=form.inp_pass2.value)
	{
		alert("Parolele nu sunt la fel !");
		form.inp_pass2.focus();
		return false;
	}
    return true;
}
//---------------------------
function checkform_adduser(form, checkPass)
{
    if(form.inp_email1.value.length<6)
    {
        alert("Introduceti email-ul !");
        form.inp_email1.focus();
        return false;
    }
    if(form.inp_email1.value!=form.inp_email2.value)
    {
        alert("Reconfirmati email-ul !");
        form.inp_email2.focus();
        return false;
    }
	if(checkPass)
	{
		if(form.inp_pass1.value.length<6)
		{
			alert("Parola trebuie sa aiba cel putin 6 caractere !");
			form.inp_pass1.focus();
			return false;
		}
		if(form.inp_pass1.value!=form.inp_pass2.value)
		{
			alert("Parolele nu sunt la fel !");
			form.inp_pass2.focus();
			return false;
		}
	}
	//---------------
    if(form.inp_firstname.value=="")
    {
        alert("Introduceti prenumele !");
        form.inp_firstname.focus();
        return false;
    }
    if(form.inp_lastname.value=="")
    {
        alert("Introduceti numele !");
        form.inp_lastname.focus();
        return false;
    }
    if(form.inp_cnp.value.length<13)
    {
        alert("CNP-ul trebuie sa aiba 13 caractere !");
        form.inp_cnp.focus();
        return false;
    }
	//---------------
    if(form.inp_address.value.length<5)
    {
        alert("Introduceti adresa !");
        form.inp_address.focus();
        return false;
    }
    if(form.inp_town.value.length<3)
    {
        alert("Introduceti localitatea !");
        form.inp_town.focus();
        return false;
    }
    if(form.inp_county.value=="")
    {
        alert("Alegeti judetul/sectorul !");
        form.inp_county.focus();
        return false;
    }
    if(form.inp_zip.value.length<4)
    {
        alert("Introduceti codul postal !");
        form.inp_zip.focus();
        return false;
    }
    if(form.inp_phone1.value.length<8)
    {
        alert("Introduceti telefon-ul !");
        form.inp_phone1.focus();
        return false;
    }
	//---------------
	if(form.persj.checked)
	{
		if(form.inp_comp_name.value.length<3)
		{
			alert("Introduceti numele companiei !");
			form.inp_comp_name.focus();
			return false;
		}
		if(form.inp_cif2.value.length<6)
		{
			alert("Introduceti codul fiscal (CUI/CIF) !");
			form.inp_cif2.focus();
			return false;
		}
		if(form.inp_comp_bank.value.length<3)
		{
			alert("Introduceti banca !");
			form.inp_comp_bank.focus();
			return false;
		}
		if(form.inp_comp_account.value.length<16)
		{
			alert("Introduceti contul !");
			form.inp_comp_account.focus();
			return false;
		}
		if(form.inp_j2.value=="")
		{
			alert("Introduceti codul de inregistrare in registrul comertului ('J'-ul) !");
			form.inp_j2.focus();
			return false;
		}
		if(form.inp_j3.value=="")
		{
			alert("Introduceti codul de inregistrare in registrul comertului ('J'-ul) !");
			form.inp_j3.focus();
			return false;
		}
		if(form.inp_j4.value=="")
		{
			alert("Introduceti codul de inregistrare in registrul comertului ('J'-ul) !");
			form.inp_j4.focus();
			return false;
		}
	}
    return true;
}
//---------------------------
//---------------------------
//---------------------------
// for the tooltips
function setState(which, state) 
{
	document.getElementById(which).style.display = state;
	if (self["timer"+which]!=null) clearTimeout(self["timer"+which]);
} 
function toggleTooltip(theEvent, targetId, state, parentId) 
{
	var states = new Array("none", "block");
	if(state==1)
	{
		if (!theEvent) theEvent = window.event;
		document.getElementById(targetId).style.left = "0px";
		document.getElementById(targetId).style.top = "0px";
		document.getElementById(parentId).style.left = theEvent.clientX+8+"px";
		document.getElementById(parentId).style.top = theEvent.clientY+16+"px";
	}
	if (document.getElementById(targetId).style.display==states[state] && self["timer"+targetId]!=null)
	{
		clearTimeout(self["timer"+targetId]);
	}else 
	{
		if (state==0)
			self["timer"+targetId]=setTimeout("setState('"+targetId+"', '"+states[state]+"')", 100);
		else
			setState(targetId, states[state]);
	}
} 
//---------------------------
function displayDiv(targetId,disp)
{
	if(disp==0)
	{
		document.getElementById(targetId).style.display = "none";
	}else
	{
		//alert("mda1");
		document.getElementById(targetId).style.display = "block";
	}
}
//---------------------------
//---------------------------
//---------------------------
// jQuery functions
// assign onclick functions to elements after page loading
/* The following code is executed once the DOM is loaded */
$(document).ready(function()
{
//	alert("the page was loaded");
	/*
	$("#generate").click(function()
	{
		$("#quote p").load("script.php");
	});
	$("a").click(function(event)
	{
		alert("mda, merge pe <a>");
		event.preventDefault();// nu mai executa actiunea
		//$(this).hide("slow");// efect de "hide"
		//$("a").addClass("test");// adauga o clasa CSS la element
		//$("a").removeClass("test");// sterge o clasa CSS din element
	});
	*/
	// Tell jQuery that our div is to be a dialog
//	$('#searchResultsDiv').addClass('flora').dialog();
	$('#searchResultsDiv').hide();
/*
	$('#searchResultsDiv').addClass('flora').dialog(
		{
		title: 'Add Note',
		buttons: {
		'Save': function() { $(this).dialog('close'); ajaxSaveNote(); },
		'Cancel': function() { $(this).dialog('close'); }
		},
		autoOpen: true,
		position: [150,200],
		modal: false,
		overlay:{color:'#000'}
		}
	);
*/
	//$("a[rel^='prettyPhoto']").prettyPhoto();
	// prettyPhoto bug fix to eliminate url modification at exit: function clearHashtag(){ ... if(hashtag && settings.deeplinking) location.hash = "!prettyPhoto";}
	$("a[rel^='prettyPhoto']").prettyPhoto({theme:'facebook', slideshow:3000, overlay_gallery:false, hideflash:true, deeplinking:false});
	//$(".gallery a[rel^='prettyPhoto']").prettyPhoto({theme:'facebook',slideshow:3000});
	// the admin tab
	theAdminTab = $('#adminTabs > ul');
	if(theAdminTab) if(theAdminTab.tabs) theAdminTab.tabs({ selected: 0, fx: {height: 'toggle', opacity: 'toggle', duration: 'fast'} });
	
	$('.buttonjquery1 a').hover(function()
	{  
		$(this).stop().animate({'opacity' : '0'}, 150);  
	}, function()
	{
		$(this).stop().animate({'opacity' : '1'}, 300);
	});
	
	// Calling the jQuery plugin and splitting the
	// #contentCategsUl UL into pages of 3 LIs each:
	$('#contentCategsUl').sweetPages({perPage:1});

	// The default behaviour of the plugin is to insert the
	// page links in the ul, but we need them in the main contentCategsDiv container:
	var controls = $('.swControls').detach();
	controls.appendTo('#contentCategsDiv');
	/*
	$('#slideshow').cycle({ 
		fx:     'fade', 
		timeout: 2000, 
		after:   onAfter 
	});
	*/
	// start getting error messages in your Firebug console
	$(document).ajaxError(function()
	{
	    if(window.console && window.console.error) 
		{
	        console.error(arguments);
	    }
	});
});
//---------------------------
function showBanners(buttonPressed,thePage)
{
	theUrl = '/index/ajax/showbanners-'+thePage+'.html';
	$.post(theUrl,
	function (resp)
	{
		// update the paragraph with the response
		$('#showBannersDiv').html(resp);
	});
}
//---------------------------
function showOrders(buttonPressed,thePage)
{
	theUrl = '/index/ajax/showorders-'+thePage+'.html';
	$.post(theUrl,
	function (resp)
	{
		// update the paragraph with the response
		$('#showOrdersDiv').html(resp);
	});
}
//---------------------------
function showAccounts(buttonPressed,thePage,sortColumn,sortOrder,filterString)
{
	theUrl = '/index/ajax/showaccounts-'+thePage+'-'+sortColumn+'-'+sortOrder+'.html';
	if(!filterString) filterString = ' ';
	//alert(theUrl);
	//alert('the string is "'+filterString+'"'); return;
	$.post(theUrl,
	{inp_filter_string: filterString},
	function (resp)
	{
		// update the paragraph with the response
		$('#showAccountsDiv').html(resp);
	},"html");
}
//---------------------------
function doAjaxAction(urlToPost, divToUpdate)
{
	$.post(urlToPost,
	function (resp)
	{
		// update the paragraph with the response
		$('#'+divToUpdate).html(resp);
	});
}
//---------------------------
function createNewOrder()
{
	theAccountId = $("#theAccountId").val();
	doAjaxAction('/index/ajax/addneworder-'+theAccountId+'.html','showOrdersDiv');
}
//---------------------------
function modifyOrderProductCount(orderId, productId, textfieldId)
{
	theValue = $("#cant_"+textfieldId).val();
	//alert("update order "+orderId+" modify product "+productId+" to "+theValue);
	doAjaxAction('/index/ajax/editorderproduct-'+orderId+'-'+productId+'-'+theValue+'.html','showOrdersDiv');
}
//---------------------------
function clearOrder(orderId, deleteOrder)
{
	mesaj = 'Sunteti sigur ca doriti sa stergeti toate produsele?';
	if(deleteOrder)
	{
		mesaj = 'Sunteti sigur ca doriti sa stergeti comanda?';
	}
	result = confirm(mesaj);
	if(result)
	{
		if(deleteOrder)
		{
			doAjaxAction('/index/ajax/clearorder-'+orderId+'-1.html','showOrdersDiv');
		}else
		{
			doAjaxAction('/index/ajax/clearorder-'+orderId+'-0.html','showOrdersDiv');
		}
	}
}
//---------------------------
function changeOrderManufSelector(orderId)
{
	$('#showProductsSelectSpan').html('se incarca ...');
	manufId = $("#showManufOrderSelect").val();
	//alert('changeOrderManufSelector order='+orderId+', manuf='+manufId);
	doAjaxAction('/index/ajax/showproductsselector-'+orderId+'-'+manufId+'.html','showProductsSelectSpan');
}
//---------------------------
function changeOrderProductSelector(orderId)
{
	//$('#showOrdersDiv').html('se incarca ...');
	prodId = $("#showProductOrderSelect").val();
	doAjaxAction('/index/ajax/editorderproduct-'+orderId+'-'+prodId+'-1.html','showOrdersDiv');
}
//---------------------------
function changeOrderStatus(orderId)
{
	status = $("#inp_status").val();
	//alert('changeOrderStatus order='+orderId+', status='+status);
	doAjaxAction('/index/ajax/changeorderstatus-'+orderId+'-'+status+'.html','showOrdersDiv');
}
//---------------------------
function changeAccountType(accountId)
{
	// mesaj de confirmare
	mesaj = 'ATENTIE: Sunteti sigur ca doriti sa schimbati tipul acestui cont?\n\n(un cont cu drepturi de admin poate efectua operatii ce pot fi periculoase pentru securitatea si continutul site-ului!!!)';
	result = confirm(mesaj);
	if(!result) return;
	accountType = $("#inp_account_type").val();
	/*
	// daca noul tip este admin se da inca un mesaj
	mesaj2 = 'ATENTIE: Sunteti sigur ca doriti sa schimbati tipul acestui cont?\n\n(un cont cu drepturi de admin poate efectua operatii ce pot fi periculoase pentru securitatea si continutul site-ului!!!)';
	result = confirm(mesaj2);
	if(!result) return;
	*/
	//alert('changeAccountType account='+accountId+', accountType='+accountType);
	doAjaxAction('/index/ajax/changeaccounttype-'+accountId+'-'+accountType+'.html','showAccountTypeDiv');
}
//---------------------------
function showDiv(theDiv)
{
	theDivObj = $('#'+theDiv);
	theDivObj.toggle("fast");
	//if(theDivObj.isShown()) theDivObj.hide("fast");else theDivObj.show("fast");
	return false;
}
//---------------------------
function changeManufacturerSource()
{
//	alert('changeManufacturerSource');
	manufacturer = $("#showStockSelect").val();
	theUrl = '/index/ajax/updateandshowstock-'+manufacturer+'.html';
	$.post(theUrl,
	function (resp)
	{
		// update the paragraph with the response
//		$('#showStockDiv').html("&euro;");
		$('#showStockDiv').html(resp);
	},"html");// Type of data to be returned to callback function: "xml", "html", "script", "json", "jsonp", or "text"
}
//---------------------------
function bulkUpdateDisc(totalRows)
{
	mesaj = 'ATENTIE: Sunteti sigur ca doriti sa schimbati toate discount-urile pentru acest producator?\n\n(se vor supra-scrie toate in acelasi timp!)';
	result = confirm(mesaj);
	if(!result) return;
	// get the bulk values
	theId = '#disc1_'+(totalRows+1); disc1 = $(theId).val()
	theId = '#disc2_'+(totalRows+1); disc2 = $(theId).val()
	theId = '#disc3_'+(totalRows+1); disc3 = $(theId).val()
	//alert('bulkUpdateDisc disc1='+disc1+', disc2='+disc2+', disc3='+disc3);
	// do the actual bulk set
	for(i=1; i<=totalRows; i++)
	{
		theId = '#disc1_'+i; $(theId).val(disc1);
		theId = '#disc2_'+i; $(theId).val(disc2);
		theId = '#disc3_'+i; $(theId).val(disc3);
	}
}
//---------------------------
function updateStock(manufacturer,totalRows)
{
	var myVars = ['isDisabled', 'isPromo', 'promoPrice', 'price', 'priceMsrp', 'stock', 'disc1', 'disc2', 'disc3', 'isPriceHidden'];
	var isChkBox = [1,1, 0,0,0,0, 0,0,0, 1];
	// in the HTML element, we encode the internalId and the initialValue in the 'name' attribute
	// eg. 'isDisabledName_23_0' = var name 'isDisabled' with id '23' and initial value '0'
	theData = '';
	for(i=1; i<=totalRows; i++)
	{
		shouldBeAdded = false;
		theTempData = '';
		for(j=0; j<myVars.length; j++)
		{
			// compose the html element id name
			theId = '#'+myVars[j]+'_'+i;
			theNameAttr = $(theId).attr("name");
			//alert(theId+' name="'+theNameAttr+'"');
			// remove the first N chars to get the actual content
			theNameAttrContent = theNameAttr.substring((myVars[j]+'Name_').length);
			var temp = new Array();
			temp = theNameAttrContent.split('_');
			// get the new value (and test if it's not a checkbox field)
			if(isChkBox[j]==0)
			{
				theNewValue = $(theId).val();
			}else
			{
				if($(theId).is(":checked")) theNewValue=1;else theNewValue=0;
			}
			// we now have the internalId in 'temp[0]', the initialValue in 'temp[1]' 
			// and the new edited (or not) value in 'theNewValue'
			if(j==0) theTempData = temp[0];
			theTempData += ","+theNewValue;
			if(theNewValue!=temp[1]) shouldBeAdded = true;
		}
		//alert(theTempData);
		if(shouldBeAdded)
		{
			theData += theTempData + ';';
		}
	}
	// upload the data
	if(theData.length<=0) 
	{
		alert("Nu ati modificat niciun produs !");
		return;
	}
	// make an ajax request to update the database and get back the changes made
	//alert('updateStock '+theData); return;
	theUrl = '/index/ajax/updateandshowstock-'+manufacturer+'.html';
	$.post(theUrl,
	{inp_new_stock: theData},
	function (resp)
	{
		// update the paragraph with the response
		$('#showStockDiv').html(resp);
		alert('Produsele au fost updatate !');
	},"html");
}
//---------------------------
function newsletterSubmit()
{
	var name = $('#newsName').val();
	var email = $('#newsEmail').val();
    if(name.length<3)
    {
        alert("Introduceti numele !");
        name.focus();
        return false;
    }
    if((email.length<6)||(email.indexOf('@')<0)||(email.indexOf('.')<0))
    {
        alert("Introduceti email-ul !");
        email.focus();
        return false;
    }
	//alert('newsletterSubmit name='+name+' email='+email);
	theUrl = '/index/ajax/addToNewsletter-0.html';
	$.post(theUrl,
		{inp_eml: email, inp_nme: name},
		function(resp)
		{
			$('#newsName').val('');
			$('#newsEmail').val('');
			// update the paragraph with the response
			//alert(resp);
			alert('Va multumim pentru ca v-ati inscris la newsletter-ul nostru !');
		},"html");
	return false;
}
//---------------------------
//---------------------------
//---------------------------
var searchBoxString='';
//---------------------------
function closeSearch()
{
	searchBoxString='';
	$('#searchResultsDiv').hide("fast");
}
//---------------------------
function searchOnBlur()
{
//	$('#searchResultsDiv').dialog('close');
	$("#searchsite").val("Cauta produse, firme ...");
	//$('#searchResultsDiv').hide("fast");
	//$('#searchResultsDiv').html("");
}
//---------------------------
function searchOnFocus()
{
	$("#searchsite").val("");
	$('#searchResultsDiv').show("fast");
//	$('#searchResultsDiv').dialog('open');
//	setTimeout("$('#searchResultsDiv').dialog('open')",1000);
//	setTimeout("alert('mda')",1000);
//	return false;
}
//---------------------------
function searchOnChange()
{
	theString = $("#searchsite").val();
	searchBoxString = theString;
	getSearchResults(theString);
	//alert('searchOnChange');
}
//---------------------------
function searchOnKeyDown(e)
{
	var keynum;
	var keychar;
	e = (e) ? e : ((event) ? event : null);
	if(window.event) // IE
	{
		keynum = e.keyCode;
	}else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}
	if(keynum==27)
	{
		//$("#searchsite").val("");
		$("#searchsite").blur();
		$('#searchResultsDiv').hide("fast");
		//searchOnBlur();
		//alert("merge esc");
		return;
	}
	if(keynum==13)
	{
		//alert("search in new page");
		thelink = '/index/page/en-home-search.html?s=' + $("#searchsite").val();
		window.location = thelink;
		return;
	}
	keychar = String.fromCharCode(keynum);
}
//---------------------------
function searchInNewPage()
{
	thelink = '/index/page/en-home-search.html?s=' + searchBoxString;
	window.location = thelink;
	return false;
}
//---------------------------
function searchOnKeyPress(e)
{	
	//theString = $("#searchsite").val();
	//getSearchResults(theString);
	//alert('searchOnKeyUp');
}
//---------------------------
function searchOnKeyUp(e)
{	
	theString = $("#searchsite").val();
	getSearchResults(theString);
	//alert('searchOnKeyUp');
	var keynum;
	var keychar;
	e = (e) ? e : ((event) ? event : null);
	if(window.event) // IE
	{
		keynum = e.keyCode;
	}else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}
	if(keynum==27)
	{
		//window.focus();
		//$('#searchResultsDiv').focus();
		//setTimeout('$(document).focus();',100);
//		$(document).focus();
//		$(document).click();
//		$('#searchResultsDiv').click();
//		$(document).window.focus();
		//alert("merge esc2");
		return;
	}
}
//---------------------------
function searchOnSelect()
{
	//alert('searchOnSelect');
}
//---------------------------
function getSearchResults(searchString)
{
	//if(searchString.length<1) return;
//	$('#searchResultsDiv').html(searchString);
	theUrl = '/index/ajax/search.html';
	$.post(theUrl,
	{inp_search_string: searchString},
	function (resp)
	{
		// update the paragraph with the response
		$('#searchResultsDivInner').html(resp);
	},"html");
}
//---------------------------
function changeValueData(varName)
{
	theValue = $('#'+varName).val();
	theUrl = '/index/ajax/updateglobalvariable.html';
	$.post(theUrl,
	{inp_var_name: varName, inp_var_value: theValue},
	function (resp)
	{
		// update the page with the response
		$('#'+varName+'UpdateText').html(resp);
	},"html");
}
//---------------------------
// test functions
function getServerTime()
{
	// get the current time from the server and display it to the user
	// we can also use 'jQuery.' instead of '$.'	
	$.post('/index/ajax/time-023.html',
	function (resp)
	{
		// update the paragraph with the response
		$('#serverTime').html(resp);
	});
	//
	// For example, to append the text "Hello World!" to all divs with the class 'foo', 
	// then set the color to red, we'd use the following code:
	// $("div.foo").append("Hello World!").css("color","red");	
};
//---------------------------
//---------------------------
//---------------------------
function filterOnBlur()
{
	theString = $("#filteraccounts").val();
	if((theString=='')||(theString==" ")) 
	{
		$("#filteraccounts").val("Cauta ...");
		showAccounts(1, 1, 0, 0, " ");
	}
	return true;
}
//---------------------------
function filterOnFocus()
{
	theString = $("#filteraccounts").val();
	if((theString=='')||(theString=="Cauta ...")) $("#filteraccounts").val("");
	return true;
}
//---------------------------
function filterOnChange()
{
	theString = $("#filteraccounts").val();
	showAccounts(1, 1, 0, 0, theString);
	//alert('filterOnChange');
	return true;
}
//---------------------------
function filterOnKeyDown(e)
{
	var keynum;
	var keychar;
	e = (e) ? e : ((event) ? event : null);
	if(window.event) // IE
	{
		keynum = e.keyCode;
	}else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}
	if(keynum==27)
	{
		$("#filteraccounts").val("");
		//showAccounts(1, 1, 0, 0, " ");
		//alert("merge esc");
		return true;
	}
	keychar = String.fromCharCode(keynum);
	return true;
}
//---------------------------
function filterOnKeyUp(e)
{	
	theString = $("#filteraccounts").val();
	showAccounts(1, 1, 0, 0, theString);
	//alert('filterOnKeyUp');
	var keynum;
	var keychar;
	e = (e) ? e : ((event) ? event : null);
	if(window.event) // IE
	{
		keynum = e.keyCode;
	}else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}
	if(keynum==27)
	{
		//window.focus();
		//$('#searchResultsDiv').focus();
		//setTimeout('$(document).focus();',100);
//		$(document).focus();
//		$(document).click();
//		$('#searchResultsDiv').click();
//		$(document).window.focus();
		//alert("merge esc2");
		return true;
	}
	return true;
}
//---------------------------
//---------------------------
//---------------------------
(function($)
{
// Creating the sweetPages jQuery plugin:
$.fn.sweetPages = function(opts)
{
	// If no options were passed, create an empty opts object
	if(!opts) opts = {};

	var resultsPerPage = opts.perPage || 3;

	// The plugin works best for unordered lists,
	// although OLs would do just as well:
	var ul = this;
	var li = ul.find('li');

	li.each(function(){
		// Calculating the height of each li element,
		// and storing it with the data method:

		var el = $(this);
		el.data('height',el.outerHeight(true));
	});

	// Calculating the total number of pages:
	var pagesNumber = Math.ceil(li.length/resultsPerPage);

	// If the pages are less than two, do nothing:
	if(pagesNumber<2) return this;

	// Creating the controls div:
	var swControls = $('<div class="swControls">');

	for(var i=0;i<pagesNumber;i++)
	{
		// Slice a portion of the li elements, and wrap it in a swPage div:
		li.slice(i*resultsPerPage,(i+1)*resultsPerPage).wrapAll('<div class="swPage" />');

		// Adding a link to the swControls div:
		swControls.append('<a href="" id=swShowPage'+(i+1)+' class="swShowPage">'+(i+1)+'</a>');
	}

	ul.append(swControls);
	var maxHeight = 0;
	var totalWidth = 0;

	var swPage = ul.find('.swPage');
	swPage.each(function(){

		// Looping through all the newly created pages:

		var elem = $(this);

		var tmpHeight = 0;
		elem.find('li').each(function(){tmpHeight+=$(this).data('height');});

		if(tmpHeight>maxHeight)
			maxHeight = tmpHeight;

		totalWidth+=elem.outerWidth();

		elem.css('float','left').width(ul.width());
	});

	swPage.wrapAll('<div class="swSlider" />');

	// Setting the height of the ul to the height of the tallest page:
	ul.height(maxHeight);

	var swSlider = ul.find('.swSlider');
	swSlider.append('<div class="clear" />').width(totalWidth);

	var hyperLinkPrev = $('.arrowleft'); hyperLinkPrev.text(1);
	var hyperLinkNext = $('.arrowright'); hyperLinkNext.text(1);
	var hyperLinks = ul.find('a.swShowPage');
	// Mark the first link as active the first time the code runs:
	hyperLinks.eq(0).addClass('active');

	hyperLinks.click(function(e)
	{
		// If one of the control links is clicked, slide the swSlider div
		// (which contains all the pages) and mark it as active:
		$(this).addClass('active').siblings().removeClass('active');
		
		var indexNo = parseInt($(this).text());
		hyperLinkPrev.text(indexNo);
		hyperLinkNext.text(indexNo);
		//alert('indexNo = '+indexNo);

		swSlider.stop().animate({'margin-left': -(indexNo-1)*ul.width()},'slow');
		e.preventDefault();
	});
	
	hyperLinkPrev.click(function(e)
	{
		var indexNo = parseInt($(this).text()) - 1;
		//alert('indexNo = '+indexNo);
		if((indexNo>0)&&(indexNo<=pagesNumber))
		{
			hyperLinkPrev.text(indexNo);
			hyperLinkNext.text(indexNo);
			swSlider.stop().animate({'margin-left': -(indexNo-1)*ul.width()},'slow');
			// show the proper circle selected
			$('#swShowPage'+indexNo).addClass('active').siblings().removeClass('active');
		}
		e.preventDefault();
	});
	hyperLinkNext.click(function(e)
	{
		var indexNo = parseInt($(this).text()) + 1;
		//alert('indexNo = '+indexNo);
		if((indexNo>0)&&(indexNo<=pagesNumber))
		{
			hyperLinkPrev.text(indexNo);
			hyperLinkNext.text(indexNo);
			swSlider.stop().animate({'margin-left': -(indexNo-1)*ul.width()},'slow');
			// show the proper circle selected
			$('#swShowPage'+indexNo).addClass('active').siblings().removeClass('active');
		}
		e.preventDefault();
	});
	

	// Center the control div:
	swControls.css({
		'right':'0px',
		'margin-left':-swControls.width()/2
	});

	return this;

}})(jQuery);

