var loadAfterLogin=false;		//for reloading after login from login thickbox
							
function validateEmail(src) 
{
    var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
    return regex.test(src);
}
	
$(document).ready(function () 
{ 
	if($('#btnLogin') ) $('#btnLogin').attr('disabled', false);							
	
	var uID = $.cookie('customID')+""; 
	
	//alert('customID - '+ uID);
	
	if(uID !="null"){ 
		//alert(uID);
		if($.cookie('firstName').length > 1)
		{
			$('#username').html('<b>'+ $.cookie('firstName').toUpperCase() +'</b>');
		}
		else if($.cookie('firstName').length <= 1)
		{
			$('#username').html('<b>'+ $.cookie('lastName').toUpperCase() +'</b>');
		}
		$('#tblLogin').hide();
		$('#tblAfterLogin').show();
		$('#loginHead').html("Member area"); 
		
		$('#menuLogin').hide();
		$('#menuLogout').show();
		$('#myAccount').show();
		$('#trRegister').hide();
		
		//alert($.cookie('firstName')+"....."+$.cookie('lastName')+"........"+$.cookie('customID')+"........"+$.cookie('genderID'));
		
		if($.cookie('firstName').length > 1 && $.cookie('firstName')!='null')
		{
			$('#hrefMyAccount').html('Welcome ' + $.cookie('firstName').toUpperCase());
		}
		else if($.cookie('firstName').length <= 1 || $.cookie('firstName') == 'null')
		{
			if($.cookie('genderID') == 2)
			{
				var title= 'Ms. ';
			}
			else
			{
				var title= 'Mr. ';
			}
			$('#hrefMyAccount').html('Welcome ' + title + $.cookie('lastName').toUpperCase());
		}		
		
		$('#hrefMyAccount').attr('href', '/shop/my-account.php');
	}
	else{
		$('#menuLogin').show();
		$('#trRegister').show();
		$('#menuLogout').hide();		
		$('#hrefMyAccount').html('LOGIN');
		$('#hrefMyAccount').attr('href', '/shop/my-account.php');
	}
	
	/* display cart value.. need to write in cookie.. reads from shop/theme/defaulttheme/header.tpl*/
	if( $('#cartQty') !=undefined && $('#cartValue') !=undefined) {
		 $.cookie('cartQ', $('#cartQty').val(), {path: '/' } );
		 $.cookie('cartA', $('#cartValue').val(), {path: '/'} ); 		 
	}
	 
		 
	var xQ = "";
	var xA ="";
	
	xQ = $.cookie('cartQ')+"";
	xA = $.cookie('cartA')+""; 
	
	if(xQ=="" || xQ=="null") {
		xQ="0"; 
	}
	else {
		$('#hrefViewCart').attr('href', '/shop/order.php');
	}
	
	if(xA=="" || xA=="null") xA="$00.00";
	
	$('#spnItem').html(xQ); 
	$('#spnAmount').html(xA); 
	
	/*END*/ 
	
	//display banners
		//alert($('#hidBannerName').val());
		if($('#hidBannerName').val() != undefined && $('#hidBannerName').val() != '')
		{
			bName = $('#hidBannerName').val().split("~");
			sName = $('#hidSectionName').val().split("~");
			wUrl = $('#hidWebsiteUrl').val().split("~");
			bId = $('#hidBannerId').val().split("~");
			
			
			for(i=0; i<(bName.length-1); i++)
			{
				var width;
				var height;
				
				//alert(sName[i]+'.....'+bName[i]);
				if(bName[i]!='')
				{
					if(sName[i] == '_top_left')
					{
						width='500';
						height='80';
					}
					if(sName[i] == '_top_right')
					{
						width='234';
						height='60';
					}
					if(sName[i] == '_left')
					{
						width='125';
						height='125';
					}
					if(sName[i] == '_right' && $('#hidCode').val() == 'home')
					{
						width='250';
						height='250';
					}
					else if(sName[i] == '_right' && $('#hidCode').val() != 'home')
					{
						width='125';
						height='125';
					}
					if(sName[i] == '_bottom_left')
					{
						width='728';
						height='90';
					}
					if(sName[i] == '_bottom_right')
					{
						width='234';
						height='90';
					}
					
					
					if(bName[i].indexOf('swf') >= 0)
					{
						$('#'+sName[i]).html('<center ><a href="javascript:;" onclick="changeBannerHit('+bId[i]+', '+"'"+wUrl[i]+"'"+')"><object classid="clsid:166B1BCA-3F9C-11CF-8075-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,0,0" width="'+width+'" height="'+height+'" ><param name="src" value="/images/banner/'+bName[i]+'" /><embed src="/images/banner/'+bName[i]+'" pluginspage="http://www.macromedia.com/shockwave/download/" width="'+width+'" height="'+height+'"></embed></object></a></center>');
						$('.'+sName[i]).show();
					}
					else
					{
						$('#'+sName[i]).html('<center ><a href="javascript:;" onclick="changeBannerHit('+bId[i]+', '+"'"+wUrl[i]+"'"+')"><img src="/images/banner/'+bName[i]+'" width="'+width+'" height="'+height+'"></a></center>');
						$('.'+sName[i]).show();
					}
				}
			}
		}
			
		if($('#_top_left').html() == '')	
		{
			$('#_top_left').html('<center ><img src="/images/standard banners/_top_left.jpg"></center>');
			$('._top_left').show();
		}
		if($('#_top_right').html() == '')	
		{
			$('#_top_right').html('<center ><img src="/images/standard banners/_top_right.jpg"></center>');
			$('._top_right').show();
		}
		//if($('#_left').html() == '' && ($('#hidCode').val() == 'manufacturers' || $('#hidCode').val() == 'dealers' || $('#hidCode').val() == 'Buy Scales - Level I' || $('#hidCode').val() == 'Buy Scales - Level II' || $('#hidCode').val() == 'Buy Scales - Level III' || $('#hidCode').val() == 'News and Events' || $('#hidCode').val() == 'My Account' || $('#hidCode').val() == 'Industry Jobs' || $('#hidCode').val() == 'resources' || $('#hidCode').val() == 'Services' || $('#hidCode').val() == 'Classified' || $('#hidCode').val() == 'Other'))	
		if($('#_left').html() == '' && ($('#hidCode').val() != 'home'))	
		{
			$('#_left').html('<center ><img src="/images/standard banners/_left.jpg"></center>');
			$('._left').show();
		}
		if($('#_right').html() == '')	
		{
			$('#_right').html('<center ><img src="/images/standard banners/_right.jpg"></center>');
			$('._right').show();
		}
		if($('#_bottom_left').html() == '')	
		{
			$('#_bottom_left').html('<center ><img src="/images/standard banners/_bottom_left.jpg"></center>');
			$('._bottom_left').show();
		}
		if($('#_bottom_right').html() == '')	
		{
			$('#_bottom_right').html('<center ><img src="/images/standard banners/_bottom_right.jpg"></center>');
			$('._bottom_right').show();
		}

		//alert($('#hidCode').val());
		if($('#hidCode').val() == 'home')
			$('#aFaq').attr('href', '/faq.php');
		else if($('#hidCode').val() == 'manufacturers' || $('#hidCode').val() == 'dealers')
			$('#aFaq').attr('href', '/faq.php?cat=directory');
		else if($('#hidCode').val() == 'Buy Scales - Level I' || $('#hidCode').val() == 'Buy Scales - Level II' || $('#hidCode').val() == 'Buy Scales - Level III')
			$('#aFaq').attr('href', '/faq.php?cat=buy_scales');
		else if($('#hidCode').val() == 'Classified')
			$('#aFaq').attr('href', '/faq.php?cat=classified');
		else if($('#hidCode').val() == 'Industry Jobs')
			$('#aFaq').attr('href', '/faq.php?cat=job');
		else if($('#hidCode').val() == 'News and Events')
			$('#aFaq').attr('href', '/faq.php?cat=news');
		else if($('#hidCode').val() == 'resources')
			$('#aFaq').attr('href', '/faq.php?cat=resources');
		else if($('#hidCode').val() == 'Services')
			$('#aFaq').attr('href', '/faq.php?cat=services/Support');
		else if($('#hidCode').val() == 'My Account')
			$('#aFaq').attr('href', '/faq.php?cat=my_account');
		else
			$('#aFaq').attr('href', '/faq.php');
		
		/*..... check browser compatibility .......*/
		if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))  	//test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
		{
			var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
			if (ffversion<3)
			alert("You're using an older version of firefox. Please update your browser.");
		}
	
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
			 var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
			 if (ieversion<7)
			  alert("You're using an older version of internet explorer. Please update your browser.");
		}
		
		$('.rsslinks:eq(1)').html('');
		$('.rsslinks:eq(2)').html('');
	
});

/*.......................................translate language...................................................................*/
	
	jQuery(function($){ //when DOM is ready

	$.translate(function(){  //when the Google Language API is loaded
  	
    function translateTo( destLang ){ //this can be declared in the global scope too if you need it somewhere else
       
		$('body').translate( 'english', destLang, {   //translate from english to the selected language
          not: '.jq-translate-ui',  //by default the generated element has this className
          fromOriginal:true   //always translate from english (even after the page has been translated)
        });
    }
    
    
    var destLang = $.cookie('destLang'); //get previously translated language
    
    if( destLang )  //if it was set then
        translateTo( destLang );

  }); //end of Google Language API loaded	
		
}) //end of DOM ready

function translateNow(dLang)
{
	$.cookie('destLang', dLang, { path: '/' } );	
	location.reload();
	
}
	
	
/*..........................................................................................................*/

var blogEmail='';
 
 function thickboxCheckLogin()
{
	var email = $('#txtEmail').val();
	var pass = $('#txtPasswd').val();
	
	blogEmail=email;

	if(validateEmail(email))
		if(	pass !=""){
			$('#thkBtnLogin').val('Please wait...');
			$('#thkBtnLogin').attr('disabled', true);
			$.ajax({type: "GET", url: "/loginProcess.php?email="+email+"&password="+pass, success:thickboxCheckLoginResponse});	
		}
		else
			alert("Please enter password");	
	else
		alert("Please valid email address ");
}
 

function thickboxCheckLoginResponse(data)
{ 
	$('#thkBtnLogin').val('Login');
	$('#thkBtnLogin').attr('disabled', false);
		
	if(data=="Hack attempt" || data=="failed"){	 
		alert("Invalid email or password, please try again")
	}
	else
	{
		data = data.split("~"); 
		
		if(data[1].length > 1)
		{
			$('#username').html('<b>'+ data[1] +'</b>');
			$('#hrefMyAccount').html('Welcome ' + data[1].toUpperCase());
		}
		else if(data[1].length <= 1)
		{
			$('#username').html('<b>'+ data[0] +'</b>');
		}
		
		$('#tblLogin').hide();
		$('#tblAfterLogin').show('slow');
		$('#loginHead').html("Member area");
		
		$('#menuLogin').hide();
		$('#menuLogout').show();
		$('#myAccount').show();
		$('#menuLogin').hide();
		
		
		if(loadAfterLogin){
			loadAfterLogin=false;
			
			$.ajax({type: "GET", url: "/blogAutoLogin.php?email="+blogEmail, success:blogAutoLoginThickboxResponse});
		
			//alert($.cookie('lastName'));
			//document.location.reload();
			//window.location='/shop/my-account.php';
		}
	
	} 
}
 
 
function checkLogin()
{
	var email = $('#email').val();
	var pass = $('#passwd').val();
	
	blogEmail=email;

	if(validateEmail(email))
		if(	pass !=""){
			$('#btnLogin').val('Please wait...');
			$('#btnLogin').attr('disabled', true);
			$.ajax({type: "GET", url: "/loginProcess.php?email="+email+"&password="+pass, success:checkLoginResponse});	
		}
		else
			alert("Please enter password");	
	else
		alert("Please valid email address ");
}

function checkLoginResponse(data)
{ 
	$.ajax({type: "GET", url: "/blogAutoLogin.php?email="+blogEmail, success:blogAutoLoginResponse});
	
	$('#btnLogin').val('Login');
	$('#btnLogin').attr('disabled', false);
		
	if(data=="Hack attempt" || data=="failed"){	 
		alert("Invalid email or password, please try again")
	}
	else
	{
		data = data.split("~"); 
		
		if(data[1].length > 1)
		{
			$('#username').html('<b>'+ data[1] +'</b>');
			$('#hrefMyAccount').html('Welcome ' + data[1].toUpperCase());
		}
		else if(data[1].length <= 1)
		{
			$('#username').html('<b>'+ data[0] +'</b>');
			if($.cookie('genderID') == 2)
			{
				var title= 'Ms. ';
			}
			else
			{
				var title= 'Mr. ';
			}
			$('#hrefMyAccount').html('Welcome ' + title + data[0].toUpperCase());
		}
		
		$('#tblLogin').hide();
		$('#tblAfterLogin').show('slow');
		$('#loginHead').html("Member area");
		
		$('#menuLogin').hide();
		$('#menuLogout').show();
		$('#myAccount').show();
		$('#trRegister').hide();
		//$.cookie('lastName', data[0]);
		//$.cookie('customID', data[1], '/');
		
			
	 
		if(loadAfterLogin){
			loadAfterLogin=false;	
			document.location.reload();
		}
	} 
}

function blogAutoLoginResponse(data)
{
		
}

function blogAutoLoginThickboxResponse(data)
{
		window.location='/shop/my-account.php';		
}



function moveLeft(){
	slideCarousel($('div.carouselWrapper','#largeCarousel'),'-');	
}

function moveRight(){
	slideCarousel($('div.carouselWrapper','#largeCarousel'),'-');
}

function slideCarousel (elm, dir) {
	var dir = dir;
	var offset = elm.width();
	elm.animate({scrollLeft: dir + '=' + offset + 'px'}, 1000, 'easeOutQuad');
}
 


function showTab(tb, ob)
{
	//aler('asd');
	$('#dvDescription').hide();
	$('#dvSpecialDesc').hide();
	
	$('#'+tb).show();
	$('#tb1').attr('style', 'color:black;') ;
	$('#tb2').attr('style', 'color:black;') ;
	
	if($(ob).attr('id')=='tb2')
	{
		$('#tb2').attr('class', 'tab_new') ;
		$('#tb1').attr('class', 'inactive_tab') ;
	}
	else if($(ob).attr('id')=='tb1')
	{
		$('#tb2').attr('class', 'inactive_tab') ;
		$('#tb1').attr('class', 'tab_new') ;
	}
	
	$(ob).attr('style', 'color:red;') 
}


//show extra images in the directory page..
function showImages(adv, im)
{   
    imgs = $('#'+adv +'_dv .extraImages');        
    $(imgs).each(function (i) {$(this).hide(); });    
    $('#'+adv +'_'+ im +'_img').show();    
} 

var recLimit=10;
var country='';
var searchFlag=false;

function getDirectory(ob, re)
{	
	btnName=ob; 
	var dirState='';
	currentPage=1;
	atype = getParameter("atype");
	reg = getParameter("reg");
	showPlanId = getParameter("showPlanId");
	
	if(re=="limit"){		//change the quesry limit only
		var x = {re:'limit', recLimit:recLimit, reg:reg, atype:atype, country:country, showPlanId:showPlanId};
		$.ajax({type: "GET", url: "/includes/getDirectory.php", data:x, success:getDirectoryData});	    
		return; 
	}
	 
	  
	country= $('#country').val().trim();
 	if(whichState !="") dirState = $(whichState).val(); 
	 
	if(country=="Select") country='';
	if(dirState=="Select" ||  dirState=="") dirState='n/a';

	if(searchType=="b"){		//business ssearch 

		catorName = $('#txtDirectorySearch').val().trim();
		city  = $('#txtDirectoryCity').val().trim();
		zip   = $('#txtDirectoryZip').val().trim(); 
		state = dirState;
		
		var default_location = $("input[@id=defaultLocation]:checked").length;
				
		if (default_location != 0) 
		{
			$.cookie('saveDefault', 'checked'); 
			$.cookie('defaultState', state);
			$.cookie('defaultCity', city);
			$.cookie('defaultZip', zip);
			$.cookie('defaultName', catorName);
		}	
		else
		{
			$.cookie('saveDefault', "");
			$.cookie('defaultState', "");
			$.cookie('defaultCity', "");
			$.cookie('defaultZip', "");
			$.cookie('defaultName', "");
		}
		
		if(catorName =="" && city == "" && zip == "" && state == "" && country=="")
		{
			alert("please enter atleast one field ");	
			return;
		}	
		else{
			$('#dvFeatured').hide();
	
			var x = {catorName:catorName, city:city, zip:zip, state:state, searchType:searchType, reg:reg, atype:atype, recLimit:recLimit, country:country, showPlanId:showPlanId};
	        $.ajax({type: "GET", url: "/includes/getDirectory.php", data:x, success:getDirectoryData});	    
		}
	}
	
	if(searchType=="p"){		//people ssearch 
		peopleFirstName = $('#txtDirectoryFirstName').val().trim();
		peopleLastName = $('#txtDirectoryLastName').val().trim();
		peopleCity = $('#peopleDirectoryCity').val().trim();
		peopleZip = $('#peopleDirectoryZip').val().trim();
		peopleState=dirState.trim();
			
		if(peopleFirstName =="" && peopleLastName == "" && country=="")
		{
			alert("please enter the first name or last name ");	
			return;
		}
		else{
			var x = {peopleFirstName:peopleFirstName, peopleLastName:peopleLastName, peopleCity:peopleCity, peopleZip:peopleZip, peopleState:peopleState, searchType:searchType, reg:reg, atype:atype, recLimit:recLimit, country:country, showPlanId:showPlanId};
	        $.ajax({type: "GET", url: "/includes/getDirectory.php", data:x, success:getDirectoryData});	    
		}
	}
		
	if(searchType=="r" && re =='ph')	//reverse lookup - phone
	{
		phoneNumber = $('#txtPhoneNumber').val().trim();
		
		if(phoneNumber =="" && country==""){
			alert("please fill in the required fields");
			return;
		}
		else
		{
			var x = {phoneNumber:phoneNumber, searchType:searchType, reg:reg, atype:atype, re:'ph', recLimit:recLimit, country:country, showPlanId:showPlanId};
			$.ajax({type: "GET", url: "/includes/getDirectory.php", data:x, success:getDirectoryData});
		}
	}
	
	if(searchType=="r" && re =='ad')	{		//reverse lookup - street, zip or steat
		streetAddress = $('#reverseDirectoryStreet').val().trim();
		reverseCity = $('#reverseDirectoryCity').val().trim();
		reverseZip = $('#reverseDirectoryZip').val().trim();
		reverseState=dirState.trim();
		if(streetAddress =="" && reverseCity=="" && reverseZip=="" && country==""){
			alert("please fill in the required fields");
			return;
		}
		else
		{
			var x = {streetAddress:streetAddress, reverseCity:reverseCity, reverseZip:reverseZip, reverseState:reverseState, searchType:searchType, reg:reg, atype:atype, re:'ad', recLimit:recLimit, country:country, showPlanId:showPlanId};
			$.ajax({type: "GET", url: "/includes/getDirectory.php", data:x, success:getDirectoryData});	    
		}
	} 
				
	if(searchType=="a"){		//area/zip search 
		areaOrZip = $('#txtAreaOrZipCode').val().trim();
 			
		if(areaOrZip =="" && country==""){
			alert("please enter the area/zip code ");
			return;
		}
		else{
			var x = {areaOrZip:areaOrZip, searchType:searchType, reg:reg, atype:atype, recLimit:recLimit, country:country, showPlanId:showPlanId};
	        $.ajax({type: "GET", url: "/includes/getDirectory.php", data:x, success:getDirectoryData});	    
		}	
	}
	
	if(searchType=="i"){		//area/zip search 
		dirID = $('#txtID').val().trim();
 			
		if(dirID =="" && country==""){
			alert("please enter the ID ");
			return;
		}
		else{
			var x = {dirID:dirID, searchType:searchType, reg:reg, atype:atype, recLimit:recLimit, country:country, showPlanId:showPlanId};
	        $.ajax({type: "GET", url: "/includes/getDirectory.php", data:x, success:getDirectoryData});	    
			}	
	}
	
	$(ob).val('Searching...');
}

var btnName;

function getDirectoryData(data)
{
	$("#dvDirectory").html(data);	
	$(btnName).val('Search'); 
	searchFlag=true;
	startLimit=0;
}

function changeLimit(ob)
{
	recLimit = $(ob).val();
	getDirectory(null, 'limit');
}

function changeCountry(ob)
{
	country = $(ob).val();
	getDirectory(null, 'country');
}

var searchType="b";
function activateTab(ob, tp)
{
    $('.tab_search').attr('class', 'inactive_tab_search'); 
    $(ob).attr('class', 'tab_search');  
    searchType = tp;
	
	$('.directorySearchClass').hide();
	
	if(tp=="b")
	{
		$('#businessSearch').show();
		$('#txtDirectorySearch').focus();
	}	
		
	if(tp=="p")
	{
		$('#peopleSearch').show();
		$('#txtDirectoryFirstName').focus()
	}	
		
	if(tp=="r")
	{
		$('#reverseSearch').show();
		$('#txtPhoneNumber').focus()
	}	
		
	if(tp=="a")
	{
		$('#areaOrZipSearch').show();		
		$('#txtAreaOrZipCode').focus()
	}	
	
	if(tp=="i")
	{
		$('#idSearch').show();		
		$('#txtID').focus()
	}	
		
}

/*var type;
function tabActivate(ob, type, r_type, newsId)
{ 
	if(type=='wn')
	{
		//alert(type);
		$('#w_newsTd').attr('class', 'tab_new');
		$('#eventsTd').attr('class', 'inactive_tab');
		$('#i_newsTd').attr('class', 'inactive_tab');
		$('#s_newsTd').attr('class', 'inactive_tab');
		$('#news').show();
		//$('#newsContent').show();
		$('#wn_news').show();
		$('#sn_news').hide();
		$('#in_news').hide();
		$('#events').hide();
		$('#gotNews').show(); 
		$('#postEvents').hide(); 

		if(newsId != "")
		{
			if(type != r_type)
				var x= {type:type};
			else
				var x= {type:type, newsId:newsId};
				
			
			$("#newsContent").html('<center><br><br><br><br><br><img src="/images/loader.gif"></center>');
			$.ajax({type: "GET", url: "/news/get_news.php", data:x, success:getNewsData});
			
		}
	}
	
	if(type=='in')
	{	
		$('#i_newsTd').attr('class', 'tab_new');
		$('#eventsTd').attr('class', 'inactive_tab');
		$('#w_newsTd').attr('class', 'inactive_tab');
		$('#s_newsTd').attr('class', 'inactive_tab');
		$('#news').show();
		//$('#newsContent').show();
		$('#in_news').show();
		$('#sn_news').hide();
		$('#wn_news').hide();
		$('#events').hide();
		$('#gotNews').show(); 
		$('#postEvents').hide(); 

		if(newsId != "")
		{
			if(type != r_type)
			{
				var x= {type:type};
			}
			else
			{
				var x= {type:type, newsId:newsId};
			}	
			
			$("#newsContent").html('<center><br><br><br><br><br><img src="/images/loader.gif"></center>');
			$.ajax({type: "GET", url: "/news/get_news.php", data:x, success:getNewsData});
		}
	}
	
	if(type=='sn')
	{
		$('#s_newsTd').attr('class', 'tab_new');
		$('#eventsTd').attr('class', 'inactive_tab');
		$('#i_newsTd').attr('class', 'inactive_tab');
		$('#w_newsTd').attr('class', 'inactive_tab');
		$('#news').show();
		//$('#newsContent').show();
		$('#sn_news').show();
		$('#wn_news').hide();
		$('#in_news').hide();
		$('#events').hide();
		$('#gotNews').show(); 
		$('#postEvents').hide(); 
		
		if(newsId != "")
		{
			if(type != r_type)
			{
				var x= {type:type};
			}
			else
			{
				var x= {type:type, newsId:newsId};
			}
			
			$("#newsContent").html('<center><br><br><br><br><br><img src="/images/loader.gif"></center>');	
			$.ajax({type: "GET", url: "/news/get_news.php", data:x, success:getNewsData});				
		}
	}
	
	if(type=='e')
	{
		$('#eventsTd').attr('class', 'tab_new');
		$('#w_newsTd').attr('class', 'inactive_tab');
		$('#i_newsTd').attr('class', 'inactive_tab');
		$('#s_newsTd').attr('class', 'inactive_tab');
		$('#events').show();
		$('#news').hide();
		$('#postEvents').show(); 
		$('#gotNews').hide(); 
	}

}

function getNewsData(data)
{
	
	$("#newsContent").html(data);	
}

var op='all';
function searchEvent(type)
{
	//alert('alert');
	type=type;
	op = $('#searchOption').val().trim();
	keyword = $('#keyword').val().trim();
	var x = {type:type, op:op, keyword:keyword};
	$.ajax({type: "GET", url: "/news/search_event.php", data:x, success:searchEventData});	    
}


//shop/product.php
function searchEventData(data)
{
	$("#eventsContent").html(data);	
}*/


function showBigPictures(pic, thick)
{  
	$('#bigpic').attr('src', pic);
	$('#hrefBigPic').attr('href', thick);
}

function showProducts(ob)
{
	document.location.href='/shop/product.php?id_product='+ $(ob).val();	
}


function showState(ob)
{
	setDefault =0;
	
	if(ob ==undefined || ob ==null){
		ob = $("#country");
		setDefault =1;
	}
	
	//alert(setDefault);
	
	if( $(ob).val()=="USA" || $(ob).val()=="Canada")
	{
		$("#otherState").hide();
		$("#States").show();		
		
		if( $(ob).val()=="Canada")
		{ 
			var elSel = document.getElementById('selStateProvince');
			var i;
			for (i = elSel.length - 1; i>=0; i--) 
			{
				//console.log( elSel.options[i].value );
				nm = elSel.options[i].value;
				
				if (nm.length <= 2 ) 
				  $(elSel.options[i]).hide();
				else
					$(elSel.options[i]).show();
			}
			
			if(setDefault==0) elSel.options[62].selected=true;
		}
		
		if( $(ob).val()=="USA")
		{ 
			var elSel = document.getElementById('selStateProvince');
			var i;
			for (i = elSel.length - 1; i>=0; i--) {
				//console.log( elSel.options[i].value );
				nm = elSel.options[i].value;
				
				if (nm.length == 2 )
				  $(elSel.options[i]).show();
				else
					$(elSel.options[i]).hide();
			}
			
			if(setDefault ==0){
				elSel.options[1].selected=true;
			}
		}
		
	}
	else{
		$("#otherState").show();
		$("#States").hide();
	}
	
} 
 

var whichState;

function changeState(ob)
{
	if(ob ==undefined || ob ==null) 
		ob = $("#country");

	whichState ="#otherstate";
	
	if($(ob).val() == 'Canada')
	{	
		$("#selStateProvince").hide();
		$("#selectCanadaState").show();

		whichState ="#selectCanadaState";
	}

	if($(ob).val() == 'USA')
	{
		$("#selStateProvince").show();
		$("#selectCanadaState").hide();

		whichState ="#selStateProvince";
	}	
	 
	
	if( $(ob).val()=="USA" || $(ob).val()=="Canada")
	{
		$("#otherState").hide();
		$("#States").show();	
	}
	else{
		$("#otherState").show();
		$("#States").hide();
	}
	 

	if( $(ob).val()=="")
	{
		$("#otherState").hide(); 
		$("#States").hide(); 
		whichState="";
	}

	$('.defaultClass').show();
}


function changeNewsState(ob)
{
	if(ob ==undefined || ob ==null){
		ob = $("#newsCountry");
	
		if($(ob).val() == 'Canada')
		{
			$("#newsSelStateProvince option").removeAttr("selected");
			$("#newsSelStateProvince option").hide()
			$('.canadaState').show();
 			
		}
		if($(ob).val() == 'USA')
		{
			$("#newsSelStateProvince option").removeAttr("selected");
			$("#newsSelStateProvince option").hide()
 			$('.usaState').show();
			
		}
	}	
	else
	{
		if($(ob).val() == 'Canada')
		{	
			//$("#newsSelStateProvince option").removeAttr("selected");
			//$("#newsSelStateProvince option").hide()
			$('.canadaState').show();
			$("#newsSelStateProvince option[value='Select']").attr('selected', 'selected');
			$('.usaState').hide();
			
		}
		else if($(ob).val() == 'USA')
		{
			//$("#newsSelStateProvince option").removeAttr("selected");
			//$("#newsSelStateProvince option").hide()
			$('.canadaState').hide();
			$("#newsSelStateProvince option[value='Select']").attr('selected', 'selected');
			$('.usaState').show();
			
		}
		else
		{
			$('#newsotherstate').val('');	
		}
	}
	
	if( $(ob).val()=="USA" || $(ob).val()=="Canada")
	{
		$("#newsOtherState").hide();
		$("#newsStates").show();
	}
	else{
		$("#newsOtherState").show();
		$("#newsStates").hide();
	}
	
	$('.defaultClass').show();
}


/*SYSTEM FUNCS*/

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}


var qs; 
      
function getParameter(s) 
{
    if (qs===undefined) 
    {
	    var q = location.search;
	    q = q.substring(1, q.length);
	    var a = q.split("&");
	    qs = new Object();
	    if (a.length>0) {
		    for(var i=0; i<a.length; i++) {
			    var p = a[i].indexOf('=');
			    if (p > 0) {
				    var key = a[i].substring(0,p);
				    var value = a[i].substring(p+1);
				    qs[key] = value;
			    }
		    }
    	}
	}
	
    var v = qs[s];
    
    if (v===undefined) 
	    v = "";
	    
return v;
}
 
 
function checkZipcode(s)
{
	value = s;	//s.value.trim(); 
 	
	var USrexp = /(^\d{5}$)|(^\d{5}-\d{4}$)/ ;
	var CArexp = /(^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$)|(^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$)/;
	if(!(value == '') && !USrexp.test(value) && !CArexp.test(value))
	 	return false;
 	else 
		return true; 
}

function logout()
{
	var cookie = document.cookie.split(/;\s*/);
	for(var i=0;i<cookie.length;i++){
		var cName = cookie[i].split("=")[0];  
		document.cookie=cName+"=; path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
		document.cookie=cName+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
	}	 
	
	$.cookie("lastName", "null");
	$.cookie("customID", "null");
	$.cookie("userid", "null");	
	
	document.location.href="/shop/"
}


//usage
function enable_submit(status)
{
	status=!status; 
	$("input[@name='submit']").attr('disabled',status);

}


function submitTemp()
{
		
}



function html_entity_decode(str) {
  return str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
} 

function showAdminMessage(nm, cn)
{
	//alert( unescape(nm) );
	var strURL = html_entity_decode(nm) ;
	$("#cn_"+cn).html( strURL ); 	
}

//formatting currency

function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}

//function to implaement back button
function getPreviousPage()
{
	window.history.back(1);
}



//form grid with table and apply pagination
function ShowGrid()
	{
			if($('.GridTable').length)
			{ 
				var xCount = $('.GridTable')[0].rows.length; 
				
				if(xCount>=1){
					$('.GridTable').jTPS( {scrollStep:1, scrollDelay:30} );
						$('.GridTable tbody tr:not(.stubCell)').bind('mouseover mouseout',
							function (e) { e.type == 'mouseover' ? $(this).children('td').addClass('hilightRow') : $(this).children('td').removeClass('hilightRow'); }
					);
			   }
			   else
			   {
					var firstRow = $('.GridTable')[0].rows[0];
					var secondRow = $('.GridTable')[0].rows[1];
					
					var secondRows = secondRow.cells[0];
					
					$(firstRow).hide();
					$(secondRows).html('<br><center><span class="noRecords">No record found !</span> </center> <br>');
					  
			   }	  
			}	
	}
	

	
function ShowGridNew()
	{
			if($('.GridTable').length)
			{ 
				var xCount = $('.GridTable')[0].rows.length; 
				
				if(xCount>=1){
					$('.GridTable').jTPS( {scrollStep:1, scrollDelay:30} );
						$('.GridTable tbody tr:not(.stubCell)').bind('mouseover mouseout',
							function (e) { e.type == 'mouseover' ? $(this).children('td').addClass('hilightRow') : $(this).children('td').removeClass('hilightRow'); }
					);
			   }
			  /* else
			   {
					var firstRow = $('.GridTable')[0].rows[0];
					var secondRow = $('.GridTable')[0].rows[1];
					
					var secondRows = secondRow.cells[0];
					
					$(firstRow).hide();
					$(secondRows).html('<br><center><span class="noRecords">No record found !</span> </center> <br>');
					  
			   }*/	  
			}	
	}	
	
//format date with javascript

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {
	return(x<0||x>9?"":"0")+x
	}
	
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}
	
	
//change banner hit
function changeBannerHit(bId, wUrl)
{
	var x = {bId:bId, wUrl:wUrl};
	$.ajax({type: "GET", url: "/banner/changeBannerHit.php", data:x, success:changeBannerHitResponse});	    
	
	if(wUrl.trim() != '')
		window.open('http://'+wUrl.trim(),'','toolbar=yes, location=yes, directories=yes, scrollbars=yes, status=yes, menubar=yes, copyhistory=yes, resizable=yes') ;	
}

function changeBannerHitResponse(data)
{
	/*if(data.trim() != '')
	{
		window.open('http://'+data.trim(),'','width=900,height=600, scrollbars=1') ;
	}*/
}	


var startLimit=0;
var currentPage=1;



function getNextRecords(totalPages)
{ 
	if((currentPage+1) > totalPages)
	{
		alert('No further records found !');
		return false;
	}
	$('#spLoadingImage').show();
	
	startLimit=startLimit+10;	
	currentPage=parseInt(currentPage) + 1;
	
	atype = getParameter("atype");
    reg = getParameter("reg");
	showPlanId = getParameter("showPlanId");

	var x = {startLimit:startLimit, atype:atype, reg:reg, searchFlag:searchFlag, showPlanId:showPlanId};
	$.ajax({type: "GET", url: "/includes/getDirectory.php", data:x, success:showNextRecords});
}

function showNextRecords(data)
{
	$("#dvDirectory").html(data);
	$('#currentPage').html(currentPage);
	$('#spLoadingImage').hide();
}

function getPreviousRecords()
{
	if(startLimit <= 0)
	{
		alert('No records found !');
		return false;
	}
	$('#spLoadingImage').show();
	
	startLimit=startLimit-10;
	currentPage=parseInt(currentPage)-1;
	atype = getParameter("atype");
    reg = getParameter("reg");
	showPlanId = getParameter("showPlanId");
	var x = {startLimit:startLimit, atype:atype, reg:reg, searchFlag:searchFlag, showPlanId:showPlanId};
	$.ajax({type: "GET", url: "/includes/getDirectory.php", data:x, success:showPreviousRecords});
}

function showPreviousRecords(data)
{
	$("#dvDirectory").html(data);
	$('#currentPage').html(currentPage);
	$('#spLoadingImage').hide();
}

function getPageNumber(totalPages)
{
	if(isNaN($('#txtPageNo').val()) || $('#txtPageNo').val().indexOf('.') != -1)
	{
		alert('Please enter a valid page number');
		return false;
	}
	
	if($('#txtPageNo').val() <= 0)
	{
		alert('Please enter a value greater than zero');
		return false;
	}
	
	if($('#txtPageNo').val() > totalPages)
	{
		alert('Please enter a value less than or eqal to '+totalPages);
		return false;
	}
	$('#spLoadingImage').show();
	
	currentPage=parseInt($('#txtPageNo').val());
	startLimit=$('#txtPageNo').val()*10-10;
	atype = getParameter("atype");
    reg = getParameter("reg");
	showPlanId = getParameter("showPlanId");
	var x = {startLimit:startLimit, atype:atype, reg:reg, searchFlag:searchFlag, showPlanId:showPlanId};
	$.ajax({type: "GET", url: "/includes/getDirectory.php", data:x, success:showPageNumber});
}

function showPageNumber(data)
{
	$("#dvDirectory").html(data);
	$('#currentPage').html(currentPage);
	$('#spLoadingImage').hide();
	
}

function checkEnter(e)
{ 
	var characterCode
	//e = event
	characterCode = e.keyCode
	if(characterCode == 13)
	{
		$('#btnGoToPage').click();	
	}
}	


function clearGlobalText()
{
	if( $('#txtGlobalSearch').val()=="Search")
		$('#txtGlobalSearch').val("");
}

function checkGlobalText()
{
	if( $('#txtGlobalSearch').val()=="")
		$('#txtGlobalSearch').val("Search");
}

function checkGlobalEnter(e)
{ 
	var characterCode
	//e = event
	characterCode = e.keyCode
	if(characterCode == 13)
	{
		$('#btnGlobalSearch').click();	
	}
}

function globalSearch()
{
	if($('#txtGlobalSearch').val() != '' && $('#txtGlobalSearch').val() != 'Search')
	{
		if($('#selectModule :selected').val() == '')
		{
			alert('Please select a category');
			return false;
		}
		var strSearchText=$('#txtGlobalSearch').val();
		
		window.location='/topSearch.php?searchAgainst='+strSearchText+'&cat='+$('#selectModule :selected').val();
		
	}
	else
	{
		alert('Please enter a keyword to search');
		$('#txtGlobalSearch').val('');
		$('#txtGlobalSearch').focus();
		return false;
	}
}


function selectGlobalsearch()
{
	if($('#selectModule :selected').val() != '')
		window.location=$('#selectModule :selected').val();
}

/*
//add a combination of attributes in the global JS sytem
function addCombination(idCombination, arrayOfIdAttributes, quantity, price, ecotax, id_image, reference)
{
	globalQuantity += quantity;

	var combination = new Array();
	combination['idCombination'] = idCombination;
	combination['quantity'] = quantity;
	combination['idsAttributes'] = arrayOfIdAttributes;
	combination['price'] = price;
	combination['ecotax'] = ecotax;
	combination['image'] = id_image;
	combination['reference'] = reference;
	combinations.push(combination);
}
*/

var startLimitGlobal=0;
var currentPageGlobal=1;

function getNextRecordsGlobal(totalPages)
{ 
	if((currentPageGlobal+1) > totalPages)
	{
		alert('No further records found !');
		return false;
	}
	$('#spLoadingImage').show();
	
	startLimitGlobal=startLimitGlobal+5;	
	currentPageGlobal=parseInt(currentPageGlobal) + 1;
	
	cat = getParameter("cat");
    searchAgainst=getParameter("searchAgainst");
	
	var x = {startLimitGlobal:startLimitGlobal, cat:cat, searchAgainst:searchAgainst};
	$.ajax({type: "GET", url: "globalDirSearch.php", data:x, success:showNextRecordsGlobal});
}

function showNextRecordsGlobal(data)
{
	$("#dvDirectory").html(data);
	$('#currentPage').html(currentPageGlobal);
	$('#spLoadingImage').hide();
}

function getPreviousRecordsGlobal()
{
	if(startLimitGlobal <= 0)
	{
		alert('No records found !');
		return false;
	}
	$('#spLoadingImage').show();
	
	startLimitGlobal=startLimitGlobal-5;
	currentPageGlobal=parseInt(currentPageGlobal)-1;
	
	cat = getParameter("cat");
    searchAgainst=getParameter("searchAgainst");
	
	var x = {startLimitGlobal:startLimitGlobal, cat:cat, searchAgainst:searchAgainst};
	$.ajax({type: "GET", url: "globalDirSearch.php", data:x, success:showPreviousRecordsGlobal});
}

function showPreviousRecordsGlobal(data)
{
	$("#dvDirectory").html(data);
	$('#currentPage').html(currentPageGlobal);
	$('#spLoadingImage').hide();
}

function getPageNumberGlobal(totalPages)
{
	if(isNaN($('#txtPageNo').val()) || $('#txtPageNo').val().indexOf('.') != -1)
	{
		alert('Please enter a valid page number');
		return false;
	}
	
	if($('#txtPageNo').val() <= 0)
	{
		alert('Please enter a value greater than zero');
		return false;
	}
	
	if($('#txtPageNo').val() > totalPages)
	{
		alert('Please enter a value less than or eqal to '+totalPages);
		return false;
	}
	$('#spLoadingImage').show();
	
	currentPageGlobal=parseInt($('#txtPageNo').val());
	startLimitGlobal=$('#txtPageNo').val()*5-5;
	cat = getParameter("cat");
    searchAgainst=getParameter("searchAgainst");
	
	var x = {startLimitGlobal:startLimitGlobal, cat:cat, searchAgainst:searchAgainst};
	$.ajax({type: "GET", url: "globalDirSearch.php", data:x, success:showPageNumberGlobal});
}

function showPageNumberGlobal(data)
{
	$("#dvDirectory").html(data);
	$('#currentPage').html(currentPageGlobal);
	$('#spLoadingImage').hide();
	
}