// Fast trim
// USE the jQuery trim() method instead


// --- Do a cached currency conversion ---
function convertPrice(domIDOfCurrentPrice) {
	// Get current number-only value from the title attribute of domIDOfCurrentPrice
	// NOTE: this value NEVER changes and all calculations are actually done in GBP
	var currentValue = $(domIDOfCurrentPrice).attr('title');  
	var baseCurrency = "GBP";
	// ------------------------------------------------------------
	var cDetails = $.cookie("PE_currency_Details").split("=");
	var requiredCurrency = cDetails[0];
	if (baseCurrency==requiredCurrency) { 
		var formattedNewValue = parseFloat(currentValue).toFixed(2);  // no need to convert
		$(domIDOfCurrentPrice).html("&pound;"+formattedNewValue);     // but do need to make sure html is set
		return;
	}
	// First, try getting a cached value for this conversion from cookies
	var conversionName = "PE_"+baseCurrency+"2"+requiredCurrency;
	var conversionRate = $.cookie(conversionName);
	var d = new Date();
	// if conversion rate doesn't exist then we've either never seen it before or the cookie/conversion is too old/expired
	if ( conversionRate==undefined || conversionRate==null ) {
		$.ajax({
			url:'assets/templates/shoppingCart/convertCurrency.php',
			type:'POST',
			async:false,
			data: {
				'amount':1,
				'baseCurrencyCode':baseCurrency,
				'convertCurrencyCode':requiredCurrency
			},
			success:function(r) {
				//alert("retn:"+r);
				conversionRate=r;
			}
		});
		// store the value in a cookie for an hour
		$.cookie(conversionName, conversionRate, d.getTime()+3600, '/eco-ethical-fashion/')
	}
	// use the conversion value * price to make the conversion
	var newValue = conversionRate * parseFloat(currentValue);
	// Try formatting the new value
	var formattedNewValue=parseFloat( newValue ).toFixed(2);
	if (formattedNewValue==undefined || isNaN(formattedNewValue) || formattedNewValue==null) {
		// something's broken, try formatting the GBP value
		formattedNewValue = parseFloat( currentValue ).toFixed(2);
		if (formattedNewValue==undefined || isNaN(formattedNewValue) || formattedNewValue==null) {
			return;  // things are really fouled up: leave things as they are
		}
	} 
	// over-write the existing value at domIDOfCurrentPrice with the new price string
	var newCurrencySymbol = cDetails[1];
	$(domIDOfCurrentPrice).html(newCurrencySymbol+formattedNewValue);
}


$(document).ready(function() {

// -- MENU --
	// make whole width of li-tags clickable
	$('#menu li').click(function() {
		var a_url = $(this).find('a').attr('href');
		location.href = a_url;
		return false;
	});
	// Make menu li hover active even on IE
	$('#menu>ul>li').hover(
		function() { $(this).addClass('overLevel1LI'); },
		function() { $(this).removeClass('overLevel1LI'); }
	);
	$('#menu>ul>li ul>li').hover(
		function() { $(this).addClass('overLevel2LI'); },
		function() { $(this).removeClass('overLevel2LI'); }
	);
	// Put menu in the right place (the HTML has it at the end for SEO)
	$('#menuContainer').html( $("#menu") );
	$('#ajaxSearch_submit').parent().hide();
	// Make menu work for IE6
	if ( (BrowserDetect.browser).toString()=="Explorer" && (BrowserDetect.version).toString()=="6") {
		$('#menu>ul>li>ul').css({ 'position':'absolute', 'top':'19px', 'width':'200px', 'left':'-1px', 'display':'none', 'background-color':'#fff'});
		$('#menu>ul>li').hover(
			function() { $(this).children('ul').show().end().children('a').css({ 'color':'#fff', 'display':'inline', 'width':'100%' }); },
			function() { $(this).children('ul').hide().end().children('a').css({ 'color':'#987', 'display':'inline', 'width':'100%' }); }
		);
		// IE6 warning
		alert("WARNING: Your web browser is unsafe and should not be used for shopping on the internet, plus it contains well-known errors in the way it renders web pages."+"\n\n"+
			  "- Using your current web browser is like driving a car with faulty electrics, lazy steering and brakes that don't work very well.  The French and German governments have banned their staff from using it.  If at all possible, please consider changing to Firefox, Chrome or some other safer browser."+"\n\n"+
			  "- If you don't understand this message, it might be an idea to write it down and ask someone who will."+"\n\n"+
			  "- This warning will appear on every page of this website.");
	}
	
// -- CURRENCY --	
	// Get currencyDetails cookie, or ensure that it's set
	var currencyDetails = $.cookie('PE_currency_Details');
	if (currencyDetails=="" || currencyDetails==null) {
		var currencyName   = "GBP";
		var currencySymbol = "&pound;";	
		var d = new Date();
		var time = d.getTime()/1000;
		$.cookie('PE_currency_Details', currencyName+"="+currencySymbol, time+500000, "/eco-ethical-fashion/");
	} else {
		var cdBits = currencyDetails.split("=");
		var currencyName   = cdBits[0];
		var currencySymbol = cdBits[1];
	}
	// Activate the currency chooser HTML/JS
	$('#currencyChoiceControl span').click(function() {
		$('#currencyChooser').show();
		$('#currencyChooser').attr('action','assets/templates/shoppingCart/changeCurrencyChoice.php');
		$('#currencyChooser').attr('method','post');
	});
	$('form#currencyChooser input[type=submit]').click(function() {
		var cc = $('form#currencyChooser input:radio:checked').val();
		$.ajax({ 
			url:'assets/templates/shoppingCart/changeCurrencyChoice.php', 
			type:"POST", 
			data:{'currencyChoice':cc}, 
			success:function(r) { window.location.reload(); } });
		$('#currencyChooser').hide();
		return false; // kill the normal action
	});
	// Show header cart info
	var existingFieldNames = $.cookie("PE_cart_totals")
	if (existingFieldNames=="" || existingFieldNames==null) {
		existingFieldNames="0--0.00";
	}
	existingFieldNames = existingFieldNames.split("--");
	if (existingFieldNames.length==2) {
		var numItems = parseInt(existingFieldNames[0],10);
		var cartTot = (parseFloat( existingFieldNames[1] )).toFixed(2);
		if (cartTot==undefined || isNaN(cartTot)) { numItems=0; cartTot="0.00"; }
	} else {
		numItems=0; cartTot="0.00";
	}
	$('#numItems').html(numItems);
	$('#cartTot').attr("title",cartTot);
	$('#cartTot').html(currencySymbol+cartTot);
	// convert all prices
	$('.convertableCurrency').each(function() { convertPrice(this); });
	// pre-load flags for currency converter
	var flagName = ["flag_canada","flag_europe","flag_japan","flag_new_zealand","flag_singapore","flag_uk","flag_usa"];
	$.each(flagName, function(){
		var stub = this;
		var fname = "assets/images/IconsAndBackgrounds/"+stub+".png";
		var image = new Image();
		image.src = fname;
		$(image).load( function() {
			var $stub = $('#'+stub);
			$stub.attr('src',fname);
		});
	});
	// set current currency flag from currencyName cookie data
	var stub = "flag_uk";  // default
	if      (currencyName=="CAD") { stub="flag_canada"; }
	else if (currencyName=="EUR") { stub="flag_europe"; }
	else if (currencyName=="JPY") { stub="flag_japan"; }
	else if (currencyName=="NZD") { stub="flag_new_zealand"; }
	else if (currencyName=="SGD") { stub="flag_singapore"; }
	else if (currencyName=="USD") { stub="flag_usa"; }
	$('#currCurrencyFlag').attr('src',"assets/images/IconsAndBackgrounds/"+stub+".png");	

// -- SEARCH --
	// Search box : convert to general search
    var defaultValue = "Search";
	$('#ajaxSearch_input')
    .bind("focus", function(e) {
        if(defaultValue == $(this).val()) {
            $(this).val('');
            $(this).css({'background-color':'#f9f8f7','color':'#654'});
        }

    })
    .bind("blur", function(e) {
        if(!$(this).val()) {
            $(this).val(defaultValue);
            $(this).css({'background-color':'#fff','color':'#654'});
        }
    });
	$("#ajaxSearch_input").keypress(function (e) {
      if (e.which == 13) {
      		var searchValue = $('#ajaxSearch_input').attr('value');
      		var searchScope = "All";
      		var phpCall = "./php/doRealSearch.php";
      		var jsonObject = {'searchTextSent':searchValue, 'searchScope':searchScope};
      		doAjaxSearchCall(phpCall,jsonObject);
			return false;
		}
	});

// -- PAGE STATS? --
	if ($('#defaultCTA').length>0) {
		var docID    = $('input[name=docID]').val();
		var quantity = $('#quantityChooser').val();
		// Page visit
		$.ajax({
			url:'assets/templates/shoppingCart/StockItemStats.php',
			type:'POST',
			data:{
				'action':'pageView',
				'docID':docID,
				'quantity':1
			},
			success:function(r) { result = r; }
		});
	}
	// Setup Add to Cart - record click and then validate availability and sizing
	$('#defaultCTA').click(function() {
		// validate availability and sizing
		if ( $('select[name=choiceOfSize]').val()=="none" ) { alert("Please choose a size first. Thanks."); return false; }
		// record click
		var docID    = $('input[name=docID]').val();
		var quantity = $('#quantityChooser').val();
		$.ajax({
			url:'assets/templates/shoppingCart/StockItemStats.php',
			type:'POST',
			async:false,
			data:{
				'action':'addToCart',
				'docID':docID,
				'quantity':quantity
			},
			success:function(r) { result = r; }
		});
	});
	// Ensure user can't add "Choose" to cart, only an actual size choice
	if ($('#callToAction').length>0) { 
		var userC
	}
	
// OTHER
	$('div.promo').click(function() {
		var url = $(this).find('a').attr('href');
		location.href = url;
	});
	
	// stop annoying title popups
	var originalTitle="";
	$("a").hover(
		function() {
			originalTitle = $(this).attr("title");
			$(this).attr("title","");
			$(this).parent().addClass("hovered");
		},
		function() {
			$(this).attr("title",originalTitle);
			$(this).parent().removeClass("hovered");
		}
	);
});

