//
//last update: 2011-10-8
//
// global variables

/*
// defind jQuery plugin 
(function($) { 
	$.fn.name = function() { 
		...
	}
})( jQuery ); 

*/


// HOTFIX: We can't upgrade to jQuery UI 1.8.6 (yet)
// This hotfix makes older versions of jQuery UI drag-and-drop work in IE9
(function($){var a=$.ui.mouse.prototype._mouseMove;$.ui.mouse.prototype._mouseMove=function(b){
	if($.browser.msie&&document.documentMode>=9){b.button=1};a.apply(this,[b]);}
}(jQuery));





var isreloadPage=false;
//var currentUrl = window.location.pathname;
var currentUrl = $(location).attr('href'); 
var pagename = basename(currentUrl).split("?")[0]; //page name
var isCatalogue = /catalogue/.test(pagename);
var isDetails = /details/.test(pagename);
var isCart = /cart/.test(pagename);
var isContactus = /contact_us/.test(pagename);
var isAccount = /account/.test(pagename);
var isWishlist = /wishlist/.test(pagename);
var isRegister = /register/.test(pagename);
var isDetailspopup = /detailspopup/.test(pagename);  

if (isCatalogue || isDetails || isCart || isContactus || isAccount || isWishlist || isRegister) {
	isreloadPage=true;
	if (isCart) currentUrl='cart.php';
	if (isRegister) currentUrl='account.php';
}
//alert ('currentUrl: '+currentUrl);//debug
//alert ('pagename: '+pagename);//debug
//alert ('Reload page? '+isreloadPage);//debug
//alert ('reloadUrl: '+currentUrl);//debug

//alert (isDetailspopup);//debug


var wishlistDelimiter = '^'; //delimiter for wishlist cart cookie


$(document).ready(function(){     // jQuery   

	//alert ('common.js jQuery loaded');
	var sideloginForm = $('#sideloginform');
	var sideLogin=$('.sidelogin'); 
	var sideLoggedin=$('.sideloggedin');
 	var sideLoggedinemail=$('#sideloggedinemail'); 
	
	
	//var sideLoggedinemail=$('sapn:[id==sideloggedinemail]');
	
	//alert ('#sideLoggedinemail = ' + sideLoggedinemail);
	var action='login';
	
	//var sideLoggedinemailLength=$.trim(sideLoggedinemail.html()).length;  //check if logged in ; contain emails
	//alert (sideLoggedinemailLength);
	
	//alert (isLoggedin); debug logged in flag 
	
	
	
	$('#maintable').css("height",$('#sidemenu').height()); //equal maintable to sidemenu table 
	
	$('#showsidelogin').click(function(event) {  //toggle side member Login
		event.preventDefault(); // ignore default href action
		
//individual slideUp and slideDown
//		if ($('#sidememberlogin').css("display") == "none")     
//			$('#sidememberlogin').slideDown(1000,"easeOutBounce"); 
//		else     
//			$('#sidememberlogin').slideUp(500,"easeOutQuad"); 
//
		
		$('#sidememberlogin').slideToggle(1000,"easeOutBounce",function(){
			//alert ($('#sidemenu').height()); //debug
			$('#maintable').css("height",$('#sidemenu').height()); //entend maintable to equal sidemenu table
		}); //end of toggle
		
	}); //end of toggle side member Login
	
	
	// expand side login panel
	$('#login').click(function(event) {  
		event.preventDefault(); // ignore default href action
		$('#sidememberlogin').slideDown(1000,"easeOutBounce",function(){
			//alert ($('#sidemenu').height()); //debug
			$('#maintable').css("height",$('#sidemenu').height()); //extend maintable to equal sidemenu table
		}); //end of toggle;
	});

	
	
	
	
	//logged in?
	if (isLoggedin==false){  //Not logged in
		sideLogin.css("display", "table-row");
		sideLoggedin.css("display", "none");
		changeLink($('#loginlink'),'Register','Register',"register" );//change Login link register
	} else { //logged in
		sideLogin.css("display", "none");
		sideLoggedin.fadeIn(800).css("display", "table-row");
		
		//inactiveLink($('#loginlink'),'You are already logged in!');  //inactive login link
		changeLink($('#loginlink'),'Click to view your account information','Account',"account" );//change login link to My account
		changeLink($('#sideaccupdate'),'Click to logout','Logout','' );//change "update account details" link to Logout
	
	};//end of logged in
	
	
	//Logout ?
	$('#sideaccupdate').click(function(event) {  
		event.preventDefault(); // ignore default href action
		$.logout();
	});
	
	
	
	//in-field label toggle for serarch box
	$(".searchInput input")  
		.each(function(){  //hide label if pre-populated 
			if (this.value) {
				$(this).prev().hide();
			}
		})
		.focus(function(){ //hide label if focused
			$(this).prev().hide();
		})
		.blur(function(){ //show label is loose focuse and nothing entered
			if (!this.value) {
				$(this).prev().show();
			}
		});


}); //end of jQuery  


//logout
jQuery.logout= function() {
	$.post('submit_register.php',{ 
			page: pagename,
			action: 'logout',
			email : $('#sideemail').val()
	}, function(data) {
		//alert ('submit_register.php logout: '+data);//debug	
	})
	.complete(function() { 
		//$('.sideloggedin').slideUp(800);
		$('.sideloggedin').fadeOut(500);
		
		$.doTimeout( 500, function(){
			//alert ('You are successfully logged out.');
			$.doTimeout( 500, function(){ 
				$.favoritesToggle(); //refresh favorites link
				$.cartToggle(); //refresh shopping cart link
				changeLink($('#loginlink'),'Login/Register','Register',"register" );//change Account link back to Register
				$('.sidelogin').fadeIn(800);
				$('#sidememberlogin').css("display", "none");
				$.doTimeout( 100, function(){
					if (isreloadPage) {  //reload page if needed
						window.location.href = currentUrl;
						//location.reload();
					}
				});
			});
		});
	});
}







jQuery.roundImgCorner = function() //round images corner with class="rounded_img" or "rounded_img2" using CSS3 only work in Firefox
{
	$(".rounded_img, .rounded_img2").load(function() {  //round images corner with class="rounded_img" or "rounded_img2" using CSS3 only work in Firefox
	$(this).wrap(function(){
	  return '<span class="' + $(this).attr('class') + '" style="background:url(' + $(this).attr('src') + ') no-repeat center center; width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px; opacity:1; filter:alpha(opacity=100); " />';
	});
	$(this).css("opacity","0");
	//$(this).css("display","none");
	});
}



//jQuery.fn.roundImgCorner = function() //round images corner with class="rounded_img" or "rounded_img2" using CSS3 only work in Firefox
//{
//	$(".rounded_img").wrap(function(){
//		return '<span class="' + $(this).attr('class') + '" style="background:url(' + $(this).attr('src') + ') no-repeat center center; width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px; opacity:1; filter:alpha(opacity=100); " />';
//	});
//	$(".rounded_img").children("img").css("opacity","0");
//}



//image hoover click effect
jQuery.fn.imgMouseEffect = function() //to be called from jQuery instances only 
//jQuery.imgMouseEffect = function() //to be called from the global jQuery object 
{
	$(".rounded_img").mouseover(function () {
    	//$(this).parents("span").css("opacity","0.7");
		$(this).parents("span").removeClass("rounded_img").addClass("rounded_hoover");
  	});
  	$(".rounded_img").mouseout(function () {
    	//$(this).parents("span").css("opacity","1");
		$(this).parents("span").removeClass("rounded_hoover").addClass("rounded_img");
  	});
//	$(".rounded_img").click(function (event) {
//		//$(this).parents("span").css("opacity","1");
//		$(this).parents("span").removeClass("rounded_hoover").addClass("rounded_click");
//  	});
}






//add an array of items to cart
jQuery.add2cart = function(itemArray) {
	$.each(itemArray, function(key, value){
		//alert (key+' '+value);  //debug
		//alert (itemArray); //debug
		
		$.post("cart.php", { 
			page: pagename,
			q: 1, 
			shipsel: "USA and Canada",
			shipopt: "Express",
			act: "add",
			code: value
		})
		.complete(function() { 
			//alert ('add2cart is done'); //debug
		});
	});//end of add to cart
}





//
//wishlist and cartlist cookie
//var updateCookie = function(cookiename,delimiter) {  // to be called : updateCookie(abc..)

jQuery.updateCookie = function(cookiename,delimiter,expiryday) {  // to be called : $.updateCookie(abc..)
	
	var cookie=$.cookie(cookiename);
	var bits = cookie ? cookie.split(delimiter) : new Array(); //array of wish items
	var bitsCount = bits.length;
	//alert ('cookie array: '+bits);//debug
	//alert (bitsCount); //debug
	
	return {
		"add": function(code) {
			bits.push(code);
			bits=unduplicate(bits); // remove duplicates
			$.cookie(cookiename,bits.join(delimiter),{expires: expiryday}); // set cookies
		},
		"remove": function(code) {
			//alert ("index :"+$.inArray(code,bits)); //debug
			bits.splice($.inArray(code,bits),1);
			$.cookie(cookiename,bits.join(delimiter),{expires: expiryday}); // set cookies
		},
		"empty": function() { 
			bits = null;  //clear the array         
			$.cookie(cookiename, null);  //clear the cookie
		}
	}
}


// return no. of element
jQuery.cookieCount = function(cookiename,delimiter) {  
	var count=0;
	var cookie=$.cookie(cookiename);
	if (cookie!=null) {  //cookie exist?
		var element = cookie.split(delimiter);//array of element
		
		for(i=0;i<element.length;i++) {
			if(element[i]!="")
				{count++}
		}
		//alert ('array: '+element); //debug
		//alert ('count: '+count); //debug
	}
	return count;
}


//remove duplicates from array
function unduplicate(array){ 
	var unduped = new Object();
	for (var i = 0; i < array.length; i++) {   
		unduped[array[i]] = array[i];}
	var uniques = new Array();
		for (var k in unduped) {
	uniques.push(unduped[k]);}
	return uniques;
}


//check if item already in whishlist
function inList(cookiename,code){
	var cookie=$.cookie(cookiename);
	if (cookie!=null) {  //cookie exist?
		if ($.cookieCount(cookiename,wishlistDelimiter)>0){ 
			//alert ('cookie:'+cookie+' code:'+code);//debug
			if (cookie.indexOf(code)>=0) return true;  
			else return false;
		}
	}
}



//toggle Favorites link state
jQuery.favoritesToggle = function() { 		
	if ($.cookieCount("wishlist",wishlistDelimiter)>0){ 
		$('a:contains(Favorites)').fadeOut(200).removeClass('PageLink_3').fadeIn(800).addClass('PageLink_3b');
	} 
	else {
		$('a:contains(Favorites)').fadeOut(200).removeClass('PageLink_3b').fadeIn(800).addClass('PageLink_3');
	}
}

//toggle shopping cart link state
jQuery.cartToggle = function() { 		
	var numCart=$.cookieCount("cartlist",wishlistDelimiter);
	var cartText='';
	//alert(numCart);//debug
	
	if (numCart>0){ 
		cartText='\<img src="Assests/images/cart.gif" width="17" height="14" border="0"\> Shopping Cart ('+numCart+')';
		$('a:contains(Shopping Cart)').fadeOut(200).removeClass('PageLink_3').html(cartText).fadeIn(800).addClass('PageLink_3b');
	} 
	else {
		cartText='\<img src="Assests/images/cart.gif" width="17" height="14" border="0"\> Shopping Cart';
		$('a:contains(Shopping Cart)').fadeOut(200).removeClass('PageLink_3b').html(cartText).fadeIn(800).addClass('PageLink_3');
	}
}


//inactive a link
function inactiveLink(id,msg) {
	id.css('color','#b8b8b8');
	id.click(function(e) {      
		e.preventDefault();  //disable login page link
		alert(msg);
	}); 
}


//change a link
function changeLink(id,msg,name,page) {
	var curUrl=id.attr('href'); 
	if (curUrl!=null) {
		var index = curUrl.indexOf('.php?');
		var before = curUrl.substr(0, index);
		var after = curUrl.substr(index); 
		//alert (curUrl);//debug
		//alert(before+'  '+after);//debug
		
		var newUrl=page+after;
		if (page==null || page=='') {
			newUrl='#';
		}
		//alert (newUrl);//debug
		
		id.hide().html(name).fadeIn(800);
		id.attr({
		  'title': msg,
		  'href': newUrl
		});
	}
}


//version 1
//convert to localcurrency
function convertCurrency(amount,from,to,deci,callback) {
	$.post("eurofx.php",{ 
		amount: amount,
		fromcur: from,
		tocur: to,
		deci: deci,
		action: "convert"
	}, function(data) {
		//alert (data);//debug	
		
		//Note: can't return anything from a function that is asynchronous
		//post is asynchronous call
		callback (data); //pass data into the var callback
	})
}



/*
//version 2
//convert to localcurrency
function convertCurrency(amount,from,to,deci) {
	return  $.post("eurofx.php",{ 
			amount: amount,
			fromcur: from,
			tocur: to,
			deci: deci,
			action: "convert"
			})
}
// var converted=convertCurrency(amount,from,to,deci)
// converted.success(function (data) {
//		do something with data here
// });
*/





function trimCallback(data) {
	var extract = data.match(/{(.*?)}/) ; //extract string within { }
	trim="{"+extract[1]+"}";
	return trim; 
}


function basename (path, suffix) {
    // *     example 1: basename('/www/site/home.htm', '.htm'); // *returns 1: 'home'
    // *     example 2: basename('ecra.php?p=1');
    // *     returns 2: 'ecra.php?p=1'
    var b = path.replace(/^.*[\/\\]/g, '');
     if (typeof(suffix) == 'string' && b.substr(b.length - suffix.length) == suffix) {
        b = b.substr(0, b.length - suffix.length);
    }
    return b;
}



jQuery.fn.imagesLoaded = function(callback, fireOne) {
  var
    args = arguments,
    elems = this.filter('img'),
    elemsLen = elems.length - 1;

  elems
    .bind('load', function(e) {
        if (fireOne) {
            !elemsLen-- && callback.call(elems, e);
        } else {
            callback.call(this, e);
        }
    }).each(function() {
        // cached images don't fire load sometimes, so we reset src.
        if (this.complete || this.complete === undefined){
            this.src = this.src;
        }
    });
}




function Search(it) /*pass productcode and search database*/
{
    document.searchbox.action="catalogue.php?act=find&searchterm="+it;
	document.searchbox.searchterm.value=it;
	document.searchbox.submit();
}


function fixH(one,two) { //match height of two objects
	if (document.getElementById(one)) {
	var lh=document.getElementById(one).offsetHeight;
	var rh=document.getElementById(two).offsetHeight;
	var nh = Math.max(lh, rh);
	document.getElementById(one).style.height=nh+"px";
	document.getElementById(two).style.height=nh+"px";
	}
}


function fixH2() { //match height of two objects using window.onload
	var one='bodytable';
	var two='maintable';
	if (document.getElementById(one)) {
	var lh=document.getElementById(one).offsetHeight;
	var rh=document.getElementById(two).offsetHeight;
	var nh = Math.max(lh, rh);
	//alert (nh)
	document.getElementById(one).style.height=nh+"px";
	document.getElementById(two).style.height=nh+"px";
	}
}



function addLoadEvent(func) { //multiple onload
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}


function addBookmark(title,url) {
	if (window.sidebar) { 
		window.sidebar.addPanel(title, url,""); 
	} else if( document.all ) {
		window.external.AddFavorite( url, title);
	} else if( window.opera && window.print ) {
		return true;
	}
}


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}






/*
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
*/


/*function forceReload() { //force reload if not yet done
    if (document.images)
        location.replace(location.href + '?' + (new Date()).getTime());
    else
        location.href = location.href + '?' + (new Date()).getTime();
}
var lastTime = location.search.substring(1) - 0;
if ((new Date()).getTime() - lastTime > 1000)
forceReload();*/


