/*
 * common.js - Common javascript functions for the Liberty storefront.
 *
 */

/**
 * Provides a really clean and easy way to declare new namespaces.
 * 
 * @param string separator = null
 */
String.prototype.namespace = function(separator) {
  this.split(separator || '.').inject(window, function(parent, child) {
    return parent[child] = parent[child] || {};
  });
};

// declare common namespaces
['Common', 'Cookies', 'Factories', 'Messages', 'URIs'].each (function(x) {
  ('Liberty.'+x).namespace();
});

// quick function to determine ie version (if any), borrowed largely from jQuery
(function() {
  var userAgent = navigator.userAgent.toLowerCase();
  Liberty.Browser = {
    ie: /msie/.test(userAgent) && !/opera/.test(userAgent),
    mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent),
    opera: /opera/.test(userAgent),
    safari: /webkit/.test(userAgent),
    version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1]
  };
})();

/**
 * Returns true if object is an Array.
 * 
 * @param Object object 
 */
Liberty.Common.isArray = function(object) {   
  return object
         && !(object.propertyIsEnumerable('length'))
         && typeof(object) === 'object'
         && typeof(object.length) === 'number';
}

Liberty.Common.isHidden = function(object) {
  return (object.style.display == 'none');
};

Liberty.Common.hide = function(object) {
  object.style.display = 'none';
};

Liberty.Common.show = function(object) {
  object.style.display = '';
};

Liberty.Common.max = function(a, b) {
  return (a > b ? a : b);
};

Liberty.Common.min = function(a, b) {
  return (a < b ? a : b);
};

/**
 * Changes the first letter of each word in string to upper case.
 * 
 *   http://kevin.vanzonneveld.net
 *   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
 *   improved by: Waldo Malqui Silva, Onno Marsman
 * 
 * @param string words
 * @return string
 */
Liberty.Common.ucWords = function(words) {
  return words.replace(/^(.)|\s(.)/g, function($1) { return $1.toUpperCase(); });
};

/**
 * Encapsulates cookie functionality.
 * 
 * @param string name
 */
Liberty.Cookie = function(name) {
  this.name = name;
  
  //TODO refactor getCookie()
  this.get = function() {
    return getCookie(this.name);
  };
  
  //TODO refactor createCookie()
  this.set = function(value, days) {
    createCookie(this.name, value, days);
  };

  this.erase = function() {
    this.set("", -1);
  }
}

/**
 * Factory for creating new Liberty.Cookie objects, will set an optional value.
 * 
 * @param string name
 * @param string value = null
 * @return object
 */
Liberty.Factories.Cookie = function(name, value) {
  if (value != null) {
    var cookie = new Liberty.Cookie(name);
    cookie.set(value);
    return cookie;
  }
  return new Liberty.Cookie(name);
}

/* Observes and assigns the primary nav selected state */
Event.observe(window,
  'load',
  function(){
     var selNav = $$('img.nav');
     for(i=0; i<selNav.length; i++){
        if(selNav[i].hasClassName('nav selected')){
            $(selNav[i].id).src = "/img/img_nav_" + selNav[i].id + "_o.gif";
        }
     }
     fixIECache();
     }
);





var loaded = false;
var loadingBoxId = "loading_box";

function startLoading() {
  loaded = false;
  showLoadingImage();
}

function stopLoading() {
  if ($(loadingBoxId)) {	
	  Element.hide(loadingBoxId);
	  loaded = true;
  }	  
}

function showLoadingImage() {
  var el = $(loadingBoxId);
  if (el && !loaded) {
    el.show();
   el.innerHTML = '<img src="/img/loading.gif" alt="loading">';

  }
}

/**
 * Returns a display formatted price for a range of
 * prices, or just one.
 */
function getDisplayPrice(min, max) {
    if (min == null) min = 0; //ensures that this function works in the same manner as our PHP get_display_price()
    if(null == max || min == max) {
        if(min < 0) {
            min = -min;
            return "-$" + (min/100).toFixed(2);
        } else {
            return "$" + (min/100).toFixed(2);
        }
    } else {
        return "$" + (min/100).toFixed(2) + " - $" + (max/100).toFixed(2);
    }
};


/**
 * Returns a display credits with comma
 */

function getDisplayCredits(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return "$" + x1 + x2;
}


/**
 * Returns a display formatted price for shipping
 */
function getShippingDisplayPrice(min, max) {
	if((min == 0 || null == min) && (null == max || min == max))
		return "<span class='noCost'>FREE</span>";
    else
		return getDisplayPrice(min, max);
};

// Overlay function - used to disable a screen after an event is fired
function screenDisableOverlay(overlayText) {
    Modalbox.show('<img class=\'f_left\' src=\'/img/spinner.gif\' alt=\'Loading\' /><p class=\'screenDisableOverlayText\'>' + overlayText + '</p>',{
    title: this.title,
    overlayDuration: 0,
    slideDownDuration: 0,
    overlayClose: false,
    transitions: false,
    onShow: function() { $('MB_window').style.top = '15%'; $('MB_frame').style.border = '4px solid #ECECE6';}
    });
}

function URLEncode(clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
        output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}


function confirmAction(url,title) {
  var cleanURL = URLEncode(url);

  Modalbox.show('/common/confirmAction?url=' + cleanURL, {
    title: title,
    width: 300,
    overlayClose: false
  });
}

function closeAndUpdate(container,type,id) {
    Modalbox.hide();
    switch(type) {
        case "address":
            new Ajax.Updater(container, '/account/fetchAddress?txtAddressId=' + id + '&container=' + container, {onComplete:function(){updateAccountInfo(container);showUpdated(container);},asynchronous:true,evalScripts:true});
            break;
        case "payment":
            new Ajax.Updater(container, '/account/fetchPayment?txtPaymentId=' + id + '&container=' + container, {onComplete:function(){updateAccountInfo(container);showUpdated(container);},asynchronous:true,evalScripts:true});
            break;
        default:
            break;
    }
}

function updateAccountInfo(container) {
    if($('preferred-billing') && $('preferred-shipping') && $('preferred-payment'))  {
        var preferredBilling = $('preferred-billing');
        var preferredShipping = $('preferred-shipping');
        var preferredPayment = $('preferred-payment');

        // Multiple containers can have the same className, don't change to
        // else if!
        if(container == preferredBilling.className) {
            preferredBilling.innerHTML = $(container).innerHTML;
            showUpdated('preferred-billing');
        }
        if(container == preferredShipping.className) {
            preferredShipping.innerHTML = $(container).innerHTML;
            showUpdated('preferred-shipping');
        }
        if(container == preferredPayment.className) {
            preferredPayment.innerHTML = $(container).innerHTML;
            showUpdated('preferred-payment');
        }
    }
}

function cleanHighBytes(txtControl) {
	v = txtControl.value;
	replaced = false;
	for (var i = 0; i < v.length; i++) {
		if (v.charCodeAt(i) > 127 ) {
			v = v.substring(0,i) + v.substring(i+1);
			replaced = true;
		}
    }
    if ( replaced ) { 
		txtControl.value = v;
	}
}


function showUpdated(container) {
    var div = $(container);
    var img = "<div id='updated-" + container + "' class='updated'>Updated</div>";
    div.insert(img);
    Effect.Fade('updated-' + container, {duration: 2, delay: 4});
}

function fixIECache() {
    /*Use Object Detection to detect IE6*/
    var m = document.uniqueID /*IE*/ && document.compatMode /*>=IE6*/ && !window.XMLHttpRequest /*<=IE6*/ && document.execCommand;
    try{
        if(!!m){
            m("BackgroundImageCache", false, true) /* = IE6 only */
        }
    }
    catch(oh){};
};

Ajax.Responders.register({
  onCreate : startLoading,
  onComplete : stopLoading
});




/* Smooth scrolling
   Changes links that link to other parts of this page to scroll
   smoothly to those links rather than jump to them directly, which
   can be a little disorienting.

   sil, http://www.kryogenix.org/

   v1.0 2003-11-11
   v1.1 2005-06-16 wrap it up in an object
*/

var ss = {
  fixAllLinks: function() {
    // Get a list of all links in the page
    var allLinks = document.getElementsByTagName('a');
    // Walk through the list
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if ((lnk.href && lnk.href.indexOf('#') != -1) &&
          ( (lnk.pathname == location.pathname) ||
        ('/'+lnk.pathname == location.pathname) ) &&
          (lnk.search == location.search)) {
        // If the link is internal to the page (begins in #)
        // then attach the smoothScroll function as an onclick
        // event handler
        ss.addEvent(lnk,'click',ss.smoothScroll);
      }
    }
  },

  smoothScroll: function(e) {
    // This is an event handler; get the clicked on element,
    // in a cross-browser fashion
    if (window.event) {
      target = window.event.srcElement;
    } else if (e) {
      target = e.target;
    } else return;

    // Make sure that the target is an element, not a text node
    // within an element
    if (target.nodeName.toLowerCase() != 'a') {
      target = target.parentNode;
    }

    // Paranoia; check this is an A tag
    if (target.nodeName.toLowerCase() != 'a') return;

    // Find the <a name> tag corresponding to this href
    // First strip off the hash (first character)
    anchor = target.hash.substr(1);
    // Now loop all A tags until we find one with that name
    var allLinks = document.getElementsByTagName('a');
    var destinationLink = null;
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if (lnk.name && (lnk.name == anchor)) {
        destinationLink = lnk;
        break;
      }
    }

    // If we didn't find a destination, give up and let the browser do
    // its thing
    if (!destinationLink) return true;

    // Find the destination's position
    var destx = destinationLink.offsetLeft;
    var desty = destinationLink.offsetTop;
    var thisNode = destinationLink;
    while (thisNode.offsetParent &&
          (thisNode.offsetParent != document.body)) {
      thisNode = thisNode.offsetParent;
      destx += thisNode.offsetLeft;
      desty += thisNode.offsetTop;
    }

    // Stop any current scrolling
    clearInterval(ss.INTERVAL);

    cypos = ss.getCurrentYPos();

    ss_stepsize = parseInt((desty-cypos)/ss.STEPS);
    ss.INTERVAL =
setInterval('ss.scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',10);

    // And stop the actual click happening
    if (window.event) {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
    if (e && e.preventDefault && e.stopPropagation) {
      e.preventDefault();
      e.stopPropagation();
    }
  },

  scrollWindow: function(scramount,dest,anchor) {
    wascypos = ss.getCurrentYPos();
    isAbove = (wascypos < dest);
    window.scrollTo(0,wascypos + scramount);
    iscypos = ss.getCurrentYPos();
    isAboveNow = (iscypos < dest);
    if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
      // if we've just scrolled past the destination, or
      // we haven't moved from the last scroll (i.e., we're at the
      // bottom of the page) then scroll exactly to the link
      window.scrollTo(0,dest);
            if(anchor !="top") DoFade(StartFadeAt,anchor)
      // cancel the repeating timer
      clearInterval(ss.INTERVAL);
      // and jump to the link directly so the URL's right
      location.hash = anchor;
    }
  },

  getCurrentYPos: function() {
    if (document.body && document.body.scrollTop)
      return document.body.scrollTop;
    if (document.documentElement && document.documentElement.scrollTop)
      return document.documentElement.scrollTop;
    if (window.pageYOffset)
      return window.pageYOffset;
    return 0;
  },

  addEvent: function(elm, evType, fn, useCapture) {
    // addEvent and removeEvent
    // cross-browser event handling for IE5+,  NS6 and Mozilla
    // By Scott Andrew
    if (elm.addEventListener){
      elm.addEventListener(evType, fn, useCapture);
      return true;
    } else if (elm.attachEvent){
      var r = elm.attachEvent("on"+evType, fn);
      return r;
    } else {
      alert("Handler could not be removed");
    }
  }
}

/* cart-related JavaScript; needs to be "common" due to modal cart in masthead */
var cartJs = {
    shippingZip: null,

    shippingChangeHandler: function() {
        $('shippingTemplateContainer').show();
        $('shippingContainer').hide();
        loadingBoxId = 'loading_box';
        // $('shippingContainer').innerHTML = $('shippingTemplateContainer').innerHTML;
        var tempArr = document.getElementsByName('shippingZip'); //need to get Elements by name since template has same control
        for (var i = 0; i < tempArr.length; i++) {
            tempArr[i].value = this.shippingZip;
        }
        $('shippingSelector').show();
    },

    findShippingMethodsCallback: function(shippingMethods, shippingZip) {
        //no need to do anything; callback for debug only
    },

    shippingMethodClickHandler: function(control) {
        if (control.form.onsubmit()) {
            control.form.submit();
        }
    },

    shippingMethodChangeHandler: function(control,zip, firstHide) {
		
		if($('selectedShippingMethod')) {
			$('selectedShippingMethod').disable();
        	$('shippingMethodsLoadingIndicator').show();
        	
		}
    
    if (firstHide == undefined){
      firstHide = false;
    }
               
        new Ajax.Updater('response',
                         '/cart/updateTaxAndShipping?shippingZip=' + zip + '&shippingMethod=' + control + '&disableFirstHide=' + firstHide,
                         {onComplete: function() {
                             if ($('shippingMethodsLoadingIndicator')) $('shippingMethodsLoadingIndicator').hide();
                             if ($('selectedShippingMethod')) $('selectedShippingMethod').enable();
                          },
                          asynchronous: true,
                          evalScripts: true});
    },

    rebuildShippingMethods: function(zip, selectedShippingMethod) {
		
		if($('selectedShippingMethod')) {
        	$('selectedShippingMethod').disable();
        	$('shippingMethodsLoadingIndicator').show();
		}
        new Ajax.Updater('shippingMethodDropDown',
                         '/checkout/updateShipping?shippingZipCode=' + zip + "&selectedShippingMethod=" + selectedShippingMethod,
                         {onComplete: function(){
        					if ( $('shippingMethodsLoadingIndicator') ) {
        						$('shippingMethodsLoadingIndicator').hide();
        					}
        					if ( $('selectedShippingMethod') ) {
                             $('selectedShippingMethod').enable();
        					}
                          },
                          asynchronous: true,
                          evalScripts: true});
    },

    updateTaxAndShippingCallback: function(cart, disableFirstHide) {
		// Hide any previous shipping messages
		try {
		  if(!disableFirstHide) {
        $('flatRateNotChosenMessage').hide();
        $('flatRateExpiredError').hide();
        $('shippingMessagesRow').hide();
      }
      else {
        disableFirstHide=false;
      }
		}
		// Modal throws errors because it can't find disableFirstHide
		// This just makes sure this doesn't hurt things.
		catch(err){
		  var disableFirstHide = false;
		}
		
	  $('orderSubtotalContainer').innerHTML = getDisplayPrice(cart.orderSubtotal);
	  $('taxContainer').innerHTML = getDisplayPrice(cart.tax);
	  new Effect.Highlight('taxContainer', {duration: 4});
	  $('shippingCostContainer').innerHTML = getShippingDisplayPrice(cart.totalShippingRate);
	  new Effect.Highlight('shippingCostContainer', {duration: 4});
    
    // If a user is flate rate eligible they can still get a shipping code of "1034"
    // which is standard. It means that even though the user is eligible one or many
    // products in the cart can't be consolidated. In this case we don't want to message
    // the user.
    if(cart.freeShipUpgradeEligible
          && cart.shippingMethod!="1034"
          && cart.baseShippingRate!=0) {
       $('flatRateNotChosenMessage').show();
       new Effect.Appear('shippingMessagesRow', {duration: 2, delay: 0});
     }
     else {
       // If disableFirstHide isn't selected we need to hide error message.
       $('flatRateNotChosenMessage').hide();
     }

        var hasAddlShippingCost = false;
        if (parseFloat(cart.addlShippingRate) > 0) {
            hasAddlShippingCost = true;
            $('addlShippingCostRow').show();
            $('addlShippingCostContainer').innerHTML = getDisplayPrice(cart.addlShippingRate);
        }
        else {
            $('addlShippingCostRow').hide();
            $('addlShippingCostContainer').innerHTML = 'N/A'; //div is hidden, but set to 'N/A' for completeness
        }

        //additional shipping note adds height to page; resize modal if in modal mode
        if ($('MB_window')) {
            Modalbox.resizeToContent();
        }

        $('creditsAppliedContainer').innerHTML = getDisplayPrice(cart.creditsApplied);
        $('orderTotalContainer').innerHTML = getDisplayPrice(cart.orderTotal);
        new Effect.Highlight('orderTotalContainer', {duration: 4});

        if($('shippingNameContainer')) {
            $('shippingNameContainer').innerHTML = cart.shippingName;
        }

        $('shippingAsteriskContainer').innerHTML = (hasAddlShippingCost ? '*' : '');

        if($('checkoutCart')) {
            $('estimatedArrivalValue').update(cart.shippingEtaFormatted);
            new Effect.Highlight('estimatedArrivalValue', {duration: 4});
            
            
            // Update individual shipment ETAs
            for(var shipmentNode in cart.shipments) {
                if($('shipmentEta_'+shipmentNode)) {
                    $('shipmentEta_'+shipmentNode).update(cart.shipments[shipmentNode].shippingEta);
                    new Effect.Highlight('shipmentEta_'+shipmentNode, {duration: 4});                    
                }               
            } 
            
            if ($('selectedShippingMethod').value == 1029) {             
                $('nextDayMsg').style.display = 'block';
                new Effect.Highlight('nextDayMsg', {duration: 4});            
            }
            else {            
             	$('nextDayMsg').style.display = 'none';
            }
        }
						
		if ( $('shippingLabel') != null ) {
			$('shippingLabel').style.display = ((cart.shippingMethod=="1046")?'none':'inline');
		}
		if ( $('shipUpgradeMessage') != null ) {
			$('shipUpgradeMessage').style.display = ((cart.shippingMethod=="1046")?'none':'block');
		}
		
		
 
        this.shippingZip = cart.taxZipCode;

        if($('shippingSelector')) {
            $('shippingSelector').hide();
        }
                
    }
    
}
/*Cart...Hide special messages if user clicks on change shipping */
function chkMsgs(){
	if($('flatShippingRateAlert')!=null) {
		$('flatShippingRateAlert').hide();
	}
}



// Extensions of Modalbox added by Optaros January 17, 2008
// Used to call different positioning and style of the MB

// Overlay function - used to disable a screen after an event is fired
function screenDisableOverlay(overlayText) {
    Modalbox.show('<img class=\'f_left\' src=\'/img/spinner.gif\' alt=\'Loading\' /><p class=\'screenDisableOverlayText\'>' + overlayText + '</p>',{
    title: this.title,
    overlayDuration: 0,
    slideDownDuration: 0,
    overlayClose: false,
    transitions: false,
    onShow: function() {setScreenDisableStyle()}
    });
}

function setScreenDisableStyle(){
    $('MB_window').addClassName('setDialogModalTop');
    $('MB_frame').addClassName('setDialogModalStyle');
}

function setTeaserDisableStyle(){
    // set the top and add the class
    //$('MB_window').style.top = '110px';
    $('MB_frame').addClassName('teaserReelHeader');
    $('MB_content').addClassName('teaserReelContent');

}

function closeTeaserReel(){
    Modalbox.hide();
}

function setParentInviteTrigger(){
    // set the top and add the class
    $('MB_header').style.display = 'block';
    $('MB_frame').removeClassName('teaserReelHeader');
    $('MB_content').removeClassName('teaserReelContent');
}





// limiter for the invitation message textarea

var count = "210";   //Example: var count = "175";
function limiter(){
var tex = $('message').value;
var len = tex.length;
if(len > count){
        tex = tex.substring(0,count);
        $('message').value=tex;
        return false;
}

var newCount = count-len;
    if(newCount > 0) {
        $('limit').innerHTML = "(" + newCount + " characters left)";
        $('limit').style.color = '#989B97';
    } else {
        $('limit').innerHTML = 'maximum reached!';
        $('limit').style.color = '#A90061';
    }
}

/************************************************************/

/**
 *
 */
function chkAllEmail() {
    $$('.chkEmail').each(function(obj) {obj.checked=true});
}

/**
 *
 */
function chkAllSMS(defMobilePhone) {
    $$('.chkSMS').each(function(obj) {obj.checked=true});
    showHideReqMobilePhoneContainer(defMobilePhone);
}

/**
 *
 */
function showHideReqMobilePhoneContainer(defMobilePhone) {
    var hasSms = false;
    $$('.chkSMS').each(function(obj) {if (obj.checked) hasSms=true});
    if (hasSms) {
        //reset to stored value
        $('txtMobilePhone').setValue(defMobilePhone);
        $('reqMobilePhoneContainer').show();
    }
    else {
        //clear before hiding so value is not submitted
        $('txtMobilePhone').clear();
        $('reqMobilePhoneContainer').hide();
    }
}

/************************************************************/



function getCartItemSwatch(host, styleNum, attrImage, imgSuffix) {
	var path = 'images/product/' + styleNum.substr(0, 6) + '/';
	var colorNameSuffix = '';
	if (attrImage != null) {
	    var uScoreIndex = attrImage.lastIndexOf('_');
	    var dotIndex = attrImage.lastIndexOf('.');
	    var colorNameSuffix = attrImage.substr(uScoreIndex, dotIndex - uScoreIndex);
	}
	return host + path + styleNum + imgSuffix + colorNameSuffix + '.jpg';
}

/**
 * Validates via AJAX that state and zip combo is valid.
 */
function validateStateZipCombo(formObj, stateObjName, zipObjName) {
    var state = $F(formObj.elements[stateObjName]);
    var zip = $F(formObj.elements[zipObjName]);

    //only validate if state and zip filled in
    if (state.length == 0 || zip.length == 0) {
        return false;
    }

    var parameters = {
            state: state,
            zip: zip
        };

    var isValid = false;

    new Ajax.Request('/account/validateStateZipCombo', {
        method: 'get',
        asynchronous: false, //block until this AJAX call returns
        parameters: parameters,
        onComplete: function(transport) {
            if (!transport.request.success()) {
                alert('An error occurred. Please reload this page and try again.'); //TODO: enhance
                return;
            }

            (transport.responseText).evalScripts(); //handle session timeouts
            var response = eval( '(' + transport.responseText + ')' );
            if (typeof response == 'boolean') {
                isValid = response;
            }

            if (!isValid) {
                alert("That state and zip code don't match. Please check the state and zip code and try it again.");
            }
        }
    });

    return isValid;
}

/**
 * Updates my credits in masthead.
 */
function updateMastheadMyCredits(newCredits) {
  mastHeadInfoCookie = new Liberty.Cookie('mastHeadInfo');
  mastHeadInfoStr = mastHeadInfoCookie.get();
	if ( mastHeadInfoStr != null ) {
		try {
			var mastHeadInfoRoot = mastHeadInfoStr.evalJSON();
			var mastHeadInfo = mastHeadInfoRoot.mhi[0];
			if ( mastHeadInfo.cb != newCredits ) {
				mastHeadInfo.cb = newCredits;
				storeMastheadCookie(Object.toJSON(mastHeadInfoRoot));
				return true;
			}
		} catch (e) {	
			deleteCookie('mastHeadInfo');
		}
	}
	getMastheadInfo();
}

/**
 * Updates cart quantity in masthead.
 */
function updateMastheadCartQty(newQty) {
    var mastHeadInfoStr = getCookie('mastHeadInfo');
	if ( mastHeadInfoStr != null ) {
		try {
			var mastHeadInfoRoot = mastHeadInfoStr.evalJSON();
			var mastHeadInfo = mastHeadInfoRoot.mhi[0];
			if ( mastHeadInfo.cc != newQty ) {
				mastHeadInfo.cc = newQty;
				storeMastheadCookie(Object.toJSON(mastHeadInfoRoot));
				return true;
			}
		} catch (e) {	
			deleteCookie('mastHeadInfo');
		}
	}
	getMastheadInfo();
}


/**
 * Toggles between the WOM and get on the list forms
 */


function showDivInvitedBy() {
	$('divReferredBy').style.display = 'block';
	$('divReferredBy').style.width = 57 + "%";
	if ($('MB_window')) Modalbox.resizeToContent();
}

function showDivBecomeMember() {
	$('divBecomeMember').style.display = 'block';
	$('divBecomeMember').removeClassName('f_right');
	$('divBecomeMember').style.width = 57 + "%";
	if ($('MB_window')) Modalbox.resizeToContent();
}

function welcomeModal() {	
	if ( getCookie('newMember') == 'true' ){
		Modalbox.show('/common/newMember', {title:'&nbsp;', width:950, slideDownDuration:0, onShow: function() { $('MB_window').style.top = '15%'}});
		eraseCookie('newMember');
	}
}



function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  var domain = ( cookieDomain!=null && cookieDomain.length>0 )?('; domain=' + cookieDomain):'';
  document.cookie = name+"="+escape(value)+expires+"; path=/" + domain;
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
	    if (begin == -1) {
	        begin = dc.indexOf(prefix);
	        if (begin != 0) return null;
	    } else {
	        begin += 2;
	    }
	    var end = document.cookie.indexOf(";", begin);
	    if (end == -1) {
	        end = dc.length;
	    }
	    return unescape(dc.substring(begin + prefix.length, end));
}

function readCookie(name) {
	
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}

function ajaxFailure( transport ) {
	// alert( "Unable to get userInfo [" + transport.status + "] : " + transport.responseXML.documentElement.childNodes[0].textContent);
}

function getMastheadAjax() {
	var uid = getCookie('uid');
	if ( uid == null ) {
		window.location.href = '/access/logout';
		return false;
	}
	new Ajax.Request('/access/mastheadInfo/userId/' + uid, 
	{
		method:'get',
		requestHeaders: {Accept: 'application/json'},
		onSuccess: function(transport) {
			storeMastheadCookie(transport.responseText);
		 },
		  //TODO: Remove this before we get to QA.
      	onFailure: ajaxFailure
	} );
}

function storeMastheadCookie(response) {
	if ( response != null ){
		createCookie('mastHeadInfo',response);
		getMastheadInfo();
	}
}

var sifrSet = false;
var serverTimeOffset = null;
function getMastheadInfo() {
	var isMobile = isMobileVersion();
	var mastHeadInfoStr = getCookie('mastHeadInfo');
	var mastheadInfo = null;
	
	if ( mastHeadInfoStr != null ) {
		mastheadInfo = mastHeadInfoStr.evalJSON().mhi[0];
	}	
	if ( mastheadInfo == null || mastheadInfo.cc == null ) {
		getMastheadAjax();
	} else {		
		getServerTimeOffset( mastheadInfo );
		var fmtCreditBalance = getDisplayCredits((mastheadInfo.cb/100).toFixed(2));
		var cartCount = getCartItemQty(mastheadInfo);
		if ( $('bag') && cartCount == 0 ) {
			$('bag').onclick = function() {return false;};
		} else {
			if ($('bag') && $('bag').tagName == 'A') {
				$('bag').onclick = function() {
					Modalbox.show(this.href, {title: this.title, width: 950});
					return false;
				};
			}      
		}

		if ( $('mh_sifr')!=null && !sifrSet ) {
			var greeting = "Ooh la la, " + mastheadInfo.fn + "!";
			$('mh_sifr').update(greeting).innerHTML;
			targetedHelveticaLight.replaceElement($('mh_sifr'));
			sifrSet = true;
		}

		//Set the values to the appropriate divs.
		$('myCredits').update(fmtCreditBalance).innerHTML;
		$('mh_preview_indicator').update((mastheadInfo.ss == mastheadInfo.uid)?'*':'').innerHTML;
		$('cartCount').update( cartCount + (( cartCount == 1 )?' item':' items') ).innerHTML;
		if($('bag')) {
		    if (cartCount==0){
		        $('bag').addClassName("zero");
		    }else{
		        $('bag').removeClassName("zero");
		    }
	    }
		cartUri = ( cartUri == null )?'/cart':cartUri;
		if ( cartCount == 0 || $('checkoutButton').readAttribute("rel") == "cart") {
			if (!isMobile) {
				$('checkoutButton').update('<h5 class="chkoutInActive">Checkout</h5>').innerHTML;
			}else {
				$('checkoutButton').update('<button id="chkoutBtn" class="cancel">CHECKOUT</button>').innerHTML;
			}
		} else {
			if (!isMobile) {
				$('checkoutButton').update('<a href="' + cartUri + '"><h5 class="chkoutActive">Checkout</h5></a>').innerHTML;
			}else {
				$('checkoutButton').update('<a href="' + cartUri + '" id="cartLink"><button id="chkoutBtn" class="accent">CHECKOUT</button></a>').innerHTML;
			}	

		}		
	}	
}

function getServerTimeOffset( mastHeadInfo ) {
	var clientDate = new Date();
	var stOffset = getCookie('stos');
	if ( stOffset != parseInt(stOffset) ) {
		var rllTS = mastHeadInfo.ts;
		var clientTS = clientDate.getTime();
		var rllDate = new Date();
		rllDate.setTime( rllTS );
		var stOffset = rllDate - clientDate;
		createCookie('stos', stOffset );
	}
	serverTimeOffset = ( parseInt(stOffset) == stOffset )?parseInt(stOffset):0;
}

function getCartItemQty(mastHeadInfo){
	if (!mastHeadInfo || mastHeadInfo == null) {
		var mastHeadInfoStr = getCookie('mastHeadInfo');
		if ( mastHeadInfoStr == null ) {
			getMastheadAjax();
			mastHeadInfoStr = getCookie('mastHeadInfo');
		} 	
		mastHeadInfo = mastHeadInfoStr.evalJSON().mhi[0];
	}
	var cartCount = parseFloat(mastHeadInfo.cc);
	cartCount = isNaN(cartCount)?0:cartCount;
	return cartCount;
}




// HIDE SHOW TOGGLE
// Used on the facebook page to hide and show the already invited friends.
function showHideToggle(id){
	if($(id).style.display == 'block'){
		$(id).style.display = 'none';
	}
	else{
		$(id).style.display = 'block';
	}
}
//Simple link function used on the access gate.  
//TODO: Make this more unobtrusive
function goHome() { 
	   window.location = "/";
	} 
	
/*Show Hide Nav Menus*/
// The reason for the delays is that ie spams us with events when we 
// move the mouse around in the menus.  If there are no delays on closing
// then the menus are unusable on ie.  The delays on opening are to compensate
// for the close delays and prevent mutliple menus from being displayed at
// the same time.
function showNavMenu(id){
    el = $(id);
    if (el.closeDelayTimer) window.clearTimeout(el.closeDelayTimer);
    if (el.getStyle('display') == "none" && !el.openDelayTimer) {
      el.openDelayTimer = window.setTimeout("$('"+id+"').show()", 100);
    }
}
function hideNavMenu(id){
    el = $(id);
    if (el.closeDelayTimer) window.clearTimeout(el.closeDelayTimer);
    if (el.openDelayTimer) window.clearTimeout(el.openDelayTimer);
    el.openDelayTimer = null;
    el.closeDelayTimer = window.setTimeout("$('"+id+"').hide()", 100);
}

/**
 * Check if there is a field indicating mobile application.
 * Originally in _accountHeaderMobile.php
 * @return
 */
function isMobileVersion(){
	if ($('isMobile') && $('isMobile').value =='true') {
		return true;
	} else {
		return false;
	}	
}

function initStrikePriceTips() {
  var striked = $('striked').innerHTML;
  $$('span.productStrikePrice').each(function(element) {
    new Tip(element,
            striked,
            { title : 'What does the comparative price mean?',
              className: 'pinktip',
              showOn: 'click',
              viewport: true,
              offset: {x:-170, y:-35},
              hideOn: {element: '.close', event: 'click'},
              closeButton: true });
  });
}

function notify(message) {
  var el = new Element('div', {'class': 'success notice'});
  el.innerHTML = message;
  $$('.pageContainer').invoke('insert', {top: el});
}

/**
 * The following is an algorithm to determine if credit card numbers are 
 * valid.  Basically, we add values to validate according to the mod10 rules,
 * and if validate is a factor of 10, then the credit card is valid.  The
 * rules are as follows:
 *
 * Each digit in the credit card number has an index.  Starting from the back, 
 * digits with an odd numbered index are doubled and each digit in the 
 * resulting value is added to validate.  digits with even numbered indexes 
 * are added to validate.  When the process is complete, validate should be a 
 * factor of 10 if the credit card number is valid.
 */
Liberty.Common.mod10check = function(cc) {
  var validate = 0;
  cc.toArray().reverse().each(function(digit, idx) {
    digit = Number(digit);
    // if odd then double the value and add each resulting digit to validate
    if (idx % 2 == 1) {
      String(digit * 2).toArray().map(Number).each(function(n) {
        validate += n; 
      });
    // else just add the digit to validate
    } else {
      validate += digit;
    }
  });
  // if validate is a factor of 10, then the cc number is valid
  return (validate % 10 == 0);
};

document.observe('dom:loaded', function() {
  var notification = getCookie('Liberty.Product.notification');
  if (notification) {
    notify(notification);
    eraseCookie('Liberty.Product.notification');
  }
});

// vim: ts=2 sw=2


