/*

	1312 vs. Kitty Cooper

	

	written by Mike "1312" (mike at fudgestudios.com) and Phil (phil at fudgestudios.com) 

	for Fudge Studios (www.fudgestudios.com)
	

	This javascript is the main javascript for the sites actions.
	
	Also its probably mootools not at its best...
	(jQuery > Prototype > Mootools :: Mootools != ftw lol!!1!)
	
*/

// --------------------------------------------------------------------------------------------------------------
// some set up variables
var isOverToolbox = false;
var totalThumbs = 0;
var currentThumb = 0;
var moving = false;
var moveTo = 0;
// stupid IE 6
var isIE6var = window.ie6;


// --------------------------------------------------------------------------------------------------------------
// triggered on dom ready, so before the page content has loaded
window.addEvent('domready', function() {
	// dom element events
			
	//1312 - temp ie gif fix for toolbox
	// sets isIE6 to true if if6 and the same for ie (all of them)
	var isIE6 = window.ie6;
	var isIE = window.ie;
	
	// doesnt seem to need to test if any exist..
	formHelpers(isIE,isIE6);
	
	// on every page, no need to test if exists
	navAccordionDo();
	
	// test if #basket-accordion exits, if so, do basket accordion
	if($('basket-accordion') != null) {
		basketPageAccordion(isIE,isIE6);
	}
	
	// test if #content-page exists
	if($('content-page') != null) {
		contentPageIsIE(isIE,isIE6);
	}
	
	
	// test if #homepage-products exits
	if($('homepage-products') != null) {
		homePageAutoScroller(isIE6);
		homePageUlWidth();
	}
	

	// test if too box exists
	//if($type($('toolbox')) != false) {
	if($('toolbox') != null) {
		if($('toolbox-outer')) {
			$('toolbox-outer').setOpacity(0);
		}
		toolBox(isIE,isIE6);	
	}	


	// test if #product-detail
	if($('product-detail') != null) {
		productDetailFunctions();
	}
	
	// test if #productList
	if($('productList') != null) {
		productListFunctions(isIE,isIE6);
	}
	
	// do the image replacement on nav
	elements = $('kitty-cooper').getElements('a[class^=ir]');
	for(i=0; i<elements.length; i++) {
		el = elements[i];
		t = el.innerHTML;
		u = '/fonts/kittycooper.php?t='+t;		
		
		el.setStyle('background-image', 'url("'+u+'")');
		el.setStyle('text-indent','-100em');
	}
	
	// reset forms so that FF doesn't cause problems
	if($('product-detail-form')) {
		$('product-detail-form').reset();
	}
});

// --------------------------------------------------------------------------------------------------------------
// moves thumbnails
function moveIt(to) {
	if (moving==false) {
		var moveDistance=56;
		var moveDistanceLarge=499;	
		move=false;
		currentLeft = $('thumbnail-strip').getStyle('left').toInt();
		currentLeftLarge = $('image-strip-inner').getStyle('left').toInt();

		if(to=="prev" || to=="next") {
			if(to=="prev") {
				//alert("debug1");
				moveTo=currentLeft-moveDistance;
				if(currentThumb < totalThumbs) {
					moveTo=currentLeft-moveDistance;
					moveToLarge=currentLeftLarge-moveDistanceLarge;				
					currentThumb++;
					move=true;
					moving=true;						
				}
			} else {
							
				if(currentThumb > 0) {
					moveTo=currentLeft+moveDistance;
					moveToLarge=currentLeftLarge+moveDistanceLarge;				
					currentThumb--;
					move=true;
					moving=true;											
				}
			}
		} else { 
			moveTo = -to*moveDistance;
			moveToLarge = -to*moveDistanceLarge;		
			currentThumb = to;
			move=true;
			moving=true;									
		}		
		if(move) {			
			// move thumbnail strip
			var myEffects = $('thumbnail-strip').effects({duration: 600, transition:Fx.Transitions.Cubic.easeOut});
			myEffects.start({'left': [currentLeft, moveTo]});
			// move large image strip
			var myEffects = $('image-strip-inner').effects({duration: 1200, transition:Fx.Transitions.Cubic.easeOut, onComplete: disableMoving});
			myEffects.start({'left': [currentLeftLarge, moveToLarge]});		
			// sync the colour dropdown and the selected colour
			$('colour-options').selectedIndex = currentThumb;
			$('product-description').innerHTML = descriptions[currentThumb];
		}
	}
}

// resets the moving var so the next option can be chosen
function disableMoving() {
	moving=false;
}

// --------------------------------------------------------------------------------------------------------------

//1312 form helpers!
function formHelpers() {
	// add class "submit" to all inputs of type submit
	$('kitty-cooper').getElements('input[type=submit]').addClass("submit");		
	// switch classes on input type "submit" on roll over
	$('kitty-cooper').getElements('input[type=submit]').addEvents({
		'mouseover': function(event){
			$(this).addClass("submitHover");
		},
		'mouseout': function(event){
			$(this).removeClass("submitHover");
		}		
	});
	// add class "checkBox" to all inputs of type checkbox
	$('kitty-cooper').getElements('input[type=checkbox]').addClass("checkBox"); 	
	// and for input type file
	$('kitty-cooper').getElements('input[type=file]').addClass("file");
	// and for input type radio
	$('kitty-cooper').getElements('input[type=radio]').addClass("radio");
	// and for input type image
	$('kitty-cooper').getElements('input[type=image]').addClass("image");
	// switch classes on input type "image" on roll over
	$('kitty-cooper').getElements('input[type=image]').addEvents({
		'mouseover': function(event){
			$(this).addClass("imageHover");
		},
		'mouseout': function(event){
			$(this).removeClass("imageHover");
		}		
	});
}


// --------------------------------------------------------------------------------------------------------------

// 1312 a var to track shopping bag open or not (suppose could test for "display: none;" as an attribute or something instead)
var isShoppingBagOpen = false;
var isMyAccountOpen = false;
var openWhatNext = "";


function toolBox(isIE,isIE6) {
	
	
	if (isIE6){ $('toolbox').addClass("isIE6"); };
	if (isIE6){ $('go-to-checkout').addClass("isIE6"); };
	if (isIE6){ $('toolbox-bottom').addClass("isIE6"); };
	
	//1312 replacing background alpha pngs with inline image pngs for ie6
	// background hidden by css
	if (isIE6){ 
		// tool box top
		var toolBoxHtml = '<img src=\"/images/toolbox/blank.gif\" style=\"width: 271px; height: 242px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/images/toolbox/nav-panel-02.png\', sizingMethod=\'scale\')\" /><ul><li><a href=\"#\" id=\"shopping-bag\" class=\"over-toolbox\">Shopping Bag</a></li><li><a href=\"#\" id=\"my-account\" class=\"over-toolbox\">My Account</a></li></ul>';
		$('toolbox').setHTML(toolBoxHtml)
		
		//go-to-checkout btn
		toolBoxHtml = '<img src=\"/images/toolbox/blank.gif\" style=\"width: 270px; height: 76px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/images/navigation/checkout.png\', sizingMethod=\'scale\')\" /><a href=\"https://www.kitty-cooper.co.uk/cart\">Go to checkout</a>';
		$('go-to-checkout').setHTML(toolBoxHtml);
		
		
		toolBoxHtml = '<img src=\"/images/toolbox/blank.gif\" style=\"width: 270px; height: 76px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/images/toolbox/bg-toolbox-bottom.png\', sizingMethod=\'scale\')\" />';
		$('toolbox-bottom').setHTML(toolBoxHtml);
	};
		
	//1312 - lights and dims the tool box bg
	$('toolbox').addEvents({
		'mouseover': function(event){
			$('toolbox').addClass("hover");
		},
		'mouseout': function(event){
			$('toolbox').removeClass("hover");
		}
	});
	
	// 1312 apend a close button to the tool box div
	var closeBtnString = '<div class=\"toolbox-close\"><a href=\"#\">Close cart</a></div>';	
	var closeButtonLogin = new Element('div').setHTML(closeBtnString).injectInside('toolbox-login');
	var closeButtonBasket = new Element('div').setHTML(closeBtnString).injectInside('toolbox-shoppingBasket');
	
	// onload we want to hide the shopping basket, log in thing and the loader swirl in the tool box
	// and then show what we want, when we want it
	$('toolbox-shoppingBasket').addClass("hide");
	$('toolbox-login').addClass("hide");
	$('toolbox-loading').addClass("hide");
	
	// 1312 function for opening shopping bag in tool box
	$('shopping-bag').addEvents({	
	 	'click': function(event){
			
			if (isMyAccountOpen) {
				openWhatNext = "shopping-bag";
				closeToolBox();
			} else {
				if (isShoppingBagOpen) {
					closeToolBox();
				} else {
					openToolBoxShoppingBasket(true);					
				}
			}
	 	}
	 });

	// 1312 function for opening my account in tool box
	if($('my-account') != null) {
		$('my-account').addEvents({	
			'click': function(event){
				if (isShoppingBagOpen) {
					openWhatNext = "my-account";
					closeToolBox();
				} else {				
					if (isMyAccountOpen) {
						closeToolBox();
					} else {				
						openToolMyAccount()
					}
				
				}
			}
		 });
	}
	
	
	// 1312
	$$('.toolbox-close').addEvents({
	 	'click': function(event){
	 		var myEffects = $('toolbox-expander').effects({duration: 500, transition:Fx.Transitions.Sine.easeInOut, onComplete: hideToolboxOuter});
	 		myEffects.start({'top': [0,-420]});
	 	}
	 });
	
}

//1312 open tool box shopping basket
function openToolBoxShoppingBasket(fadeIn, isIE6) {
	$('toolbox-outer').setOpacity(1);
	$('toolbox-shoppingBasket').removeClass("hide");
	$('toolbox-loading').setOpacity(1);
	$('toolbox-loading').removeClass("hide");		
	$('toolbox-shoppingBasket').setOpacity(0);		
	var myEffects = $('toolbox-expander').effects({duration: 500, transition:Fx.Transitions.Sine.easeInOut});
	myEffects.start({'top': [-420,0]});
	$('toolbox').addClass("active");
	if (isIE6var){
		$$('select').addClass("hide");
	};
	isShoppingBagOpen = true;
	//if(fadeIn == true) {
		var basketDelay = showBasket.delay(600); //wait 5 seconds and execute function.
	//}
}

	function showBasket() {
		var hideLoader = new Fx.Style('toolbox-loading', 'opacity').start(1,0);	
		var showBasket = new Fx.Style('toolbox-shoppingBasket', 'opacity').start(0,1);
	}
	
	function hideBasket() {
		var hideLoader = new Fx.Style('toolbox-loading', 'opacity').start(0,1);	
		var showBasket = new Fx.Style('toolbox-shoppingBasket', 'opacity').start(1,0);
	}		

//1312 open tool box login box
function openToolMyAccount(isIE6) {
	// Check if the user is logged in, if they are send to account page, else show the login form.
	if(loggedIn == false) {
		if('login-error-container') {
			$('login-error-container').innerHTML = '';
		}		
		$('toolbox-outer').setOpacity(1);
		$('toolbox-login').removeClass("hide");
			$('toolbox-loading').setOpacity(1);
			$('toolbox-loading').removeClass("hide");		
			$('toolbox-login').setOpacity(0);	
		var myEffects = $('toolbox-expander').effects({duration: 500, transition:Fx.Transitions.Sine.easeInOut});
		myEffects.start({'top': [-420,0]});
		$('toolbox').addClass("active");
		if (isIE6var){
			$$('select').addClass("hide");
		};
		isMyAccountOpen = true;
		var basketDelay = showMyAccount.delay(500); //wait 5 seconds and executemy function.
	} else {
		document.location.href = '/members/?action=myaccount';
	}
}

	function showMyAccount() {
		var hideLoader = new Fx.Style('toolbox-loading', 'opacity').start(1,0);	
		var showBasket = new Fx.Style('toolbox-login', 'opacity').start(0,1);
	}
	
	function hideMyAccount() {
		var hideLoader = new Fx.Style('toolbox-loading', 'opacity').start(0,1);	
		var showBasket = new Fx.Style('toolbox-login', 'opacity').start(1,0);
	}	
	
// 1312 function to close the tool box
function closeToolBox() {
	var myEffects = $('toolbox-expander').effects({duration: 500, transition:Fx.Transitions.Sine.easeInOut, onComplete: hideToolboxOuter});
	myEffects.start({'top': [0,-420]});
}

// 1312 function to reset the toolbox (runs after closeToolBox)
function hideToolboxOuter() {
	$('toolbox-outer').setOpacity(0);
	$('toolbox').removeClass("active");
	$$('select').removeClass("hide");
	isShoppingBagOpen = false;
	isMyAccountOpen = false;
	$('toolbox-shoppingBasket').addClass("hide");
	$('toolbox-login').addClass("hide");
	$('toolbox-loading').addClass("hide");
	if (openWhatNext!="") {	
		if (openWhatNext=="my-account") {
			openWhatNext="";
			openToolMyAccount();				
		} else if (openWhatNext!="my-account") {
			openWhatNext="";
			openToolBoxShoppingBasket();				
		} else {
			//
		}
	}
}
	
	
	
// --------------------------------------------------------------------------------------------------------------
	

// 1312 Shows the 'change currency' options on product detail page
// set the string to a var and grab exisiting
var currencyOptions = '<a href="#" onclick="changeCurrency(1)" >Sterling</a>/<a href="#" onclick="changeCurrency(2)">US Dollar</a>/<a href="#" onclick="changeCurrency(3)">Euro</a>';
var changeCurrencyHTMLvar = "";
var changeCurrecnyHTMLset = false;
// var to track the state of the currency changer
var currencyChangerActive = false;


// a function that we need to re run after its run, makes moo check the links inside the change currency div and add events, of course we keep changing the content and so the function needs to be run agian to recheck those links
function currencyChanger(changeCurrencyHTML) {
	
	if (changeCurrecnyHTMLset == false) {
		changeCurrencyHTMLvar = changeCurrencyHTML;
		changeCurrecnyHTMLset = true;
	}	
	
	$ES('a','change-currency').addEvents({
		'click': function(event){
			if(currencyChangerActive){
				//
				// send selection of currency to clever stuff here
				//	
				$('change-currency').setHTML("<em>Currency changed</em>");
				var resetDelay = resetCurrencySelector.delay(2000); 
			} else {
				// change to currency options
				$('change-currency').setHTML(currencyOptions);
				currencyChangerActive = true;
				currencyChanger();
			}
		}	
	});
}
	// quick reset function
	function resetCurrencySelector() {
		$('change-currency').setHTML(changeCurrencyHTMLvar);
		currencyChangerActive = false;
		currencyChanger();
	}

// --------------------------------------------------------------------------------------------------------------

// nav accordion 
// from the mootools demo page!
//var navAccordionShow = 0;

function navAccordionDo() {
	var navAccordion = new Accordion('h3.nav', 'ul.nav', {
		opacity: false,
		show: navAccordionShow,
		onActive: function(toggler, element){
			// events to happen when an element starts to show
			var isIE7 = window.ie7;
			if (isIE7) {
				element.addClass("navIE7Fix");
			}
		},
	 
		onBackground: function(toggler, element){
			// events to happen when an element starts to hide
			var isIE7 = window.ie7;
			if (isIE7) {
				element.removeClass("navIE7Fix");
			}
		}
	}, $('left'));
}


// --------------------------------------------------------------------------------------------------------------

//basket page - do the big accordion and add and remove titles etc.

function basketPageAccordion() {
		//boo - wont work in here for some reason	
}

// --------------------------------------------------------------------------------------------------------------

// content pages

function contentPageIsIE(isIE,isIE6) {
	if (isIE6){	$$('div.generic-text').addClass("generic-text-isIE6"); }
	if (isIE6){	$$('div.generic-text-top').addClass("generic-text-top-isIE6"); }
	if (isIE6){	$$('div.generic-text-bottom').addClass("generic-text-bottom-isIE6"); }
}

// --------------------------------------------------------------------------------------------------------------

// homepage autoscroller

function homePageAutoScroller(isIE6) {
	
	var l = $$('.btnBack').length - 1;
	
	$$('.btnBack').setOpacity(0.65);
	
	$$('.btnBack').each(function(el){		
		if (isIE6) {
			el.addClass("isIE6");	
		}
	});
	
	$$('.enter').addEvents({
		'mouseover': function(event){		
			$$('.btnBack').setOpacity(1);
		},
		'mouseout': function(event){
			$$('.btnBack').setOpacity(0.65);
		}		
	});
	
	$$('.btnBack').each(function(el){
		
		if (isIE6) {
			el.addClass("isIE6");	
		}
		el.addEvents({
			'mouseover': function(event){
				$(this).setOpacity(1);
			},
			'mouseout': function(event){
				$(this).setOpacity(0.65);
			}		
		});
	});
	
	new SmoothScroll(
		{ duration: 1000, transition: Fx.Transitions.Quad.easeInOut }
	);
	
}

// --------------------------------------------------------------------------------------------------------------

// product details functions

function productDetailFunctions() {
	var changeCurrencyHTML = $('change-currency').innerHTML;
	currencyChanger(changeCurrencyHTML);
	
	if($('thumbnail-strip')) {
		lis = $('thumbnail-strip').getElements('li');
		totalThumbs = lis.length-1;
	}
	
	$('thumbs-left').addEvents({
		'click': function(event){
			moveIt('next');
			return false;
		}	
	});
	$('thumbs-right').addEvents({
		'click': function(event){
			moveIt('prev');
			return false;			
		}	
	});	
	$('colour-options').addEvents({
		'change': function(event){
			moveIt(this.selectedIndex);
		}	
	});	
}

// --------------------------------------------------------------------------------------------------------------

// product list functions

function productListFunctions(isIE,isIE6) {
	// this next one is used here because ie7 cant yet to opacity on an alphatransparent png and ie6 cant do pngs - rewarding ff/safari users with a slight drop shadow
	if (isIE){	$('productList').addClass("isIE6"); }; 
	
	//1312 do product list list item roll over
	$('productList').getElements('li').addEvents({
		'mouseover': function(event){
			$(this).addClass("hover");
		},
		'mouseout': function(event){
			$(this).removeClass("hover");
		}		
	});	
}

// --------------------------------------------------------------------------------------------------------------

// determine the cross browser client width/height from: http://www.geekdaily.net/2007/07/04/javascript-cross-browser-window-size-and-centering/

var windowHeight = 0;
var windowWidth = 0;

function windowSize() {
	var w = 0;
	var h = 0;

	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	//return {width:w,height:h};
	windowHeight = h;
	windowWidth = w;
}

// --------------------------------------------------------------------------------------------------------------

// if the browser is bigger than 1024, make the ul width smaller that has the homepage splash images on it

window.onresize = homePageUlWidth;

function homePageUlWidth() {
	windowSize();
	var scrollBarWidth = getScrollerWidth();
	if (!isIE6var) {
		if (windowWidth > 1024) {
			windowWidth = windowWidth - scrollBarWidth;
			windowWidth = windowWidth + "px";
			//$('homepage-products').addClass('largeWindow');
			$('homepage-splashes').setStyle('width',windowWidth);
			$$('ul#homepage-splashes li').setStyle('width',windowWidth);
		} else {
			//$('homepage-products').removeClass('largeWindow');
			$('homepage-splashes').setStyle('width','993px');
			$$('ul#homepage-splashes li').setStyle('width','993px');
		}
	}
}

// --------------------------------------------------------------------------------------------------------------

// get scroll bar width from: http://www.fleegix.org/articles/2006/05/30/getting-the-scrollbar-width-in-pixels

function getScrollerWidth() {
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-3000px';
    scr.style.left = '-3000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    // Add the scrollbar
    scr.style.overflow = 'auto';
    // Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;

    // Remove the scrolling div from the doc
    document.body.removeChild(
        document.body.lastChild);

    // Pixel width of the scroller
    return (wNoScroll - wScroll);
}