/**
 * @fileoverview Venda.Widget.CurrencyConverter - Show currency conversion beside price.
 *
 * All prices shown on screen will show a second alternative price in the currency selected 
 * The process of clicking a link will read each price in <venda_currsym> and convert each price to the 
 * required alternative currency using rates provided in XML from the European Central Bank 
 * Retain the user's choice of currency display when navigating throughout the site
 * by setting a cookie which is read and used to show the desired conversion on each screen 
 * Only show on product path screens, not to be implemented on the basket or throughout the checkout 
 *
 * @requires jQuery		/venda-support/js/external/jquery-1.2.2.js
 * @requires cookiejar	/venda-support/js/external/cookiejar.js
 *
 * To implement: wrap price with tag containing class 'convertprice' (can include original currency symbol)
 * <span class="convertprice"><venda_invtsell><span>
 * 
 * @author Hayley Easton <heaston@venda.com>
 */

//create CurrencyConverter namespace
Venda.namespace('Widget.CurrencyConverter');

/**
 * Stub function is used to support JSDoc.
 * @class Venda.Widget.CurrencyConverter
 * @constructor
 */
Venda.Widget.CurrencyConverter = function(){};

/**
 * Check if currency cookie is set onload and add class listeners. 
 */
jQuery.noConflict()(function() {
		Venda.Widget.CurrencyConverter.GetCookie();
		//add event listeners
		jQuery('.resetcurrency').click(function () { //any element with classname 'resetcurrency' will remove conversions
	      Venda.Widget.CurrencyConverter.Reset();
		  return false;
	    });
		jQuery('.loadcurrency').click(function () { //any element with classname 'loadcurrency' will look at the rel attribute value for the currency to convert to
	      var rel = jQuery(this).attr('rel');
		  if(typeof(rel)!=='undefined'){//only convert if rel is supplied
		  	Venda.Widget.CurrencyConverter.Load(rel);
			if(document.getElementById('currencyMessage')){
				jQuery("#currencyMessage").removeClass("re-waiHide");
				jQuery("#currencyMessage").addClass("currencyalert");
				// fade message away: after 3 seconds fade message out for 1 second, unless overridden in element
				var show = 3000;
				var overrideShow = jQuery('#tag-show').html();
				if(overrideShow!==""){show = overrideShow;}
				popupMessage=function(){
					var fade = 1000;
					var overrideFade = parseFloat(jQuery('#tag-fade').html());
					if(overrideFade!==""){fade = overrideFade;}
					jQuery("#currencyMessage").fadeOut(fade,resetState);
				};
				var clearMessage=setTimeout(popupMessage,show);
				resetState=function(){
					jQuery("#currencyMessage").removeAttr("style"); // this is set by fadeOut function
					jQuery("#currencyMessage").addClass("re-waiHide");
					jQuery("#currencyMessage").removeClass("currencyalert");
				};
			}
		  } 
		  return false;
	    });
	});

/**
 * Run conversion script if currency cookie is set. 
 */
Venda.Widget.CurrencyConverter.GetCookie = function() {
	Venda.Widget.CurrencyConverter.setCurr = new CookieJar({expires: 3600 * 24 * 7, path: '/'});
	var setCurr = Venda.Widget.CurrencyConverter.setCurr;
	if(setCurr.get("newCurr")!==null){
		var value = setCurr.get("newCurr");
		Venda.Widget.CurrencyConverter.Load(value);
	}
};

/**
 * Accesses XML and performs conversion
 * Identify prices to be converted and calculate new approx price
 * @param {String} currency to convert to
 */
Venda.Widget.CurrencyConverter.Load = function(whichRate) {
	//set cookie
	Venda.Widget.CurrencyConverter.setCurr.put("newCurr",whichRate);
	//access the XML to find the conversion rates
	jQuery.ajax({
	   url: jQuery('#tag-xml').html(),
	   dataType: "xml",
	   success: function(o){
			var newRate = 1;
			//loop through all the Cube elements
			jQuery(o).find('Cube').each(function(){
				var currencyXMLnode = jQuery(this).attr('currency');
				var rateXMLnode = jQuery(this).attr('rate');
				if(currencyXMLnode === "GBP"){
					gbpRate = parseFloat(rateXMLnode); //get NaN with Venda.Widget.CurrencyConverter.gbpRate
				}
				if(currencyXMLnode === "USD"){
					usdRate = parseFloat(rateXMLnode); //get NaN with Venda.Widget.CurrencyConverter.usdRate
				}
				if (typeof(whichRate) !== 'undefined' && currencyXMLnode === whichRate) {
					newRate = parseFloat(rateXMLnode); //get NaN with Venda.Widget.CurrencyConverter.newRate
				}
			});
			//now that we know the rates we can loop through all the prices and convert them
			doEachConversion(whichRate,newRate,gbpRate,usdRate);
	   }
	 });
	doEachConversion = function(whichRate,newRate,gbpRate,usdRate) {
		gbpRate = gbpRate*100000;
		usdRate = usdRate*100000;
		newRate = newRate*100000;
		//set new currency symbol
		var currSym = "";
		if (whichRate==="EUR"){currSym = "\u20AC";}
		if (whichRate==="GBP"){currSym="\u00A3";}
		if (whichRate==="USD"||whichRate==="AUD"||whichRate==="CAD"||whichRate==="HKD"||whichRate==="NZD"||whichRate==="SGD"||whichRate==="MXN"){currSym="\u0024";}
		if (whichRate==="JPY"||whichRate==="CNY"){currSym="\u00A5";}
		if (whichRate==="BGN"){currSym="\u043b\u0432";}
		if (whichRate==="CZK"){currSym="K\u010d";} 
		if (whichRate==="DKK"||whichRate==="EEK"||whichRate==="SEK"||whichRate==="NOK"){currSym="kr";}
		if (whichRate==="HUF"){currSym="Ft";}
		if (whichRate==="LTL"){currSym="Lt";}
		if (whichRate==="LVL"){currSym="Ls";}
		if (whichRate==="PLN"){currSym="z\u0142";}
		if (whichRate==="RON"){currSym="lei";}
		if (whichRate==="CHF"){currSym="CHF";}
		if (whichRate==="HRK"){currSym="kn";}
		if (whichRate==="RUB"){currSym="py\u0431";}
		if (whichRate==="TRY"){currSym="YTL";}
		if (whichRate==="BRL"){currSym="R\u0024";}
		if (whichRate==="IDR"){currSym="Rp";}
		if (whichRate==="INR"){currSym="\u20A8";}
		if (whichRate==="KRW"){currSym="\u20A9";}
		if (whichRate==="MYR"){currSym="RM";}
		if (whichRate==="PHP"){currSym="\u20B1";}
		if (whichRate==="THB"){currSym="\u0E3F";}
		if (whichRate==="ZAR"){currSym="R";}
		if (jQuery(document.body).find('.convertedprice').length>0){ //if converted prices already shown, remove them first so they can generate again
			jQuery('.convertedprice').remove();
		}
		priceSelectors = jQuery('#tag-priceselectors').html();
		jQuery(priceSelectors).each(function (i) { // for each class name run the following
			var classInner = jQuery(this).html();
			var convertedPrice = classInner.replace(/[^0-9]/g, '');
			//turn into integers and do the calculation as whole numbers
			if(convertedPrice!==""){
				convertedPrice = convertedPrice*1000;
				var currsym = jQuery('#tag-currsym').html();
				if(currsym==="£"){
					convertedPrice = ((convertedPrice/gbpRate)*newRate)/100000;
				}
				if(currsym==="$"){
					convertedPrice = ((convertedPrice/usdRate)*newRate)/100000;
				}
				if(currsym==="€"){
					convertedPrice = (convertedPrice*newRate)/10000000000;
				}
				convertedPrice = convertedPrice.toFixed(2);
				var prefixChar = jQuery('#tag-prefixChar').html();
				if(prefixChar!==null){
					prefixChar=prefixChar;
				}else{
					prefixChar="";
				}
				var suffixChar = jQuery('#tag-suffixChar').html();
				if(suffixChar!==null){
					suffixChar=suffixChar;
				}else{
					suffixChar="";
				}
				var pid = jQuery(this).parents('[id$=currencyMessage]').attr("id");
				if(pid==="currencyMessage"){prefixChar=""; suffixChar="";}// this removes characters from popup message
				var newSpan = jQuery('<span class="convertedprice">'+prefixChar+currSym+convertedPrice+suffixChar+'</span>');
				jQuery(this).after(newSpan);
				var hidedefault = jQuery('#tag-hidedefault').html();
				if (hidedefault==="1"){
					jQuery(this).css("display","none");
				}
			}
		});
	};	
};

/**
 * Remove the currency conversion. 
 */
Venda.Widget.CurrencyConverter.Reset = function() {
	//remove the cookie and the converted prices
	Venda.Widget.CurrencyConverter.setCurr.remove("newCurr");
	jQuery('.convertedprice').remove();
	var hidedefault = jQuery('#tag-hidedefault').html();
		if (hidedefault==="1"){
			var priceSelectors = jQuery('#tag-priceselectors').html();
			jQuery(priceSelectors).each(function (i) { // for each class name run the following
			jQuery(this).css("display","");
		});
	}
};