/*
 * common.js - Common javascript functions for the Liberty storefront.
 *
 */
/* 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 = "/resource/images/img_nav_" + selNav[i].id + "_o.gif";
        }
     }
     fixIECache();
     }
);





var loaded = false;
var loadingBoxId = "loading_box";

function startLoading() {
  loaded = false;
  showLoadingImage();
}

function stopLoading() {
  Element.hide(loadingBoxId);
  loaded = true;
}

function showLoadingImage() {
  var el = $(loadingBoxId);
  if (el && !loaded) {
    el.show();
   el.innerHTML = '<img src="/resource/images/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);
    }
};

// Overlay function - used to disable a screen after an event is fired
function screenDisableOverlay(overlayText) {
    Modalbox.show('<img class=\'f_left\' src=\'/resource/images/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');

        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) {
		
		if($('selectedShippingMethod')) {
			$('selectedShippingMethod').disable();
        	$('shippingMethodsLoadingIndicator').show();
        	
		}
       
               
        new Ajax.Updater('response',
                         '/cart/updateTaxAndShipping?shippingZip=' + zip + '&shippingMethod=' + control,
                         {onComplete: function() {
                             $('shippingMethodsLoadingIndicator').hide();
                             $('selectedShippingMethod').enable();
                          },
                          asynchronous: true,
                          evalScripts: true});
    },

    rebuildShippingMethods: function(zip, selectedShippingMethod) {
		
		if($('selectedShippingMethod')) {
        	$('selectedShippingMethod').disable();
        	$('shippingMethodsLoadingIndicator').show();
		}
        new Ajax.Updater('shippingMethodsContainer',
                         '/checkout/updateShipping?shippingZipCode=' + zip + "&selectedShippingMethod=" + selectedShippingMethod,
                         {onComplete: function(){
                             $('shippingMethodsLoadingIndicator').hide();
                             $('selectedShippingMethod').enable();
                          },
                          asynchronous: true,
                          evalScripts: true});
    },

    updateTaxAndShippingCallback: function(cart) {
        $('orderSubtotalContainer').innerHTML = getDisplayPrice(cart.orderSubtotal);
        $('taxContainer').innerHTML = getDisplayPrice(cart.tax);
        new Effect.Highlight('taxContainer', {duration: 4});
        $('shippingCostContainer').innerHTML = getDisplayPrice(cart.shippingCost);
        new Effect.Highlight('shippingCostContainer', {duration: 4});

        var hasAddlShippingCost = false;
        if (parseFloat(cart.addlShippingCost) > 0) {
            hasAddlShippingCost = true;
            $('addlShippingCostRow').show();
            $('addlShippingCostContainer').innerHTML = getDisplayPrice(cart.addlShippingCost);
        }
        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';
            }
        }
		for (var itemIx = 0; itemIx < cart.cartItems.length; itemIx++) {
			if ( $('cartItemLineLevel_' + itemIx) != null ) {            	
				lineLevelDisplay = (cart.shippingMethod=="1046")?'block':'none';
				$('cartItemLineLevel_' + itemIx).style.display = lineLevelDisplay;
			}
		}
				
		if ( $('shippingLabel') != null ) {
			$('shippingLabel').style.display = ((cart.shippingMethod=="1046")?'none':'inline');
		}
		
 
        this.shippingZip = cart.taxZipCode;

        if($('shippingSelector')) {
            $('shippingSelector').hide();
        }
                
    }
    
}

function getProductNeighbors(styleNum) {
    var styleFound = false;
    var previousStyleNum = null;

    for(var i=0; i<products.length; i++) {
        if(styleFound) {
            return {nextStyleNum: products[i].styleNum,
                    previousStyleNum: previousStyleNum};
        }
        if(products[i].styleNum == styleNum) {
            styleFound = true;
        } else {
            previousStyleNum = products[i].styleNum;
        }
    }

    return {nextStyleNum: null,
            previousStyleNum: previousStyleNum};
};

// 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=\'/resource/images/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');
    Modalbox.resizeToContent();
}


function setQuickInviteTo(){
    // set the modal's "To" value equal to the input in the quick invite area
    if($('email_list')) { 
      $('email_list').value = $('txtShare').value;
      $('txtShare').value = '';
      $('txtShare').focus();
      $('txtShare').blur();
    }    
}




// 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 = '#222222';
    } else {
        $('limit').innerHTML = 'maximum reached!';
        $('limit').style.color = '#DA1473';
    }
}

/************************************************************/

/**
 *
 */
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();
    }
}

/************************************************************/

/**
 * JS version of get_cart_item_swatch(). Same parameters except that dynamic image host must be passed in.
 */
function getCartItemSwatch(host, styleNum, attrImage) {
    var path = 'images/PRODUCT/' + styleNum.substr(0, 6) + '/';
    var colorNameSuffix = '';
    if (attrImage != null) {
        //based on ipapas' logic in product details page
        var uScoreIndex = attrImage.lastIndexOf('_');
        var dotIndex = attrImage.lastIndexOf('.');
        var colorNameSuffix = attrImage.substr(uScoreIndex, dotIndex - uScoreIndex);
    }
    var fileName = styleNum + '_RLCT' + colorNameSuffix + '.jpg';

    return host + path + fileName;
}

/**
 * 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 cart quantity in masthead.
 */
function updateMastheadCartQty(newQty) {
	$('bag').innerHTML = newQty + ' 件商品';
	if(newQty > 0)
	{
		$('bagitems').style.backgroundColor = '#5e1b1b';
		$('checkoutimg').src = "/resource/images/toluxe/to_checkout_red.jpg";
	}
	else
	{
		$('bagitems').style.backgroundColor = '#6c6a6a';
		$('checkoutimg').src = "/resource/images/toluxe/to_checkout_grey.jpg";
	}
}


/**
 * 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 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 = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

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 hideAllMessage(mes)
{
	var meses = document.getElementsByClassName(mes.toString());
	if(meses != null)
	{
		for(var i = 0; i < meses.length; i ++)
		{
			meses[i].hide();
		}
	}
}

