var prefix=location.protocol+"//"+location.host;

var tld=".com";
//var tld=".lan";

var transitionSpeed=400;
var fadeElement="div#container";
var contentElement="div#content";

var requiredMajorVersion = 9;
var requiredMinorVersion = 0;
var requiredRevision = 28;

var basketUpdateTimeout;

var showcaseImageIndex=1;
var propResizing;
var showcaseImageW=0;
var showcaseImageH=0;
var widowResizeBinding=false;

var noisy=false;
//noisy=true;

var payload;
var urltoget="";

var openingPage;
var pageTitle="";

var currenturl;
var rssUrl;

var lastLoadedShowcase="";


function setupSpecBox() {
	if(jQuery('#specboxcontent').length) {
		jQuery('#productinfonav>span.prev').hide();
		bindSpecBoxNext();
	}
}

function bindSpecBoxNext() {
	jQuery('div#productinfonav>span.next').bind('click',function(i){
		jQuery('#specboxcontent').stop(true,true);
		jQuery('#productinfonav>span.prev').fadeIn(transitionSpeed);
		jQuery('#productinfonav>span.next').fadeOut(transitionSpeed);
		jQuery('#specboxcontent').animate(	{	marginLeft: '-218px' },
											{	duration: 	transitionSpeed,
												complete:	function(i){
													jQuery('#productinfonav>span.next').unbind();
													bindSpecBoxPrev();
												} } );
	});
}
function bindSpecBoxPrev() {
	jQuery('div#productinfonav>span.prev').bind('click',function(i){
		jQuery('#specboxcontent').stop(true,true);
		jQuery('#productinfonav>span.prev').fadeOut(transitionSpeed);
		jQuery('#productinfonav>span.next').fadeIn(transitionSpeed);
		jQuery('#specboxcontent').animate(	{	marginLeft: '0px' },
											{	duration: 	transitionSpeed,
												complete:	function(i){
													jQuery('#productinfonav>span.prev').unbind();
													bindSpecBoxNext();
												} } );
	});
}

jQuery(document).ready(function(){	
  jQuery("#FlashOver").hide();// hide the teaparty	
//  jQuery.ajaxHistory.initialize();
	updateBasketImageHTML();
	basketTogglerSetup();
	rssTogglerSetup();
	feedbackShareSetup();

	currenturl=window.location.href;


  // do we need to pull in a page?
	if ((window.location.hash)&&(window.location.hash.length>=1)) {
		jQuery(contentElement).html("");
    jQuery(fadeElement).hide();

    openingPage=currenturl=prefix+tld+getSlug(String(window.location.hash.substr(1)));
    openingPage=window.location.hash.substr(1);
    jQuery.ajaxHistory.initialize(loadPage(openingPage,true));

		loadPage(getSlug(openingPage) ,true);
	} else {
    openingPage=getSlug(String(window.location.href));
	  jQuery.ajaxHistory.initialize();
    whinealert("Start - ajaxifying links");
		setTimeout("finishInitialisation();",200);
		setTimeout("finalizeInitializeBackground();",200);
  }
});

function finishInitialisation() {
	initialiseAccordions();
	ajaxifyLinks();
	bindAddToCart();
	updateTeaPartyVisibility();
	setupShowcaseImage();	
	setupSpecBox();
}


function bindAddToCart() {
	if(jQuery("#purchaseform").length>0) {
		jQuery('#purchaseform').unbind();
		jQuery("#purchaseform").submit(function(e){
			whinealert("submit pressed on addtobasket");
			doAddToCart();
			e.preventDefault();
		});
		whinealert("bound purchas form");
	} else {
		whinealert("no purchase form!");
	}
}

function doAddToCart() {
	whinealert("doAddToCart");
	var form=jQuery("form#purchaseform");
	var formdata=form.serialize();

	var formaction="/index.php"; //jQuery("#purchaseform").attr("action");
	formaction+="?ajax=true&user=true";
	
	jQuery.post(formaction,formdata,function(response){
		eval(response);
		basketOver(); // trigger a basket update
		if (basketUpdateTimeout) {
			clearTimeout(basketUpdateTimeout);
		}
		basketUpdateTimeout=setTimeout("basketOut()",5000);
	});
}

function initialiseAccordions() {
  if (jQuery("ul.accordionelement").length>0) {
		jQuery("ul.accordionelement").accordion({ 
	    active: false, 
	    header: '.head', 
	    navigation: true, 
	    event: 'mouseover', 
	    fillSpace: false,
	    autoHeight: false,
      animated: 'slide' 
		}).activate(0);
	}
	return;	
}

function basketTogglerSetup() {
	// bind events
	jQuery("#punbasket").unbind();
	jQuery("#punbasket").bind("mouseover", function(e) {
		basketOver();
		rssOut();
	});
	jQuery("#wlkbasketouter").hide();
}

function rssTogglerSetup() {
	jQuery("#punrss").bind("mouseover", function (e) {
		rssOver();
		basketOut();
	});
	jQuery("#wlkrssouter").bind("mouseleave", function (e) {
		rssOut();
	});
	jQuery("#wlkrssouter").hide();
}

function basketOver() {
	if (hasBasketContents()==true) {
		jQuery("#wlkbasketouter").fadeIn(function(){
			jQuery("#wlkbasketouter").bind("mouseleave", function(e) {
				basketOut();
			});
		});
	}
	if (basketUpdateTimeout) {
		clearInterval(basketUpdateTimeout);
		basketUpdateTimeout=undefined;
	}
}
function basketOut() {
	jQuery("#wlkbasketouter").fadeOut();
	jQuery("#wlkbasketouter").unbind();
	if (hasBasketContents()) {
		jQuery("#punbasket").bind("mouseover", function(e) {
			basketOver();
			rssOut();
		});	
	} else {
		jQuery("#punbasket").unbind();
	}
	if (basketUpdateTimeout!=undefined) {
		clearInterval(basketUpdateTimeout);
		basketUpdateTimeout=undefined;
	}
}

function emptyCart() {
	whinealert("emptycart! nav to "+currenturl+"?category=&cart=empty");
	jQuery.post(currenturl+"?category=&cart=empty",{"ajax":"true","user":"true"},function(data){emptyCartEndpoint();});
	whinealert("emptycart routine over!");
	return(false);
}
function emptyCartEndpoint() {
	whinealert("emptycart endpoint");
	jQuery("table.shoppingcart").parent().html("");
	updateBasketImageHTML();
	return(false);
}

function updateBasketImageHTML() {
	jQuery("#punbasket").unbind();	
	//updateBasketImageHTML();
	if (hasBasketContents()==true) {
		whinealert("making basket clickable");
		jQuery("#punbasket").html('<a href="#"><img src="/static/template.png" alt="your shopping basket" /></a>');
		//basketTogglerSetup();
	} else {
		whinealert("making basket DUMB");
		jQuery("#punbasket").html('<span><img src="/static/template.png" alt="your basket is empty."></span>');
		jQuery("#punbasket").unbind();		
		jQuery("#wlkbasketouter").unbind();
		jQuery("#wlkbasketouter").fadeOut();
	}
	ajaxifyLinks(); // update checkout links, etc
}

function hasBasketContents() {
	if (jQuery("table.shoppingcart").length>0) {
		return(true);
	} else {
		return (false);
	}
}

function rssOver() {
	jQuery("#wlkrssouter").fadeIn();
	jQuery("li#punrss a").addClass("open");
}
function rssOut() {
	jQuery("#wlkrssouter").fadeOut();	
	jQuery("li#punrss a").removeClass("open");
}

///function handleChromeNavigation() {
///	whinealert("nov going to "+document.location.hash);
///	// implicitly - this has to be a 'back' event, we cannot parse forward.
///	if (navhistory.length>1) {
///			var url=navhistory[navhistory.length-1];
///			doAjaxPageLoad(prefix+url,url,true);
///			return(false);
///	}
///}

function getFlashMovie(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  return (isIE) ? window[movieName] : document[movieName];	
}

function ajaxifyLinks() {
	jQuery("a").not("a.sharing").not("a.norewrite").unbind();
	jQuery("a").not("a.sharing").not("a.norewrite").bind("click",handleAjaxifiedLink);
	if (jQuery("input#zipcode").length>0) {
		jQuery("form").unbind();
		jQuery("#current_country").unbind();
		jQuery("form#change_country_form").bind('submit', function(e) {handleAdjustFormChange; e.preventDefault(); });
		jQuery("form.adjustform").bind('submit', function(e) {handleAdjustFormChange(); e.preventDefault(); });
		jQuery("#current_country").bind('change',function(e) {handleShippingChange(); e.preventDefault(); });
	}
}

function handleAdjustFormChange(e) {
	var values = jQuery(".adjustform").formHash();
	jQuery.post(  currenturl,
								values,
								function(data, status) {
									performHandleLoadPage(currenturl, prefilterLoadPage(data) );
								},
								"html"
							);
}

function handleShippingChange(e){
	var values=jQuery("#change_country_form").formHash();
	jQuery.post(  currenturl,
								values,
								function(data, status) {
									performHandleLoadPage(currenturl, prefilterLoadPage(data) );
								},
								"html"
	);
}

function handleAjaxifiedLink(e) {
	whinealert("link requested by "+e.currentTarget+" to go to "+getSlug(e.currentTarget.href));
	var dest=(typeof(e.target.href)!="undefined")?e.target.href:e.currentTarget.href;
	if (dest.length<1) {
		e.preventDefault();
		return(false);
	}
	if ( (dest.substr(0,18)!="http://welovekaoru") || (dest.substr(0,6)=="mailto") ) {
		// not an ajaxable link - let it rhough.
		whinealert("not ajaxable - "+dest);
		return(true);
	}
	if (dest.charAt(0) != "#") {
    loadPage(getSlug(dest));
		e.preventDefault();// do not follow!
	} else {
		e.preventDefault();
	}
	return(false);
}

function loadPage(url,historical) {
///	if (navhistory.length>0) {
///		whinealert("current="+ navhistory[navhistory.length-1] + "  req="+url);
///		if (navhistory[navhistory.length-1]==url) {
///			whinealert("you're already there!");
///			return(false);
///		}
///	}
///	navhistory.push(url);
	urltoget=prefix+url;
	currenturl=urltoget;
	whinealert("urltoget="+urltoget);

	lastLoadedShowcase="";
	
	if (historical!=true) {
		window.location.hash = url; // 20 feb 2008
		jQuery.ajaxHistory.update("#"+url);
	}
	
	// send the request
	doAjaxPageLoad(urltoget,url);
}

function doAjaxPageLoad(urltoget,url) {
	whinealert("ajaxing to "+urltoget+" !");
///	if (back) {
///		navhistory.pop;
///	}
	jQuery.ajax({async: true, // async
		//beforeSend: , // beforeSend
		//cache:true, // cache
		//complete:, // completion callback - could be error, could be success
		//contentType:,// contentType for sends
		//data:,// get parameters (string or key/val array)
		dataFilter:prefilterLoadPage,
		//dataType:"html", // expected data response 
		error:handleLoadPageError, // error handler
		//global:true, // handle events globally?
		ifModified:false, // success only if response changed since last version
		//jsonp:, // jsonp - overridden callback for a jsonp request
		//password:"", // password for http auth request
		//processData:true, // processData - do we want to send non-processed data?
		//scriptCharset:, // scriptCharset
		success:function(data,textStatus) {
			handleLoadPage(url,data);
		}, // success function callback- params "data", "textStatus"
		timeout:20000, // timeout
		type:"GET", // request type
		url:urltoget, // url of request
		//xhr:, // creation callback
		padding:null
	});
}

function getSlug(url) {
	var slug=url.substring(url.indexOf(tld+"/")+(url.indexOf(tld+"/")>=0?tld.length:0));
	return(slug);
}

function prefilterLoadPage(data,type) {
	var e=/<title>([^<]*)/;
	var m=data.match(e);
	if (m[1]) {
		pageTitle=m[1];
	}
	var out=jQuery(data).find(contentElement); // was contentElement

	return(out[0].innerHTML);
}

function handleLoadPage(url,data) {
//	if (data.length) {

//	} else {
//		whinealert("empty jquery payload!");
//	}
	performHandleLoadPage(url,data);
}

function handleLoadPageError(xhr, es) {
	if (es=="notmodified") {
		performHandleLoadPage(urltoget,prefilterLoadPage(xhr.responseText));
		return;
	}
	whinealert("error loading data - error:"+es);	
}

function performHandleLoadPage(url,data) {
	
	whinealert("changing hash to "+getSlug(url) );
//#	window.location.hash = getSlug(url);
		
//	$k.swfobject.removeSWF("flashOverSWF");		

//	$j("#FlashOverSWF").fadeOut(transitionSpeed);
		
	payload=data;
	whinealert(fadeElement+" : count = "+jQuery(fadeElement).length);
	jQuery(fadeElement).fadeOut(transitionSpeed, function() {

		jQuery(contentElement).html(payload); // was replaceWith
		
		initialiseAccordions();
		ajaxifyLinks();
		bindAddToCart();
		
		document.title=pageTitle;
		
		payload=undefined;

		whinealert("setting timeOut");		
		setTimeout("introduceLoadPage();",200);
	});
	
}

function introduceLoadPage() {
	whinealert("introduceLoadPage");
	if (jQuery("#showOverSWF").length>0) {
		showOverSWF();
	} else {
		hideOverSWF();
	}
  updateTeaPartyVisibility();
  setupShowcaseImage();
  setupSpecBox();

/*	if (jQuery("#BackgroundHandler").length>0) {
		whinealert("backgroundHandler checking...");
		whinealert("backgroundHandler found!"+" class="+jQuery("#BackgroundHandler").attr("class") );*/
//		jQuery("#FlashUnderSWF").setState(jQuery("#BackgroundHandler").attr("class") );

		setTimeout("finalizeInitializeBackground();",200);

/*		if (getFlashMovie("FlashUnderSWF")) {
			performFlashSetState();
//			jQuery(this).css({visibility:"hidden"});
		} else {
// do it again later.
			setTimeout("finalizeInitializeBackground()",200);
		}*/
	/*}*/
	finishLoadPage();	
}

function finalizeInitializeBackground() {
	if (getFlashMovie("FlashUnderSWF")) {
		performFlashSetState();
		return;
	} else {
		setTimeout("finalizeInitializeBackground();",200);
	}
}

function performFlashSetState() {
	if (getFlashMovie("FlashUnderSWF")) {
		getFlashMovie("FlashUnderSWF").setState(
			((jQuery("#BackgroundHandler").length>0)?jQuery("#BackgroundHandler").attr("class"):"")
		);
	}
}

function finishLoadPage() {
//	jQuery(this).dequeue();	
	whinealert("finishLoadPage called!");
//	var fx=jQuery(fadeElement).queue("fx");
	jQuery(fadeElement).fadeIn(transitionSpeed, function(){
		updateTeaPartyVisibility();
//		setupShowcaseImage();		
	});
}


/////

function updateTeaPartyVisibility() {
//  whinealert("updateTeaPartyVisibility: #showOverSWF.length="+jQuery("#showOverSWF").length );
	if (jQuery("#showOverSWF").length>0) {
		showOverSWF();
	} else {
    	hideOverSWF();
	}
}

function hideOverSWF() {
	whinealert("hideOverSWF() invoked");
	jQuery("#FlashOver").fadeOut();
	var flo=getFlashMovie("FlashOverSWF");
	if ((flo)&&(flo.suspend)) {
		flo.suspend();
  }
}

function showOverSWF() {
	whinealert("showOverSWF() invoked");
  jQuery("#FlashOver").fadeIn();
	// message it to start
	var flo=getFlashMovie("FlashOverSWF");
	if ((flo)&&(flo.resume)) {
		flo.resume();
  }
}

function embedTeaParty() { 
	flashvars={};
	params={};
	params.wmode='opaque';
	jQuery.swfobject.embedSWF("/static/intro.swf","FlashOverSWF", "100%", "100%", "9.0.0", "expressInstall.swf", flashvars, params );
}

/////

function whinealert(whine) {
	if (noisy) {
		alert(whine);
		if(console.log) {
			console.log(whine);
		}	
	}
}

function setupShowcaseImage() {
	whinealert('setupShowcaseImage() invoked');
	showcaseImageIndex=1;
  if(jQuery("div#thumbnailstrip").length>0) {
    if(jQuery("div#thumbnailstrip div span").length>0) {
	    // this is a product page
		  jQuery("div#productimagethumbbox div.nextarrow span").unbind().bind("click",function(){
		  	if(getShowcaseImageIndex()<3) {
		  		goShowcaseImageOffset(1);
		  	} 
	  	});
		  jQuery("div#productimagethumbbox div.previousarrow span").unbind().bind("click",function(){
		  	if(getShowcaseImageIndex()>1) {
		  		goShowcaseImageOffset(-1);
		  	}
	  	});
	  	if (widowResizeBinding==false) {
				jQuery(window).resize(function(){
					proportShowcaseImageImg();
				});
			}
			// load the image
      showcaseImage(1);
		}
  }
}

var vpw;
var vph;
var ratio;
var smallAxisW;
var newwidth;
var newheight;
var calcOkay;

function proportShowcaseImageImg() {
	if ((!propResizing)&&(showcaseImageW>0)) {
		propResizing=true;
		calcOkay=false;
	
		vpw = jQuery("#productimage").width();
		vph = jQuery("#productimage").height();
		smallaxisW = ( vpw < vph ? false : true );
		// work out proportion to scale showcaseImageSmallaxis to vpSmallaxis
		ratio = (smallaxisW ? vpw / showcaseImageW
													: vph / showcaseImageH);
		while(calcOkay==false) {
			newwidth  = Math.floor(showcaseImageW * ratio);
			newheight = Math.floor(showcaseImageH * ratio);
			
			if(newheight<vph) {
				ratio=ratio*1.05;
			} else {
				calcOkay=true;			
			}
		}	
		jQuery("#productimage img").width(  newwidth+ "px" ).height( newheight+"px" );
		jQuery("#productimage img").css("left",0-(Math.abs(Math.floor((vpw-newwidth) /2)))+"px").
			css("top", 0-(Math.abs(Math.floor((vph-newheight)/2)))+"px");
	
		propResizing=false;
	}
}

function getShowcaseImageUrl() {
	return("/static/"+jQuery("div#productimagebox").attr("title")+"_"+getShowcaseImageIndex()+".jpg");
}

function loadShowcaseImage() {
	if((lastLoadedShowcase=="")&&(lastLoadedShowcase!=getShowcaseImageUrl())) {
		showcaseImageFadeoutComplete=false;
		jQuery("#productimage").fadeOut(transitionSpeed, function(){
			showcaseImageFadeoutComplete=true;
			showcaseImageW=showcaseImageH=0;
		
			performLoadShowcaseImage();

		});
	}
}

function performLoadShowcaseImage() {
	whinealert("ASKED TO LOAD: "+getShowcaseImageUrl() );
	if(lastLoadedShowcase!=getShowcaseImageUrl()) {
		lastLoadedShowcase="";
		showcaseImageImg=new Image();
		jQuery(showcaseImageImg).load(function(){
			injectShowcaseImageIMG();
		}).error(function(){
			//whinealert("FAILED LOAD!");
		}).attr('src', getShowcaseImageUrl() );
	}
}

function injectShowcaseImageIMG() {
	if(showcaseImageFadeoutComplete==true) {
		if (showcaseImageImg.width) {
			showcaseImageW=showcaseImageImg.width;
			showcaseImageH=showcaseImageImg.height;
			jQuery("#productimage").html(showcaseImageImg);
			proportShowcaseImageImg();
			jQuery("#productimage").fadeIn(transitionSpeed);
			return;
		}
	// try again
	setTimeout("injectShowcaseImageIMG()",transitionSpeed);
	}
}

function activateShowcaseImage(k) {
  jQuery("div#thumbnailstrip div."+k+" span").removeClass("active notactive").addClass("active");
}
function deactivateShowcaseImage(k) {
  jQuery("div#thumbnailstrip div."+k+" span").removeClass("active notactive").addClass("notactive");
	jQuery("div#thumbnailstrip div."+k).unbind().bind("click",function(){goShowcaseImage(k);});
}

function showcaseImage(k) {
	for(var i=1; i<4; i++) {
		if (k==i) {
			activateShowcaseImage(i);
		} else {
			deactivateShowcaseImage(i);
		}
	}
	jQuery("div#productimagethumbbox div.previousarrow span").removeClass("available");
	if(k>1) {jQuery("div#productimagethumbbox div.previousarrow span").addClass("available");};
	jQuery("div#productimagethumbbox div.nextarrow span").removeClass("available");
	if(k<3) {jQuery("div#productimagethumbbox div.nextarrow span").addClass("available");};
	loadShowcaseImage();
}
function goShowcaseImage(k) {
	showcaseImageIndex=k;
	showcaseImage(showcaseImageIndex);
}
function goShowcaseImageOffset(offset) {
	showcaseImageIndex+=offset;
	showcaseImage(showcaseImageIndex);
}
function getShowcaseImageIndex() {
	return(showcaseImageIndex);
}
function doShare(shareUrl) {
	var url=shareUrl;
	url = url.replace("XXX",currenturl?currenturl:prefix+tld);
	url = url.replace("YYY","welovekaoru");
	url = url.replace("ZZZ",rssUrl);
	window.location.href = url;
}

function capitaliseAndReturnFirstWord(tocap) {
	var str=tocap.split(" ")[0];
	str=str.substr(0,1).toUpperCase() + str.substr(1);
	return(str);
}

function feedbackShareSetup() {
	jQuery('a.sharing').bind("mouseenter",function(e){
		var title = capitaliseAndReturnFirstWord(e.target.parentNode.className)+
			" with<br/>"+ e.target.title;
		jQuery('div#subscribe div.feedback').html( title );
//			e.target.parent().attr("class").substr(0, 1).toUpperCase() +
//			e.target.parent().attr("class").substr(1)+
//			" with "+e.target.parent().attr("title")
/*			e.target.parentNode.className.substr(0, 1).toUpperCase() +
			e.target.parentNode.className.split(" "substr(1, (e.target.parentNode.className.indexOf(" ")?e.target.parentNode.className.indexOf(" "):null))+
			" with "+e.target.parentNode.title

); */
	});
	jQuery("a.sharing").bind("mouseleave",function(e){
		jQuery("div#subscribe div.feedback").html("");
	});
}
