// RWilliams
// Contains simple utilities used by other classes and functions
//----------------------------------------------------------
var FootSmartGlobal = ({
    OrderId:0, 
    OrderNumber:'0',
    CustomerId: '',
    CustomerEmail: '',
    ProductSku:'0',
    IsCanadian: false,
    OrderAmount: 0,
    ShippingAmount: 0,
    SalesTaxAmount: 0,
    Discount: 0,
    PostalCode: '',
    CountryCode: 'US'
});

var FootSmartUtilities = Class.create({
    ready: true,
    initialize: function() { },
	appendScriptTag: function(elementTagName, url, text){
		// RWilliams - 1/27/2010 - add a script tag to the given element that is specified by the tag name above
		// NOTE: you can only use this script for one thing at a time, either url or text,
		// don't try using both - it won't work!!!!
		var script = document.createElement('script');
		script.type = 'text/javascript';
		if(url != undefined) {
			script.src = url;
		}else if(text != undefined) {
			script.text = text;
		}else{
			return false;
		}
		document.getElementsByTagName(elementTagName)[0].appendChild(script);
    },
    domWrite: function(elementTagName, src) {
        /*alert(elementTagName);
        document.write = function(value){
        $(elementTagName).innerHTML += value;
        }*/
        this.appendScriptTag('body', src, null);
    },
    getPageName: function() {
        var pageName = window.location.pathname.toLowerCase();
        pageName = pageName.substring(pageName.lastIndexOf('/') + 1);
        pageName = pageName.substring(0, pageName.lastIndexOf("."));
        
        if (pageName.substr(0, 2) == 'p-')
            pageName = 'product';
            
        return pageName;
    },
    queryString: function(uri, keyName, newKeyValue) {
        //assign params
        var params = $H(uri.toQueryParams());
        var baseuri = uri.slice(0, uri.indexOf('?'));

        //set
        params.set(keyName, newKeyValue);

        //make
        return baseuri + '?' + params.toQueryString();

    },

    // Finds the x position of an object
    findPosX: function(obj) {
        var curleft = 0;
        if (obj.offsetParent) {
            while (obj.offsetParent) {
                curleft += obj.offsetLeft
                obj = obj.offsetParent;
            }
        }
        else if (obj.x)
            curleft += obj.x;
        return curleft;
    },

    // Finds the y position of an object
    findPosY: function(obj) {
        var curtop = 0;
        if (obj.offsetParent) {
            while (obj.offsetParent) {
                curtop += obj.offsetTop
                obj = obj.offsetParent;
            }
        }
        else if (obj.y)
            curtop += obj.y;
        return curtop;
    },

	// Load the Cart Item Count From Cookie
	GetCartItemCount: function() {
		var itemQuantityTotal = 0;
		var orderItems = GetCookie("Order");

		if(orderItems != null && orderItems != 'undefined' && orderItems.length >0){
			var items = orderItems.split('~');

			for(i = 1; i<items.length; i++)
			{
				var item = items[i].split('|');

				if(item.length >2)
				{
					itemQuantityTotal += parseInt(item[2]);
				}
			}
		}

		if ($('cartCountText')) {
			$('cartCountText').innerHTML = itemQuantityTotal + ' items';

			if(itemQuantityTotal == 1)
			{
				$('cartCountText').innerHTML = $('cartCountText').innerHTML.substring(0,($('cartCountText').innerHTML.length -1));
			}
		}
	},
	
	//Update the Account Sign In Link
	UpdateLoginLink: function() {
		if(document.cookie.indexOf("FootSmart_Login") >0){
			$('loginLink').innerHTML = "Sign Out"; //"<a href='Logout.aspx?account=1'>Sign Out</a>";
			$('loginLink').href = "Logout.aspx?account=1";
		}
	},

	// Load the Cart Item Count From Cookie
	UpdateNavImage: function() {
		var selectedHref = location.href;

		$$('#tTopNav a').each(function(e){
			var nav_img = $(e).childElements()[0];

			if($(e).readAttribute('href') == selectedHref)
			{
				var hrefSRC = $(nav_img).readAttribute('src');
				var updatedSRC = hrefSRC.replace('off','on');
				$(nav_img).setAttribute('src',updatedSRC);
				$(nav_img).setAttribute('onMouseOver','');
				$(nav_img).setAttribute('onMouseOut','');
			}
		});
	}
});

// RWilliams - 05/27/2009
// All UI related functions should now be placed in here and
// I'll slowly move everything else into this file.
//----------------------------------------------------------
var FootSmartUI = Class.create({
    // Initialization class if you need to init anything, 
    // think of it as a constructor
    initialize: function(){},    
    
    // Generic Function to toggle the default value for a text box
    toggleTextField: function(e){
        var defaultText = this.readAttribute('toggletext');
	    if (defaultText == null){defaultText = this.defaultValue;}	    
	    if (e.type == "blur" && this.value == ''){this.value = defaultText;}
        if (e.type == "focus" && this.value == defaultText){this.value = '';}
	    if (e.type == "keypress" && this.value == defaultText){this.value = '';}
	    if (e.type == "click" && this.value == defaultText){this.value = '';}
    },
    
    // Sets up the search textbox area and starts observing some events 
    setSearchTextBoxEvents: function() {       
	   if($$('#searchArea input.tbNavSearch')[0]) 
	   {
			$$('#searchArea input.tbNavSearch')[0].focus();
       }
       if (Prototype.Browser.IE)
       {
            $$('#searchArea .tbNavSearch')[0].observe('focusin', this.toggleTextField);
       }
       else
       {
            $$('#searchArea .tbNavSearch')[0].observe('focus', this.toggleTextField);
       }       
       $$('#searchArea .tbNavSearch')[0].observe('blur', this.toggleTextField);
       $$('#searchArea .tbNavSearch')[0].observe('keypress', this.toggleTextField);
       $$('#searchArea .tbNavSearch')[0].observe('click', this.toggleTextField);          
    },
    
    // Ensures that all submenus are visible by using the pmenuid query string param
    ensureSubmenuVisibility: function(){
        var menuId = GetCookie("pmnuid");
        if(menuId != null && menuId != 'undefined' && (typeof SwitchMenu == 'function')){
            SwitchMenu(menuId);
        }
    },
    
    // add target property to every anchor tag on page
    //  "_blank" "_parent" "_self" "_top" 
    insertParentTarget: function () {
        $$('a').each(function(link) { link.writeAttribute("target", "_parent"); } );
        if ($('searchLinkButton'))
        {
             $('searchLinkButton').writeAttribute("target", "");
        }
    }
});

// All initial load events should be loaded here
// dom:loaded - loads after HTML doc but defore images are fully loaded
//----------------------------------------------------------
document.observe("dom:loaded", function(){
    // sub menu visibility on left nav
    var fsuiw = new FootSmartUI();
    var fsu = new FootSmartUtilities();
    fsuiw.ensureSubmenuVisibility();
   
    //need to block Gomez Users, via HTTP_USER_AGENT identification, not done by CoreMetrics
    //We also do not want to load a page view tag for the blog page since page.aspx is used by the 
    //blog in an iframe.
	var GomezUser = GetCookie("GomezUser");
    if(GomezUser==null && document.URL.toLowerCase().toQueryParams().src != "blog")
    {
        if (typeof(coremetrics) != 'undefined') 
        {
            coremetrics.PageViewTag();
            coremetrics.DisplayCoremetricsFormErrorTag();
        }
    }
    else
    {
        //Only execute for a custom blank page that is meant to be used in an iframe)
        fsuiw.insertParentTarget();
    }

	if(window.ShoppingCartTracking)		//method created via Shopping Cart Product additions, in ShoppingCart.aspx					
		ShoppingCartTracking();

	if(window.ExpeditedShippingNotAvailable)
		ExpeditedShippingNotAvailable();

	SetCookie("InDomain","1",null,null);
	SourceCodeClientSideSet();
	EmailTracking();
	setSessionIds();
	fsu.GetCartItemCount();

	// from dotomiTag.ascx
	if (typeof loadDotomi == 'function')
	{
        loadDotomi();
    }
});

// window.load - fires after HTML doc and images are loaded
//----------------------------------------------------------
Event.observe(window, 'load', function(){
	var fsuiw = new FootSmartUI();	
	var fsu = new FootSmartUtilities();
	
	// Setup search box settings
	//--------------------------------------------------
	if ($('searchBar')) 
    {
		fsuiw.setSearchTextBoxEvents();
		fsu.UpdateNavImage();
    }
});
