var E4x = {
    showPopupOnClick:  false,
    
    showPopupOnLinkClick: function(container){
        //set this to true when explicitly clicking and opening context chooser
    	E4x.showPopupOnClick = true;
    	
    	E4x.initialize(container);
    },
    
	initialize : function(container) {
    	this.container = container;
		this.ajaxUpdateHandler = this.ajaxUpdate.bind(this);
		
		var loc = window.location + '';
        if(loc.indexOf('secure') < 0 )
        {
 		    if (true) {
			    this.url = '/WebServices/RenderControls.aspx?control=E4x';
			    this.ajaxUpdateHandler();
		    }
		}
		else
		{ 
		   if (true) {
			    this.url = '/WebServices/RenderControlsSecure.aspx?control=E4x';
			    this.ajaxUpdateHandler();
		    }
		}
 
	},

	ajaxUpdate : function() {
		
		new Ajax.Request(this.url, {
			onComplete : function(transport) {
				var result = RemoveScriptFromAjaxResponse(CleanAjaxResponse(transport.responseText));
				if(transport.status == 200) {
					this.container.update(result);
					E4x.popupDiv();
    			} 
			}.bind(this),
			method:'post'
		});

	},
    popupDiv: function() {
        var cookies = new CookieManager();
        var ipCountry = cookies.getValueIgnoreCase('IPCountry');
        if(E4x.showPopupOnClick ||(typeof(ipCountry)!= "undefined" && ipCountry != "US") )
		{
            var myAnnouncement = new Dialog.Box($('E4x'));
            myAnnouncement.show();
        }
        else
        {
        $('E4x').hide();
        }
    },
    setFlag: function() {
        var cookies = new CookieManager();
        var country = cookies.getValueIgnoreCase('Country')||"US";
        var img = $('imgFlag');
        if(country!= "US")
        {         
        img.src="/Images/e4xFlags/" + country + ".gif";
        }
        else
        {
        img.src="../../Images/Shopping/spacer.gif";
        }
    },
    e4xPopup: function() {
        var cookies = new CookieManager();
		var ipCountry = cookies.getValueIgnoreCase('IPCountry');
		 
	    var img = $('imgFlag');
	    if(img != null)
	    {    
        E4x.setFlag();
		Event.observe('imgFlag', 'click', E4x.showPopupOnLinkClick.bind(E4x, $$('div.E4x').first()));
		}
	
        if(typeof(ipCountry) == "undefined")
		{
		 Event.observe(window, 'load', E4x.initialize.bind(E4x, $$('div.E4x').first()));
		}
	}
	
};


// for light box effect
var Dialog = {};
Dialog.Box = Class.create();
Object.extend(Dialog.Box.prototype, {
	initialize: function(id) {
		this.createOverlay();

		this.dialog_box = $(id);
		this.dialog_box.show = this.show.bind(this);
		this.dialog_box.hide = this.hide.bind(this);

		this.parent_element = this.dialog_box.parentNode;

		this.dialog_box.style.position = "absolute";

		var e_dims = Element.getDimensions(this.dialog_box);
		var b_dims = Element.getDimensions(this.overlay);
		this.dialog_box.style.left = '300px';
		//((b_dims.width/2) - (e_dims.width/2)) + 'px';
		this.dialog_box.style.top = '100px';

		this.dialog_box.style.zIndex = this.overlay.style.zIndex + 1;

	},

	createOverlay: function() {
		if($('dialog_overlay')) {
			this.overlay = $('dialog_overlay');
		} else {
			this.overlay = document.createElement('div');
			this.overlay.id = 'dialog_overlay';
			Object.extend(this.overlay.style, {
				position: 'absolute',
				top: 0,
				left: 0,
				zIndex: 90,
				width: '100%',
				backgroundColor: '#000',
				display: 'none'
			});
			document.body.insertBefore(this.overlay, document.body.childNodes[0]);
		}
	},

	moveDialogBox: function(where) {
		Element.remove(this.dialog_box);
		if(where == 'back')
		this.dialog_box = this.parent_element.appendChild(this.dialog_box);
		else
		this.dialog_box = this.overlay.parentNode.insertBefore(this.dialog_box, this.overlay);
	},

	show: function() {
		this.overlay.style.height = Element.getDimensions(document.body).height+'px';
		this.moveDialogBox('out');
		//this.overlay.onclick = this.hide.bind(this);
		this.selectBoxes('hide');
		new Effect.Appear(this.overlay, {duration: 0.1, from: 0.0, to: 0.3});
		this.dialog_box.style.display = '';
	},

	hide: function() {
		this.selectBoxes('show');
		new Effect.Fade(this.overlay, {duration: 0.1});
		this.dialog_box.style.display = 'none';
		this.moveDialogBox('back');
		$A(this.dialog_box.getElementsByTagName('input')).each(function(e){if(e.type!='submit')e.value=''});
	},

	selectBoxes: function(what) {
		$A(document.getElementsByTagName('select')).each(function(select) {
			Element[what](select);
		});

		if(what == 'hide')
		$A(this.dialog_box.getElementsByTagName('select')).each(function(select){Element.show(select)})
	}
});

  
var E4XClient = {

	displayPrices: function() 
	{
		var cookieManager = new CookieManager();		
		var userCurrency = cookieManager.getValueIgnoreCase('Currency') || "USD";
		
		//Loop Through All Prices, setting the innerHTML to the correct price.
		$$(".e4xprice").each(
			function(e) { e.innerHTML = e.attributes["e4xprice_" + userCurrency].value;	}
		);		
	},
	displayFreeShipping: function() 
	{
		var cookieManager = new CookieManager();		
		var userCountry = cookieManager.getValueIgnoreCase('Country') || "US";
		
		if(userCountry != "US")
		{
		    $$(".e4xshipping").each(
			    function(e) { e.innerHTML = e.attributes["e4xshipping_International"].value;	}
		    );		
		}
		else
		{
		    $$(".e4xshipping").each(
			    function(e) { e.innerHTML = e.attributes["e4xshipping_Domestic"].value;	}
		    );		
		}	
	},
	fixOnSiteSearch: function() 
	{
		var cookieManager = new CookieManager();		
		var userCountry = cookieManager.getValueIgnoreCase('Country') || "US";
		
		var nInputs = document.getElementsByName("N");
		if (nInputs && nInputs.length != 0) 
		{
			var searchNValueInput = nInputs[0];
			if (searchNValueInput && userCountry != "US") 
			{
				if ($("E4xAllowedDimension")) 
				{
					searchNValueInput.value = $("E4xAllowedDimension").value || "0";
				} else {
					searchNValueInput.value = "0";
				}
			}
		}
	},
	
	hideInfo: function() 
	{
		var cookieManager = new CookieManager();		
		var userCountry = cookieManager.getValueIgnoreCase('Country') || "US";
		if (userCountry != "US") 
		{
			//Hide BML Info on Prod Details Page.
			if ($$("div.bmlBoxWrap").length > 0) { $$("div.bmlBoxWrap").first().hide(); }
			//Hide Lowest Price Guarantee Info.
			if ($("lpg")) { $("lpg").hide(); }
			//Hide Ships Same day.
			if ($("sameday")) { $("sameday").hide(); }
			//Hide Free Shipping
			if ($("freeship")) { $("freeship").hide(); }			
		}
	},

	reloadPage: function(reloadFlag) 
	{
		//Basically, check if we are on the results page.
		if ($("e4xDomesticUrl") && $("e4xInternationalUrl") && $("e4xInternationalView"))
		{
			var cookieManager = new CookieManager();		
			var userCountry = cookieManager.getValueIgnoreCase('Country') || "US";

			if (userCountry != "US" && $("e4xInternationalView").value == "False") 
			{
				window.location = $("e4xInternationalUrl").value;
			}
			else if (userCountry == "US" && $("e4xInternationalView").value == "True") 
			{
				window.location = $("e4xDomesticUrl").value;
			} 
			else if (reloadFlag && reloadFlag == true)
			{
		        window.location.reload();
			}
		} 
		else
		{
	        window.location.reload();
		}
	},
	setCCCookie: function(ddlCountry,ddlCurrency) {
        var oCountry = $(ddlCountry);
        var countryCode = oCountry.options[oCountry.selectedIndex].value;

        var oCurrency = $(ddlCurrency);
        var currencyCode = oCurrency.options[oCurrency.selectedIndex].value;
        
        if(countryCode != 0 && currencyCode!=0)
        {
            //set country and currency cookies
            var cookies = new CookieManager();
            cookies.setCookie("Country",countryCode,30,siteDomain);
            cookies.setCookie("Currency",currencyCode,30,siteDomain);

            //close modal dialog
            E4XClient.Hide('E4x');

            //refresh underlying page
		    E4XClient.reloadPage(true); 
		}
		else
		{
		    if(countryCode == 0 && currencyCode==0)
		    {
		        $('ErrorMsgCountry').style.display='';
		        $('ErrorMsgCurrency').style.display='';
		    }
		    else if (countryCode == 0)
		    {
		        $('ErrorMsgCountry').style.display='';
		        $('ErrorMsgCurrency').style.display='none';
		    }
		    else if (currencyCode==0)
		    {
		        $('ErrorMsgCurrency').style.display='';
		        $('ErrorMsgCountry').style.display='none';
		    }
    	}
    },
    USCustomer: function() {
        //set country and currency cookies to US
        var cookies = new CookieManager();
        cookies.setCookie("Country","US",30,siteDomain);
        cookies.setCookie("Currency","USD",30,siteDomain);

        //close modal dialog
        E4XClient.Hide('E4x');
        
        //refresh underlying page
		E4XClient.reloadPage(true); 
    },
    CloseWindow: function() {
        var cookies = new CookieManager();
        var userCountry = cookies.getValueIgnoreCase('Country');
        var userCurrency = cookies.getValueIgnoreCase('Currency');
	        	
	    //if no cookies present, set them to US - USD
        if((typeof(userCurrency)== "undefined")||(typeof(userCurrency)== "undefined"))
        {
            cookies.setCookie("Country","US",30,siteDomain);
            cookies.setCookie("Currency","USD",30,siteDomain);
        }
        E4XClient.Hide('E4x');
    },   
        
    Hide: function(domid)
    {
    $(domid).hide();   
    },
    
    selectDefaultCurrency: function(ddlcountry,ddlcurrency) {
     var oCountry = $(ddlcountry);
     var oCurrency = $(ddlcurrency);

     var defaultCurrency = oCountry.options[oCountry.selectedIndex].getAttribute('default');
        for(var i=0;i<oCurrency.options.length;i++)
        {
        if(oCurrency.options[i].value == defaultCurrency)
        oCurrency.options[i].selected="1";
        }
    },
    toggleCheckout: function(){
       var cookieManager = new CookieManager();		
	   var userCountry = cookieManager.getValueIgnoreCase('Country') || "US";
		
		if(userCountry!="US")
		{
		$('lnkInternational').style.display = 'none';
		$('lnkDomestic').style.display = '';
		}
		else
		{
		$('lnkInternational').style.display = '';
		$('lnkDomestic').style.display = 'none';
		}
   
    }
}

Event.observe(window, 'load', E4XClient.displayPrices);
Event.observe(window, 'load', E4XClient.displayFreeShipping);
Event.observe(window, 'load', E4XClient.fixOnSiteSearch);
Event.observe(window, 'load', E4XClient.hideInfo);
