// Javascript functions for Pedlars 2.0
// Jquery and it's plugins must be loaded before this file

// some globals
// swatches folder
var swatchdir = '/swatches/';
// for shopping kart
var theForm = 0; 
var useAsync = 1;
// for homepage animation
var animActive = 0;
var animRunning = 0;
// sets up some stuff on every page, called from document.ready via skin
function pedLoader()
{
	if(document.getElementById('searchKeys'))
	{
		document.getElementById('searchKeys').value='Search our stuff';
		document.getElementById('searchKeys').onfocus=function () {document.getElementById('searchKeys').value='';};
	}
	if(document.getElementById('muser2') && document.getElementById('mcountry'))
	{// hide US state selector from non US users on billing/register forms
		var index = document.getElementById('mcountry').selectedIndex;
		USDisplay(document.getElementById('mcountry')[index]);
	}
	preloadAllImages();
	printMyAccount();
	printKartSummary();
	$('ul#megadd').superfish({ 
	    hoverClass:    'sfHover',
	    pathClass:     'overideThisToUse',
	    pathLevels:    1,
	    delay:         400,
	    animation:     {opacity:'show'},
	    speed:         'fast',
	    autoArrows:    false,
	    dropShadows:   false,
	    disableHI:     false
	});
	// load homepage javascript if on homepage...
	if(document.getElementById('homeRoomsetMain'))
	{
		pedHomeLoader();
	}
}
// sets up some stuff on the product page, called from document.ready via skin
function prodLoader()
{
	// This sets the correct price/picture and shows/hides some elements on product pages
	if(document.getElementById('key_f'))
	{// multiple products on this page
		changeProduct(document.getElementById('key_f').value);
		if(document.getElementById('Prod_js_hide'))
		{
			document.getElementById('Prod_js_hide').className='invisible';
		}
		if(document.getElementById('ProdPrice'))
		{
			document.getElementById('ProdPrice').className='';
		}
		if(document.getElementById('ProdRRP'))
		{
			document.getElementById('ProdRRP').className='';
		}		
	}
	else if(document.getElementById('key_s'))
	{// one product on this page
		if(document.getElementById('alternateHolder'))
		{
			var alternates = document.getElementById('alternateHolder').getElementsByTagName('a');
			for(var i in alternates)
			{
				alternates[i].onclick=new Function("return viewAlternate('"+i+"')");
			}
		}
	}
	if(enableZoom == 1)
	{// product zoom
		var options = {
				     zoomWidth: 377,
				    zoomHeight: 547,
				         outTop: 43,
				       outRight: 30,
				      outBottom: 72,
				        outLeft: 20,
			            xOffset: 10,
			            yOffset: -36,
			   showEffect: 'fadein',
			           title: false,
			    fadeinSpeed: 'fast',
			  hideEffect: 'fadeout',
			 fadeoutSpeed: 'medium',
			    showPreload: 'true',
			   zoomType: 'standard',
			       position: "right" 
		};		
		$('.bigimg').jqzoom(options);
		// hack to stop wrongly positioned zoom on window resize
		$(window).bind('resize', function () {
			$('.bigimg').unbind();
			$('.bigimg').jqzoom(options);
		});
	}
}
// sets up javascript for the homepage, called from pedLoader
function pedHomeLoader() {
	// roomset stuff
	// hoverIntent stops these from jumping about like a jack in the box, it's useful that way
	$('#homeRoomsetRight').children('a').hoverIntent({
			sensitivity: 1,
			interval: 150,
			over: pedHomeAnimate,
			timeout: 500,
			out: function (){}
	});
	// change all secondary class elements to opacity 0 
	$('#homeRoomsetMain').children('a.secondary').css({opacity:0});
	// now get rid of all secondary classes on these elements. 
	$('#homeRoomsetMain').children('a.secondary').toggleClass('secondary');	
	$('#homeRoomsetRight').children('a').slice(animActive,animActive+1).css({opacity: 0.3});
}
// set up the relevant onclick events for the async shopping kart
function asyncBasketLoader()
{
	$('form#prodform').submit(asyncBasket);
	$("form[name='buyform']").submit(asyncBasket);
}
// fills the relevant divs with greeting and links to my account/logout 
// I thought doing this using DOM methods would be neater. Clearly I'm an idiot. I'll use innerHTML next time. 
function printMyAccount() 
{
	var allcookies=document.cookie;
	var posm=allcookies.indexOf('log=');
	if (document.getElementById('signInHolder') && posm != -1)
	{
		// create new stuff
		// first welcome $username
		var welcome = document.createElement("p");
		var username = 'Pedlars Customer';
		if(getCookie('member'))
		{
			username = getCookie('member');
		}
		var text = document.createTextNode('Welcome '+username);
		welcome.appendChild(text);
		// then create my account text with link to member page and logout
		// memlink is set in the skin. Yes there are probably better ways. Sue me. 
		var memlink = 'http://www.pedlars.co.uk/cgi-bin/ped/pprint.pl?efile=login&mode=s';
		if(memberpagelink)
		{
			memlink = memberpagelink;
		}
		var memanchor = document.createElement("a");
		memanchor.setAttribute('href',memlink);
		memanchor.appendChild(document.createTextNode('My account'));
		var logoutanchor = document.createElement("a");
		logoutanchor.setAttribute('href','javascript:logout()');
		logoutanchor.appendChild(document.createTextNode('Log out'));
		var myaccount = document.createElement("p");
		myaccount.id="signIn";
		// append new elements
		myaccount.appendChild(welcome);
		myaccount.appendChild(memanchor);
		myaccount.appendChild(document.createElement("br"));
		myaccount.appendChild(logoutanchor);
		// get signin holder, remove sign in text, replace with new div, append anything else in there that's not sign in text
		var sih = document.getElementById('signInHolder');
		sih.removeChild(document.getElementById('signIn'));
		// stick our new div in the sign in holder
		if(sih.hasChildNodes())
		{
			sih.insertBefore(myaccount,sih.firstChild);
		}
		else
		{
			sih.appendChild(myaccount);
		}
	}
}
// prints shopping kart summary info
function printKartSummary() 
{
	if(document.getElementById('shoppingTotal'))
	{
		var kartsummary = getCookie('kartsummary');
		var ptotal = document.getElementById('shoppingTotal');
		var aitems = document.getElementById('shoppingBag');
		if(kartsummary !='')
		{
			var dashpos = kartsummary.indexOf('-');
			var Items = kartsummary.substring(0,dashpos);
			var Money = kartsummary.substring((dashpos+1),kartsummary.length);
			ptotal.innerHTML = '<span class="space10px">Total</span>'+Money;
			aitems.innerHTML = Items;
		}
		else
		{
			ptotal.innerHTML='<span class="space10px">Total</span> &pound;00.00';
			aitems.innerHTML = '0';
		}
	}

}
// switches out product image and prices on product page
function changeProduct(key_f)
{
	if(document.getElementById('BigImageLink') && SKZoom[key_f][0])
	{
		document.getElementById('BigImageLink').href=swatchdir+SKZoom[key_f][0];
		showZoom = 1;
	}
	else if (document.getElementById('BigImageLink'))
	{
		document.getElementById('BigImageLink').href='';
		showZoom = 0;
	}
	if(document.getElementById('BigImage') && SKImg[key_f][0])
	{
		document.getElementById('BigImage').src=swatchdir+SKImg[key_f][0];
	}
	if(document.getElementById('key_f'))
	{
		var myoptions = document.getElementById('key_f').options;
		// create an array mapping option position to sk_keyf
		var products = new Array();
		for(var i=0; i <myoptions.length;i++)
		{
			var optkey = myoptions[i].value;
			products[optkey] = i;
		}
		if(products[key_f] !=undefined)
		{
			document.getElementById('key_f').selectedIndex=products[key_f];
		}
	}
	if(document.getElementById('ProdPrice'))
	{
		var pp = document.getElementById('ProdPrice');
		while(pp.hasChildNodes())
		{
			pp.removeChild(pp.firstChild);
		}
		pp.appendChild(document.createTextNode('Price: '));
		var span = document.createElement('span');
		span.appendChild(document.createTextNode("\u00A3"+SKPrice[key_f]));
		pp.appendChild(span);
	}
	if(document.getElementById('ProdRRP'))
	{
		var pp = document.getElementById('ProdRRP');
		while(pp.hasChildNodes())
		{
			pp.removeChild(pp.firstChild);
		}
		if(SKPPrice[key_f])
		{
			pp.appendChild(document.createTextNode('Was: '));
			var span = document.createElement('span');
			//\u00A3 = pound sign in unicode
			span.appendChild(document.createTextNode("\u00A3"+SKPPrice[key_f]));
			pp.appendChild(span);
		}
	}
	if(document.getElementById('alternateHolder'))
	{
		var ah = document.getElementById('alternateHolder');
		var txt = getText(document.getElementById('alternateHolderText'));
		while(ah.hasChildNodes())
		{
			ah.removeChild(ah.firstChild);
		}
		if(SKTiny[key_f] && SKTiny[key_f].length > 1)
		{
			for (var i in SKTiny[key_f])
			{
				var newa = document.createElement("a");
				newa.setAttribute('href','#');
				newa.onclick=new Function("return viewAlternate('"+i+"')");
				newa.className='alternateThumb';
				var newimg = document.createElement("img");
				newimg.src = swatchdir+SKTiny[key_f][i];
				newa.appendChild(newimg);
				ah.appendChild(newa);				
			}
		}
		var ap = document.createElement("p");
		ap.id="alternateHolderText";
		ap.appendChild(document.createTextNode(txt));
		if(SKTiny[key_f].length <= 1)
		{
			// hide alternateHolderText if there are no images, it still needs to be present
			// or subsequent calls to this function will fail
			ap.className="invisible";
		}
		ah.appendChild(ap);
	}
	return false;
}
function viewAlternate(i)
{
	var key;
	if(document.getElementById('key_f'))
	{
		key = document.getElementById('key_f').value;
	}
	else if(document.getElementById('key_s'))
	{
		key = document.getElementById('key_s').value;
	}
	else
	{
		return true;
	}
	if(document.getElementById('BigImageLink') && SKZoom[key][i])
	{
		document.getElementById('BigImageLink').href=swatchdir+SKZoom[key][i];
		showZoom = 1;
	}
	else if(document.getElementById('BigImageLink'))
	{
		document.getElementById('BigImageLink').href='';
		showZoom = 0;
	}
	if(document.getElementById('BigImage') && SKImg[key][i])
	{
		document.getElementById('BigImage').src=swatchdir+SKImg[key][i];
	}
	return false;
}
function getCookie(cook)
{
	if (document.cookie.length>0)
	{
		var startpos = document.cookie.indexOf(cook + '=');
		if (startpos !=-1)
		{
		    startpos=startpos + cook.length + 1;
		    var endpos =document.cookie.indexOf(';' ,startpos);
		    if (endpos==-1) endpos=document.cookie.length;
		    return unescape(document.cookie.substring(startpos,endpos));
		}
	}
	return '';
}
function setCookie(cname,value)
{
	document.cookie=cname+ "=" +escape(value);
}
function zapcook(cook)
{
	var temp=new Date();
	temp.setFullYear(temp.getFullYear()-1);
	document.cookie=cook+"=; path=/; expires="+temp.toGMTString();
}
function logout()
{
	zapcook('log');
	zapcook('member');
	zapcook('cryptpass');
	zapcook('lognew');
	alert('You are logged out.  Please wait while we reload the page. ');
	window.location.href='/';
}

// jquery functions
// animate the fade in/out of boxes on the homepage. Not in use, the flashier pedHomeAnimate below is used. 
function pedHomeAnimFade(i) 
{
	// get the index of the element that has been moused over. 
	var ind = $('#homeRoomsetRight').children('a').index(this);
	if( ind == animActive )
	{// active initialised in doc.ready(), the current active mouseover
		return;
	}
	var old = $('#homeRoomsetMain').children('a').slice(animActive,animActive+1);
	// crossfade 
	// the primary class has a z-index, so we can actually click the A element
	// once we've faded in
	old.toggleClass('primary');
	var cur = $('#homeRoomsetMain').children('a').slice(ind,ind+1);
	old.animate({
		opacity: 0
	}, 900);
	cur.animate({
		opacity: 1
	}, 900);
	var thumb = $('#homeRoomsetRight').children('a').slice(ind,ind+1);
	var oldthumb = $('#homeRoomsetRight').children('a').slice(animActive,animActive+1);
	thumb.css({opacity: 0.3});
	oldthumb.css({opacity: 1});
	cur.toggleClass('primary');
	// set new active element
	animActive=ind;
}
// animate the swoop in/out of boxes on the homepage
function pedHomeAnimate(i) 
{
	// get the index of the element that has been moused over. 
	var ind = $('#homeRoomsetRight').children('a').index(this);
	// animActive initialised at top of file, the current active main image
	if( ind == animActive || animRunning )
	{// we are already on this image. or animation is running
		return;
	}
	// global to stop the animations overlapping
	animRunning = 1;
	// animation time in ms
	var animTime = 700;
	
	// old is the currenly displayed image
	var old = $('#homeRoomsetMain').children('a').slice(animActive,animActive+1);	
	var oldthumb = $('#homeRoomsetRight').children('a').slice(animActive,animActive+1);
	// thumb is the thubnail of the image that we're swooping in
	var thumb = $('#homeRoomsetRight').children('a').slice(ind,ind+1);
	var thumbpos = thumb.position();
	// these are the css values we set the new image to initially, these 
	// need to be identical to the existing thumbnail
	var startwidth = thumb.width();
	var startheight = thumb.height();
	var startleft = thumbpos.left + parseInt(thumb.css("padding-left"), 10);
	var starttop = thumbpos.top + parseInt(thumb.css("padding-top"), 10);
	// next is the new image to swoop in
	var next = $('#homeRoomsetMain').children('a').slice(ind,ind+1);
	// these are the target co-ordinates for the new image. 
	// note they are the current co-ordiantes, the image just has 0 opacity right now
	var tgtwidth = next.width();
	var tgtheight = next.height();
	var tgttop = next.position().top + parseInt(next.css("padding-top"), 10);;
	var tgtleft = next.position().left + parseInt(next.css("padding-left"), 10);
	// switch the z-index on the old image
	old.toggleClass('primary');
	// this is the image itself. we also need to animate it's height and width as 
	// it doesn't follow the container. 
	var nextimg = next.find('img')
	next.css({
		width: startwidth
		,height: startheight
		,left: startleft
		,top: starttop
		,opacity: 0.2
	});
	nextimg.css({
		width: startwidth
		,height: startheight
	});
	thumb.css({opacity: 0.3});
	// first fade out the old image over 400ms
	old.animate({
		opacity: 0
	}, (animTime /2));
	// now swoop the new one into position
	nextimg.animate({
		width: tgtwidth
		,height: tgtheight
	}, animTime);
	next.animate({
		width: tgtwidth
		,height: tgtheight
		,left: tgtleft
		,top: tgttop
		,opacity: 1
	}, animTime);

	oldthumb.css({opacity: 1});
	// switch the z-index on the new image (so we can click it, dummy)
	next.toggleClass('primary');
	// store new animActive element
	animActive=ind;
	setTimeout(function(){animRunning = 0;},animTime);
}
// async shopping kart.
function asyncBasket()
{
	// useAsync initialised to 1 in skin. We set it to false if we want the user to retry without AJAX
	if(!useAsync)
	{
		return true;
	}
	var formvars = new Array();
	// this is needed for the shopping kart to work
	setCookie("cookieswork", "Y");
	// theForm is initialised at the top of this file so it's global and we can use it 
	// in asyncSuccess and asyncError
	theForm = $(this);
	// find SKU key
	formvars['key'] = 0;
	
	if(theForm.find('#key_f').attr("value"))
	{// select on product page
		formvars['key'] = theForm.find('#key_f').attr("value");
	}
	else if(theForm.find("input[name='key']").attr("value"))
	{// standard hidden input
		formvars['key'] = theForm.find("input[name='key']").attr("value");
	}
	else
	{
		return true;
	}
	// get remaining needed form values for ajax submission
	var elems = ["backto","mode","ID","quantity"];
	for (var i in elems)
	{
		if(! theForm.find('input[name='+elems[i]+']').attr("value"))
		{
			return true;
		}
		formvars[elems[i]] =  theForm.find('input[name='+elems[i]+']').attr("value");
	}
	
	// bring up "loading..." animation
	// note that the contents of these dialogs are set in the skin 
	// to allow preloading of images. 
	$('#waiting').modal({
		containerId: "modalLoading"
	});
	//window.scroll(0,0);
	// AJAX request. Note karturl is set in skin
	$.ajax({
		type: "GET"
		,url: karturl
		,data: { 
			'key': formvars['key']
			,'backto': formvars['backto']
			,'mode':formvars['mode']
			,'ID':formvars['ID']
			,'quantity':formvars['quantity']
			,'async':'Y'
		}
		,success: asyncSuccess
		,error: asyncError
		
	});
	return false; 		
}
// process return from AJAX shopping kart
function asyncSuccess(data, textStatus)
{
	if(textStatus == 'success')
	{// page sucessfully loaded.
		if($(data).find('SUCCESS').text() == 1)
		{ // Kart Success
			var msg = $(data).find('MESSAGE').text();
			printKartSummary();
			// close loading modal
			$.modal.close();
			// show success message
			$('#success').modal({
				containerId: "modalBag"
				,closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>"
				,onOpen: function (dialog) {
					dialog.overlay.show();
					dialog.container.slideDown('normal');
					dialog.data.show();
				}
				,onClose: function (dialog) {
					dialog.overlay.fadeOut('normal',function() {$.modal.close();});
					dialog.container.slideUp('normal');
					dialog.data.slideUp('normal');
				}
			});
			// show link to shopping kart when product added
			if($('#kartLink:hidden').css("display") == "none")
			{
				$('#kartLink').show('slow');
			}
			setTimeout(function(){$.modal.close();},2000);
			
		}
		else
		{ // Kart Problem
			// show error message in modal
			var msg = $(data).find('MESSAGE').text();
			$.modal.close();
			$.modal('<p>'+msg+'</p>',{
				containerId: "modalErr"
				,closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>"
				,onOpen: function (dialog) {
					dialog.overlay.show();
					dialog.container.slideDown('normal');
					dialog.data.show();
				}
				,onClose: function (dialog) {
					dialog.overlay.fadeOut('normal',function() {$.modal.close();});
					dialog.container.slideUp('normal');
					dialog.data.slideUp('normal');
				}
			});
			useAsync = 0;
		}		
	}
	else
	{
		// unknown error, retry without AJAX
		return asyncError(0, 0, 0);
	}
}
function asyncError(XMLHttpRequest, textStatus, errorThrown) 
{// ajax fail. Try without! Probably Stupid, But Try Anyway
	$.modal.close();
	$('#error').modal({
		containerId: "modalErr"
		,closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>"
		,onOpen: function (dialog) {
			dialog.overlay.show();
			dialog.container.slideDown('normal');
			dialog.data.show();
		}
	});
	useAsync = 0;
	setTimeout(function(){theForm.find("input[type='submit']").click()},1200);
}
// Make sure all hidden css background images and images with display:none are loaded. 
function preloadAllImages()
{
	var loaded = new Array();
	$('*').each(function(i,elm)
	{
		if($(this).css("background-image") != "none" && $(this).is(":hidden"))
		{
			var loc = $(this).css("background-image");
			loc = loc.match(/[^\("]+\.(gif|jpg|jpeg|png)/g);         
			if( $.inArray(String(loc),loaded) == -1 )
			{
				//alert(loc);
				var img = new Image();
				img.src = loc;
				loaded.push(String(loc));
			}
		}
	});
	$('img').each(function(i,elm) 
	{
		if($(this).is(":hidden"))
		{
			if( $.inArray(String(loc),loaded) == -1 )
			{
				//alert($(this).attr("src"));
				var loc = $(this).attr("src");
				var img = new Image();
				img.src = loc;
				loaded.push(String(loc));
			}
		}
	});
}
// For checkout/registration forms. Displays a US state dropdown when the user selects USA from the list of countries. 
function USDisplay()
{
	var display = 'none';
	if(document.getElementById('mcountry'))
	{
		var index = document.getElementById('mcountry').selectedIndex;
		if(document.getElementById('mcountry')[index].value == 'US')
		{
			display='block';
		}
		if(document.getElementById('mdcountry'))
		{
			var dindex = document.getElementById('mdcountry').selectedIndex;
			if(document.getElementById('mdcountry')[dindex].value == 'US')
			{
				display='block';
			}
		}
	}
	var usstates = getElementsByClassName('usstates');
	for(var i in usstates)
	{
		usstates[i].style.display = display;
	}
}
// Get the text of an element
function getText (el) 
{
	if(!el) { return ''; }
	if (el.textContent) {return el.textContent;}
	if (el.innerText) {return el.innerText;}
	if (typeof el.innerHTML == 'string') {
		return el.innerHTML.replace(/<[^<>]+>/g,'');
	}
}
/*
	MIT licensed getElementsByClassName from below URL... 
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/	
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};