/* cookie detection */
/* we need to use javascript instead of jsp because of squid cache */
setCookieValue('cookieDetection','saved');
setCookieIsEnable(true);
if(getCookieValue('cookieDetection') == 0){
    setCookieIsEnable(false);
}
function setCookieIsEnable(cValue){
    this.CookieIsEnable = cValue;
}
function getCookieIsEnable(){
    return this.CookieIsEnable;
}
/* cookie detection */

/* javascript detection */
function checkCookieScript() {
    setJsIsEnable();
    if(!getCookieIsEnable()){
        $('cookieDisabled').style.display = "block";
    }
    else {
        $('cookieDisabled').style.display = "none";
        $('cookieJsTopMessages').style.display = "none";
        $('cookieJsBottomMessage').style.display = "none";
    }
    // hide message for js disabled
    $('onlyScriptDisabled').style.display = "none";
    $('cookieWithoutJs').style.display = "none";
}
function setJsIsEnable() {
    this.JsIsEnable = true;
}
function getJsIsEnable() {
    return this.JsIsEnable;
}
/* javascript detection */

/* general */
function getCookieValue(cookieName) {
    var results = document.cookie.match('(^|;) ?' + cookieName + '=([^;]*)(;|$)');
    if (results) {
        return (results[2]);
    }
    else {
        return "0";
    }
}
function setCookieValue(cookieName, cookieValue, nDays){
    var today = new Date();
    var expire = new Date();
    if (nDays==null || nDays==0){
        nDays=1;
    }
    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie = cookieName+"="+cookieValue + ";expires="+expire.toGMTString();
}
function setCurrentProductId(currProdId){
    this.currProdId = currProdId;
}
function getCurrentProductId(){
    return this.currProdId;
}
function setItemString(itemStr) {
    this.itemStr = itemStr;
}
function getItemString() {
    return this.itemStr;
}
function setItemsString(itemsStr) {
    this.itemsStr = itemsStr;
}
function getItemsString() {
    return this.itemsStr;
}

/* adding style and js files dynamically */
function loadjscssfile(filename, filetype, id){
    if(filetype == "js"){ //if filename is a external JavaScript file
        var fileref = document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
        if(id != ''){
            fileref.setAttribute("id",id);
        }
        document.getElementsByTagName("head")[0].appendChild(fileref);
    }
    else if(filetype == "css"){ //if filename is an external CSS file
        var scriptElem = document.getElementsByTagName("script")[1];

        var fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
        if(id != ''){
            fileref.setAttribute("id",id);
        }
        document.getElementsByTagName("head")[0].insertBefore(fileref,scriptElem);
    }
}

var filesadded = ""; //list of files already added

function checkloadjscssfile(filename, filetype, id){
 if (filesadded.indexOf("["+filename+"]") == -1){
    loadjscssfile(filename, filetype, id);
    filesadded += "["+filename+"]"; //List of files added in the form "[filename1],[filename2],etc"
 }
 else
    alert("file already added!")
}
/* adding style and js files dynamically */

/* general */

// initiallize page js
//dom:loaded not supportted by IE8
//Event.observe(window, 'dom:loaded', initPage);
Event.observe(document, Prototype.Browser.IE ? 'novator:dom:loaded' : 'dom:loaded', initializePage);
function initializePage() {
    /* we should put here the initiallization of all js to run on load,
     for each FD its initFDName function should be responsible to check FD existance
     */

    /*Start C5HeaderTopFDT init*/
    initC5HeaderTopFDT();
    /*end productSearch init*/

    /*Start C5BillingShippingFDT init*/
    initC5BillingShippingFDT();
    /*end C5BillingShippingFDT init*/

    /*Start initC5ReviewPaymentFDT init*/
    initC5ReviewPaymentFDT();
    /*end initC5ReviewPaymentFDT init*/

    /*Start C3MainPromoFDT init*/
    initC3MainPromoFDT();
    /*end C3MainPromoFDT init*/

    /*Start C4MainPromoFDT init*/
    initC4MainPromoFDT();
    /*end C4MainPromoFDT init*/

    /*Start initC4FeaturedItemsFDT init*/
    initC4FeaturedItemsFDT();
    /*end initC4FeaturedItemsFDT init*/

    /*Start initC1MiniWishListFDT init*/
    initC1MiniWishListFDT();
    /*end initC1MiniWishListFDT init*/

    /*Start initC1MiniShoppingCartFDT init*/
    initC1MiniShoppingCartFDT();
    /*end initC1MiniShoppingCartFDT init*/

    /*Start initC5HeaderTopLinksFDT init*/
    initC5HeaderTopLinksFDT();
    /*end initC5HeaderTopLinksFDT init*/

    /*Start initC5MyAccountFDT init*/
    initC5MyAccountFDT();
    /*end initC5MyAccountFDT init*/

    /*Start C4MyPersonalProfileFDT */
    initMyPersonalProfile();
    /*end C4MyPersonalProfileFDT */

    /*Start initC4WishListFDT init*/
    initC4WishListFDT();
    /*end initC4WishListFDT init*/

    /*Start initC4MyOrderHistoryFDT init*/
    initC4MyOrderHistoryFDT();
    /*end initC4MyOrderHistoryFDT init*/

    /*Start initC1LinkListFDT init*/
    initC1LinkListFDT();
    /*end initC1LinkListFDT init*/

    /*Start recently viewed ajax call */
    initRecentlyViewedAjax();
    /*end recently viewed ajax call */

    /* attach product details events on page load */

    /*Start productDetails init*/
    initC5ProductDetailsFDTUI();
    initC5ProductDetailsFDTEvents();
    initC5ProductDetailsTabsFDT();

    /*Start productSearch init*/
    initInc_C4PaginationContainerJSP();
    /*End productDetails init */

    /*Start C1NarrowYourSearchFDT */
    initC1NarrowYourSearchFDT();
    /*End C1NarrowYourSearchFDT */

    /* START catalog request */
    initCatalogRequest();
    /* End catalog request */

    /*START wish list*/
//    initC4WishListFDT();
    /*End wish list*/

    /*Start initRecentlyViewedCookieSetup */
    initRecentlyViewedCookieSetup();
    /*ened initRecentlyViewedCookieSetup */

    /* start initMyBuysFDT */
    initMyBuysFDT();
    /* end initMyBuysFDT */
}

function setTopCategory(topCat){
    this.topCat = topCat;
}
function getTopCategory(){
    return this.topCat;
}
var startClockMybuys;
function initMyBuysFDT(){
    if($('mybuysWrapperId')){
        // set timer
        startClockMybuys = setInterval("timerMybuys()", 4000);
    }
}
function timerMybuys(){
    if($('mybuyspagezone1') || $('mybuyspagezone2')){
        $$('.mbimglink, .detailsButton, .mbnamelink, .mbpricelink, .mblistlink, .mbsalelink').each(function (ele) {
            ele.setAttribute('href',ele.getAttribute('href') + '&tc=' + getTopCategory());
        });
        $$('.mblistlink, .mbpricelink').each(function (elem) {
            elem.className = elem.className + " " + getTopCategory() + "FontColor";
        });
        clearInterval ( startClockMybuys );
    }
}

function initCatalogRequest(){
    if($('catalogRequestForm')){
        $('catRequestBack').observe('click', catalogRequestBack);
        $$('.catalogueRequestImages input').each(function (ele) {
            ele.observe('click', verifyCheckboxStatus);
        });
        verifyCheckboxStatus();
    }
}
function catalogRequestBack(){
    $('catRequestBack').removeAttribute('href');// this is for non IE browsers, otherwise they bounce back to the catalog request page
    history.go(-1);
}
function verifyCheckboxStatus(){
    var isFormEnabled = false;
    $$('.catalogueRequestImages input').each(function (el) {
        if(el.checked){
            isFormEnabled = true;
        }
    });
    catalogFormStatus(isFormEnabled);
}
function catalogFormStatus(formStatus){
    if(formStatus){// enable form fields
        $('whatIsThisId').style.display = "inline";
        $('catalogSubmit').style.opacity = 1;
        $('catalogSubmit').className = "button black";// for IE in order not to give the impression the button is disabled for double click
    }
    else{// disable form fields
        $('whatIsThisId').style.display = "none";
        $('catalogSubmit').style.opacity = .5;
        $('catalogSubmit').className = "button black multiClickSubmitButtonId";// for IE in order not to give the impression the button is disabled for double click
    }
    $$('.catalogForm input, .catalogForm select').each(function (elm) {
        elm.disabled = !formStatus;
    });
    $('catalogSubmit').disabled = !formStatus;
}

var blockStatus1 = "displayBlock";
var blockStatus2 = "displayNone";
function initC1NarrowYourSearchFDT(){
    $$('ul.narrowSearchItems').each(function (els) {
        if($('moreRefinementId_' + els.readAttribute('id'))){
            $('moreRefinementId_' + els.readAttribute('id')).observe('click', clickSearchRefinements);
            $('closeMoreRefinementId_' + els.readAttribute('id')).observe('click', clickSearchRefinements);
        }
    });
}
function clickSearchRefinements(){
    var clickLinkClass = this.readAttribute("class");
    $$('ul.narrowSearchItems').each(function (el) {
        if(el.readAttribute('id').indexOf(clickLinkClass) != -1){
            var allLi = el.getElementsByTagName('li');
            for(var x = 0; x < allLi.length; x++){
                if(allLi[x].className.indexOf(blockStatus2) != -1){
                    allLi[x].className = blockStatus1;
                }
                else if(allLi[x].className.indexOf(blockStatus1) != -1){
                    allLi[x].className = blockStatus2;
                }
            }
        }
    });
    blockStatus1 = (blockStatus1 == 'displayBlock' ? 'displayNone' : 'displayBlock');
    blockStatus2 = (blockStatus2 == 'displayBlock' ? 'displayNone' : 'displayBlock');
}

function initRecentlyViewedCookieSetup(){
    if ($('C5ProductDetailsTabsFDT')) {
        // set current productId to cookie for most recently viewed products
        // cookie will contain a string with comma separated productIds
        setMostRecentlyViewedProducts();
    }
}
//---------START initRecentlyViewedAjax-------------------//
function initRecentlyViewedAjax(){
    if($('recentlyViewedProductsId')){
        if(getCookieValue('recentlyViewedCookie') != 0){
            var url = "mostRecentViewedPage.mtw?" + getCookieValue('recentlyViewedCookie') + '&categoryId=' + getCurrentCategoryId() + '&shouldViewRetainState=' + getShouldViewRetainState();
            new Ajax.Request(url, {
                onComplete: function(transport) {

                },
                onSuccess: function(transport) {
                    $('recentlyViewedProductsId').update(transport.responseText);
                    if(!$('recentlyViewedLoadedId')){// this is to hide error from UI
                        $('recentlyViewedProductsId').style.display = "none";
                    }
                },
                onFailure: function(){ alert('RecentlyViewedAjax - Something went wrong...') }
            });
        }
    }
}
function setCurrentCategoryId(cCategId) {
    this.currentCategoryId = cCategId;
}
function getCurrentCategoryId() {
    return this.currentCategoryId;
}
function setShouldViewRetainState(shouldViewRetainState) {
    this.shouldViewRetainState = shouldViewRetainState;
}
function getShouldViewRetainState() {
    return this.shouldViewRetainState;
}

//---------END initRecentlyViewedAjax-------------------//

//---------START initC1LinkListFDT-------------------//
function initC1LinkListFDT() {
    if ($('favouritesId')) {
        $('favouritesId').observe('click', clickAddToFavourites);
    }
}
function clickAddToFavourites() {
    if (window.sidebar) { // firefox
        window.sidebar.addPanel(document.title, self.location, "");
    }
    else if (window.opera && window.print) { // opera
        var elem = document.createElement('a');
        elem.setAttribute('href', self.location);
        elem.setAttribute('title', document.title);
        elem.setAttribute('rel', 'sidebar');
        elem.click();
    }
    else if (document.all) {// ie
        window.external.AddFavorite(self.location, document.title);
    }
    else {// mac ???????????todo
        alert('Please use CTRL + D to bookmark this website.');
    }
}
//---------END initC1LinkListFDT-------------------//

//---------START initC4WishListFDT-------------------//
function initC4WishListFDT() {
    if($('wishListContent')){
        $$('select#itemsPerPageWishList').each(function (el) {
            el.observe('change', WishListFDTPaginationAjax);
        });

//        $$('ul.wishListPagination a').each(function (pageNumberLink) {
//            pageNumberLink.observe('click', WishListFDTPaginationAjax);
//        });
        if($$('div.addToCartMessagePopupLayer').size() > 0){
            lightBox.init($('wishListContent'), 0.1);
            lightBox.centreLayer($$('div.addToCartMessagePopupLayer')[0], 300);
            lightBox.showLayer($$('div.addToCartMessagePopupLayer')[0]);
        }

    //    $$('ul.wishListContent a').each(function (pageNumberLink) {
    //        pageNumberLink.observe('click', WishListFDTRemoveAjax);
    //    });
        if($('continueShop')){
        $('continueShop').observe('click',wishListContinueShop);
    }
}
}
function wishListContinueShop(){
    $('continueShop').removeAttribute('href');// this is for non IE browsers, otherwise they bounce back to the wishlist page
    history.go(-1);
}
function WishListFDTPaginationAjax(event) {
    var form = this.ancestors().find(function (ancestor) {
        return ancestor.tagName == 'FORM';
    });
    var eventNode = this;
//    if(this.tagName == "A"){
//        form.select('input[name="currentPage"]').each(function(pageNumber){
//            pageNumber.value = eventNode.readAttribute('data_pageNumber');
//        });
//    }
    form.submit();

   /* var url = this.readAttribute('href') + "&itemsPerPage=" + $("itemsPerPageWishList").value + "&ajax=true";

    if (this.readAttribute('id') == "itemsPerPageWishList") {
        url = "viewWishList.mtw?itemsPerPage=" + $("itemsPerPageWishList").value + "&ajax=true";
    }

    new Ajax.Request(url, {
        onComplete: function(transport) {
//             update caused some js error so use innerHTML
//            $('wishListContent').update(transport.responseText);
            $('wishListContent').innerHTML = transport.responseText;
            // re-observe events since dom updated
            initC4WishListFDT();
        }
    });*/
    event.stop();
}
function WishListFDTRemoveAjax(event) {
    var url = this.readAttribute('href') + "&ajax=true";
    new Ajax.Request(url, {
        onComplete: function(transport) {
            $('wishListContent').update(transport.responseText);
        }
    });
    event.stop();
}

//---------END initC4WishListFDT----------------------//

//---------START C4MyOrderHistoryFDT-------------------//
function initC4MyOrderHistoryFDT() {
if($("orderHistoryContainer")) {
   $$('select#itemsPerPageOrderHistory').each(function (el) {
        el.observe('change', orderHistoryFDTPaginationAjax);
    });

    $$('form#searchOrderForm a').each(function (el) {
        el.observe('click', searchOrders);
    });

    $$('ul.orderHistoryPagination a').each(function (el) {
        el.observe('click', orderHistoryFDTPaginationAjax);
    });

    $$('table.orderHistoryTable a.orderDetails').each(function (el) {
        el.observe('click', viewOrderHistoryDetailsAjax);
    });

	$$('select#itemsPerPageOrderHistory').each(function (el) {
        el.observe('change', orderHistoryFDTPaginationAjax);
    });

  var from_fieldname = new DatePicker({
        relative:'fromDateCal',
        keepFieldEmpty:true,
        //dateFilter:DatePickerUtils.noWeekends().append(DatePickerUtils.noDatesBefore(1.5)).append(DatePickerUtils.noDatesAfter(60))
        dateFilter:DatePickerUtils.noDatesAfter(0)
    });

    var to_fieldname = new DatePicker({
        relative:'toDateCal',
        keepFieldEmpty:true,
        dateFilter:DatePickerUtils.noDatesAfter(0)
    });

    $$('ul.orderHistoryPagination a').each(function (el) {
        el.observe('click', orderHistoryFDTPaginationAjax);
    });

    $$('table.orderHistoryTable a.orderDetails').each(function (el) {
        el.observe('click', viewOrderHistoryDetailsAjax);
    });
	}
}

function searchOrders(event){
    if (this.readAttribute('id') == 'fromDateCal'){
        alert('from cal........');
    }
    else if (this.readAttribute('id') == 'toDateCal'){
        alert('to cal........');
    }
    else {
        $('searchOrderForm').action = "viewOrderHistory.mtw";
        $('searchOrderForm').submit();
    }
}

function orderHistoryFDTPaginationAjax(event) {
    var url = this.readAttribute('href') + "&fromDate=" + $('fromDate').value + "&toDate=" + $('toDate').value + "&itemsPerPage=" + $("itemsPerPageOrderHistory").value;

    if (this.readAttribute('id') == "itemsPerPageOrderHistory") {
        url = "viewOrderHistory.mtw?fromDate=" + $('fromDate').value + "&toDate=" + $('toDate').value + "&itemsPerPage=" + $("itemsPerPageOrderHistory").value;
    }
    $('orderHistoryForm').action = url;
    $('orderHistoryForm').submit();
    event.stop();
}
function viewOrderHistoryDetailsAjax(event) {
    if($('viewOrder' + this.readAttribute('orderNumber'))){
        if(this.readAttribute('action') == 'view'){
            $('viewOrder' + this.readAttribute('orderNumber')).className = "orderDetails displayNone";
            $('order' + this.readAttribute('orderNumber') + 'Details').className = "orderDetails";
            $('hideOrder' + this.readAttribute('orderNumber')).className = "orderDetails";
        }
        else{
            $('hideOrder' + this.readAttribute('orderNumber')).className = "orderDetails displayNone";
            $('order' + this.readAttribute('orderNumber') + 'Details').className = "orderDetails displayNone";
            $('viewOrder' + this.readAttribute('orderNumber')).className = "orderDetails";
        }
        event.stop();
    }
}
//---------END C4MyOrderHistoryFDT----------------------//

//---------START C4MyPersonalProfileFDT-------------------//
function initMyPersonalProfile() {
    if ($("changePassword")) {
        $("changePassword").observe('click', function() {
            var container = 'passwordResetContainer';
            if ($(container)) {
                $(container).hasClassName('displayNone') ? $(container).removeClassName('displayNone') : $(container).addClassName('displayNone')
            }
        });
    }
}
//---------END C4MyPersonalProfileFDT-------------------//

//---------START initC5MyAccountFDT-------------------//
function initC5MyAccountFDT() {
    if ($('myAccountSigninId')) {
        $('myAccountSigninId').select('a')[0].observe('click', clickForgotMyPassword);
        lightBox.init($('myAccountSigninId'), 0.1);
    }
    if ($('C5BillingShippingFDT')) {
        $('C5BillingShippingFDT').select('a')[0].observe('click', clickForgotMyPassword);
    }
    if($('addressBookId')){
        lightBox.init($('addressBookId'), 0.1);
    }
    if($('addAddressForm')){
        lightBox.init($('addAddressForm'), 0.1);
    }
    if($('orderHistoryContainer')){
        lightBox.init($('orderHistoryContainer'), 0.1);
    }
}
function clickForgotMyPassword() {
    // remove eventual error rmessages and email address
    if($('popupForgotPswdId')){
        $('popupForgotPswdId').className = "errorMessage clearBoth displayNone";
		$('popupForgotPswdId').innerHTML = "";
		$('forgotPasswordEmail').value = "";

		$('resetPasswordBtnC5MyAccountFDT').observe('click', submitForgotMyPassword);
    }
}
function submitForgotMyPassword(event){
    var url = "forgotPassword.mtw?emailAddress=" + $('forgotPasswordEmail').value;
    new Ajax.Request(url, {
        onComplete: function(transport) {

        },
        onSuccess: function(transport) {
            $('lightbox11').update(transport.responseText);
            if($('forgotPasswordStatus')){
                if($('forgotPasswordStatus').innerHTML == 'false'){
                    // closes existing popup
                    $('lightbox1_lightBoxAjax').style.display = "none";
                    // shows succes popup
                    $('lightbox2').style.display = "block";

                    // remove existing child if any
                    $('successPswdId').removeChild( $('successPswdId').firstChild);

                    $('successPswdId').insert($('forgotPwrdEmailId').innerHTML);
                }
                else if($('forgotPasswordStatus').innerHTML == 'true'){
                    // show error message
                    if($('forgotPswdMsgId')){
                        $('popupForgotPswdId').insert($('forgotPswdMsgId').innerHTML)
                        $('popupForgotPswdId').className = "errorMessage clearBoth displayBlock";
                    }
                }
            }
            else{
                // any other error
                $('popupForgotPswdId').className = "errorMessage clearBoth displayBlock";
                $('popupForgotPswdId').insert("There is an error");
            }
        },
        onFailure: function(){ alert('ForgotMyPassword - Something went wrong...') }
    });
}
function popupForgotPassword(){}
//---------END initC5MyAccountFDT-------------------//

//---------START initC5HeaderTopLinksFDT-------------------//
function initC5HeaderTopLinksFDT() {
    if ($('headerTopLinksId')) {
        if (getCookieValue('loginCookie') == 'true') {
            $('headerTopLinksLogoutId').className = "linkDividerLogout";
            $('headerTopLinksLoginId').className = "linkDivider displayNone";
            $('dividerLogoutId').className = "divider";
            $('dividerLoginId').className = "divider displayNone";
        }
        observeC5HeaderTopLinksFDT();
    }
}
function observeC5HeaderTopLinksFDT(){
    $('headerTopLinksLogoutId').observe('click', myAccountLogout);
    if($('myAccountHomePageLogoutId')){
        $('myAccountHomePageLogoutId').observe('click', myAccountLogout);
    }
}
/*  Do an ajax call then reload the page if http or redirect to my account login if https.
    This is necessary because the framework doesn't know where to go after logout.
*/
function myAccountLogout(){
    var url = "myAccountLogout.mtw";
    new Ajax.Request(url, {
        onComplete: function(transport) {
        },
        onSuccess: function(transport) {// reload the page
            if (isCheckoutPage) {
                location.href = "/checkoutBilling.mtw";
            }else if(isSecure == 'false'){
                location.reload(true);// 'true' parameter is necessary to force a reload. Without 'true' the page may be cached and won't reload.
            }else if(!isCheckoutPage){
                location.href = "/myAccountHome.mtw";
            }else if (getCookieValue('loginCookie') == 0){
                $('headerTopLinksLogoutId').className = "linkDivider displayNone";
                $('headerTopLinksLoginId').className = "linkDivider";
                $('dividerLogoutId').className = "divider displayNone";
                $('dividerLoginId').className = "divider";
            }
        },
        onFailure: function(){ alert('Something went wrong during log out...') }
    });
}
//---------END initC5HeaderTopLinksFDT-------------------//

//---------START initC1MiniWishListFDT-------------------//
function initC1MiniWishListFDT() {
    var topMiniWishListObj = $('topMiniWishListId');
    var linkMiniWishListObjs = $$('a.linkMiniWishList');
//    if(topMiniWishListObj && wlQtyObj && linkMiniWishListObjs.size()>0){



        if ($('topMiniWishListId')) {
            var wishListValue = getCookieValue('wishListCookie');
            $('wlQtyId').innerHTML = wishListValue;
            if (wishListValue == 0 || wishListValue > 1) {
                $('wlItemId').innerHTML = getItemsString();
            }
            else {
                $('wlItemId').innerHTML = getItemString();
            }

        if(linkMiniWishListObjs.size()>0){
            if(getCookieValue('loginCookie') != 'true'){// not logged in
                $('topMiniWishListId').select('a.linkMiniWishList')[0].setAttribute("href","#");
                $('topMiniWishListId').select('a.linkMiniWishList')[0].className = "linkMiniWishList lightboxOpener";
                $('topMiniWishListId').select('a.linkMiniWishList')[0].setAttribute('rel','lightbox0');
            }
            else{// logged in
                $('topMiniWishListId').select('a.linkMiniWishList')[0].className = "linkMiniWishList";
                $('topMiniWishListId').select('a.linkMiniWishList')[0].setAttribute('rel','lightbox00');
            }

            }

            lightBox.init($('topMiniWishListId'), 0.1);
        }

//    }

}
//---------END initC1MiniWishListFDT-------------------//

//---------START initC1MiniShoppingCartFDT-------------------//
function initC1MiniShoppingCartFDT() {
    if ($('topMiniShoppingCartId')) {
        var shoppingCartValue = getCookieValue('shopCartCountCookie');
        if($('scQtyId')){
            $('scQtyId').innerHTML = shoppingCartValue;
        }
        if($('scItemId')){
            $('scItemId').innerHTML = getItemsString();
        }
    }
}
//---------END initC1MiniShoppingCartFDT-------------------//

//---------START initC3MainPromoFDT and initC4FeaturedItemsFDT-------------------//
function initC3MainPromoFDT() {
    if($('C3MainPromoFDTId')){
        observeMainPromoImages();
    }
}
function observeMainPromoImages() {
    setIsFeaturedDot(false);
    observePromoImages();
}
var startClock;
var iterationCounter = 0;
function observePromoImages() {
    if ($('dotsWrapperMain') && $('dotsWrapperMain').descendants() != '') {
        $('dotsWrapperMain').style.display = "block";
        $$('#dotsWrapperMain a').each(function (allDots) {
            allDots.observe('click', changePromoImage);
        });
        startClock = setInterval("timerPromoToLoad()", 4000);
    }
}
var rotCounter;
function timerPromoToLoad() {
    iterationCounter++;

    if (iterationCounter > (getSlotCounter() - 1)) {
        rotCounter = iterationCounter - 1;
        // hide this block
        $('rotatingImage' + rotCounter).style.display = "none";
        // turn of this dot
        $('link' + rotCounter).getElementsByTagName('img')[0].src = (getIsFeaturedDot() ? "dotFeaturedOff.gif" : "dotOff.gif");
        iterationCounter = 0;
    }
    else if (iterationCounter > 0) {
        rotCounter = iterationCounter - 1;
        // hide this block
        $('rotatingImage' + rotCounter).style.display = "none";
        // turn off this dot

        $('link' + rotCounter).getElementsByTagName('img')[0].src = (getIsFeaturedDot() ? "dotFeaturedOff.gif" : "dotOff.gif");
    }
    $('rotatingImage' + iterationCounter).style.display = "block";
    $('link' + iterationCounter).getElementsByTagName('img')[0].src = (getIsFeaturedDot() ? "dotFeaturedOn.gif" : "dotOn.gif");
}
function changePromoImage() {
    clearInterval(startClock);
    // set display to hide for all images
    if (getIsFeaturedDot()) {
        $$('#C4FeaturedItemsWrapperId div').each(function (allDivs) {
            if (allDivs.id.indexOf('rotatingImage') != -1) {
                allDivs.style.display = "none";
            }
        });
    }
    else {
        $$('#C3MainPromoFDTId div').each(function (allDivs) {
            if (allDivs.id.indexOf('rotatingImage') != -1) {
                allDivs.style.display = "none";
            }
        });
    }

    // set img to 'off' for all dots
    if ($('dotsWrapperMain')) {
        $$('#dotsWrapperMain img').each(function (allImgs) {
            allImgs.src = (getIsFeaturedDot() ? "dotFeaturedOff.gif" : "dotOff.gif");
        });
    }

    var index = this.id.substring(4, this.id.length);
    $('rotatingImage' + index).style.display = "block";

    // turn the dot ON
    $('link' + index).getElementsByTagName('img')[0].src = (getIsFeaturedDot() ? "dotFeaturedOn.gif" : "dotOn.gif");

    iterationCounter = index;
    startClock = setInterval("timerPromoToLoad()", 4000);
}
//---------END initC3MainPromoFDT and initC4FeaturedItemsFDT-------------------//

//---------START initC4MainPromoFDT -------------------//
function initC4MainPromoFDT() {
    if($('C4MainPromoFDTContainer')){
        observeMainPromoImages1();
    }
}
function observeMainPromoImages1() {
    setIsFeaturedDot(false);
    observePromoImages1();
}
var startClock1;
var iterationCounter1 = 0;
function observePromoImages1() {
    if ($('indicatorContainer')) {
        $('indicatorContainer').style.display = "block";
        $$('#indicatorContainer a').each(function (allDots) {
            allDots.observe('click', changePromoImage1);
        });
        startClock1 = setInterval("timerPromoToLoad1()", 4000);
    }
}
var rotCounter1;
function timerPromoToLoad1() {
    iterationCounter1++;

    if (iterationCounter1 > (getSlotCounter() - 1)) {
        rotCounter1 = iterationCounter1 - 1;
        // hide this block
        $('rotatingImage' + rotCounter1).style.display = "none";
        // turn off this dot
        $('link' + rotCounter1).className = "promoIndicatorOff";
        iterationCounter1 = 0;
    }
    else if (iterationCounter1 > 0) {
        rotCounter1 = iterationCounter1 - 1;
        // hide this block
        $('rotatingImage' + rotCounter1).style.display = "none";
        // turn off this dot

        $('link' + rotCounter1).className = "promoIndicatorOff";
    }
    $('rotatingImage' + iterationCounter1).style.display = "block";
    $('link' + iterationCounter1).className = "promoIndicatorOn";
}
function changePromoImage1() {
    clearInterval(startClock1);
    // set display to hide for all images
    {
        $$('#C4MainPromoFDTContainer div').each(function (allDivs) {
            if (allDivs.id.indexOf('rotatingImage') != -1) {
                allDivs.style.display = "none";
            }
        });
    }

    // set img to 'off' for all dots
    if ($('indicatorContainer')) {
        $$('#indicatorContainer a').each(function (allAnchors) {
            allAnchors.className = "promoIndicatorOff";
        });
    }

    var slot = this.id.substring(4, this.id.length);
    $('rotatingImage' + slot).style.display = "block";

    // turn the dot ON
    $('link'+ slot).className = "promoIndicatorOn";

    iterationCounter1 = slot;
    startClock1 = setInterval("timerPromoToLoad1()", 4000);
}
//--------- END initC4MainPromoFDT -------------------//

//--------- GENERAL-----------------------------------//
function setSlotCounter(sCounter) {
    this.sCounter = sCounter;
}
function getSlotCounter() {
    return this.sCounter;
}
//--------- GENERAL-----------------------------------//


//---------START initC4FeaturedItemsFDT-------------------//
function initC4FeaturedItemsFDT() {
    if ($('C4FeaturedItemsWrapperId')) {
        observeFeaturedPromoImages();
    }
}
function observeFeaturedPromoImages() {
    setIsFeaturedDot(true);
    observePromoImages();
}
function setIsFeaturedDot(fDot) {
    this.fDot = fDot;
}
function getIsFeaturedDot() {
    return this.fDot;
}
//---------END initC4FeaturedItemsFDT-------------------//


//---------START initC5BillingShippingFDT-------------------//

function initC5BillingShippingFDT() {
    if ($('C5BillingShippingFDT')) {
        observeSameAsBillingAddress();
        observeSameAsBillingAddress();
        if ($('billAddrselector')){
            var billingAdd = $('billAddrselector').options[$('billAddrselector').selectedIndex].text != 'New Address' ? $('billAddrselector').options[$('billAddrselector').selectedIndex].value : '';
            if ((billingAdd == 'text.global.mydefaultbill' || billingAdd == 'text.global.mydefaultship')){
                $('billAddrAliasNone').style.display = "none";
                $('billAddrAliasDefault').style.display = "inline";
            }
            else {
                $('billAddrAliasDefault').style.display = "none";
                $('billAddrAliasNone').style.display = "inline";
            }
            $('billAddrAliasDefault').value = $('billAddrselector').options[$('billAddrselector').selectedIndex].text;
            $('billAddrAliasNone').value = $('billAddrselector').options[$('billAddrselector').selectedIndex].text;
        }
        if ($('shipAddrselector')){
            var shippingAdd = $('shipAddrselector').options[$('shipAddrselector').selectedIndex].text != 'New Address' ? $('shipAddrselector').options[$('shipAddrselector').selectedIndex].value : '';
            if ((shippingAdd == 'text.global.mydefaultbill' || shippingAdd == 'text.global.mydefaultship')){
                $('shipAddrAliasNone').style.display = "none";
                $('shipAddrAliasDefault').style.display = "inline";
            }
            else {
                $('shipAddrAliasDefault').style.display = "none";
                $('shipAddrAliasNone').style.display = "inline";
            }
            $('shipAddrAliasDefault').value = $('shipAddrselector').options[$('shipAddrselector').selectedIndex].text;
            $('shipAddrAliasNone').value = $('shipAddrselector').options[$('shipAddrselector').selectedIndex].text;
        }
    }
}

/*
function initC5BillingShippingFDT() {
    if ($('C5BillingShippingFDT')) {
        observeSameAsBillingAddress();
        if($('shipAddrSameAsBill')){
        $('shipAddrSameAsBill').click();
        }
    }
    if($('updateCartId')){
        lightBox.init($('updateCartId'), 0.1);
    }
}
*/
function aliasVal(whichMethod){
    $(whichMethod + 'AddrAlias').value = $(whichMethod + 'AddrAliasNone').value;
}
function observeSameAsBillingAddress() {
    if($('shipAddrSameAsBill')){
    $('shipAddrSameAsBill').observe('click', toggleShippingAddress);
    }
}
function toggleShippingAddress() {
    if ($('shippingFormFields')){
        $('shippingFormFields').style.display = $('shipAddrSameAsBill').checked ? 'none' : 'block';
    }
    if($('addrSelectAreaId')){
        $('addrSelectAreaId').style.display = $('shipAddrSameAsBill').checked ? 'none' : 'block';
    }
}
//---------END initC5BillingShippingFDT-------------------//

//---------START initC5ReviewPaymentFDT-------------------//
function initC5ReviewPaymentFDT(){
    if($('reviewPaymentBack')){
        $('reviewPaymentBack').observe('click', backToBillingShipping);
    }
}

function backToBillingShipping(){
    history.back();
}
//---------END initC5ReviewPaymentFDT-------------------//

//---------START C5HeaderTopFDT-------------------//
function initC5HeaderTopFDT() {
    if ($('formSearchResults')) {
        $('frmTextSimpleSearch').value = searchFormFieldValue;
        observeHeaderTopSearch();
    }
}
// add onclick event to form field
function observeHeaderTopSearch() {
    $('frmTextSimpleSearch').observe('click', removeText);
}
// remove the text from form field onclick
function removeText() {
    $('frmTextSimpleSearch').value = "";
}
function setSearchFormFieldValue(searchFormFieldValue) {
    this.searchFormFieldValue = searchFormFieldValue;
}
function getSearchFormFieldValue() {
    return this.searchFormFieldValue;
}
//---------END C5HeaderTopFDT-------------------//

//---------START ProductDetailsPage.mtw-----------//
//START C5ProductTabsFDT.jsp
// attach events to product details tabs
function initC5ProductDetailsTabsFDT() {
    // may be it is better to have all FDT container div to have its FD names as it id so we can check exitence.
//    $$('div.pr-snippet-read-reviews a').each(function (el) {
//        alert('123');
//        el.observe('click', readReview);
//    });
}

function readReview(event){

    var selectedTabIndex = clickedLiNode.previousSiblings().size();
    $$('#tabsContainerC5ProductDetailsTabsFDT li.selected', '#tabsContainerC5ProductDetailsTabsFDT li.firstSelected').each(function(selected){
        selected.removeClassName('selected');
        selected.removeClassName('firstSelected');
    });
    // highlight the tab
    if(clickedLiNode.hasClassName('first')){
        clickedLiNode.addClassName('firstSelected');
    }
    else{
        clickedLiNode.addClassName('selected');
    }
    // hide content,
    $$('#tabContentContainerC5ProductDetailsTabsFDT div.currentShowing')[0].removeClassName('currentShowing').addClassName('displayNone');
    // show selected content
    $$('#tabContentContainerC5ProductDetailsTabsFDT div.tabContentBody')[selectedTabIndex].removeClassName('displayNone').addClassName('currentShowing');
}

function observeTabChangeEvents() {
    $$('#tabsContainerC5ProductDetailsTabsFDT li.normal', '#tabsContainerC5ProductDetailsTabsFDT li.selected', '#tabsContainerC5ProductDetailsTabsFDT li.first').each(function (tabLi) {
        tabLi.select('a')[0].observe('click', changeTab);
    });
}
function observeAltImageChangeEvents() {
    $$('li.altImage').each(function (altImgThumb) {
        altImgThumb.observe('click', changeProductImage);
    });
}

function changeTab(event) {
    var clickedLiNode = this.up();
    var selectedTabIndex = clickedLiNode.previousSiblings().size();
    $$('#tabsContainerC5ProductDetailsTabsFDT li.selected', '#tabsContainerC5ProductDetailsTabsFDT li.firstSelected').each(function(selected){
        selected.removeClassName('selected');
        selected.removeClassName('firstSelected');
    });
    // highlight the tab
    if(clickedLiNode.hasClassName('first')){
        clickedLiNode.addClassName('firstSelected');
    }
    else{
        clickedLiNode.addClassName('selected');
    }
    // hide content,
    $$('#tabContentContainerC5ProductDetailsTabsFDT div.currentShowing')[0].removeClassName('currentShowing').addClassName('displayNone');
    // show selected content
    $$('#tabContentContainerC5ProductDetailsTabsFDT div.tabContentBody')[selectedTabIndex].removeClassName('displayNone').addClassName('currentShowing');
    event.stop();
}
//END C5ProductTabsFDT.jsp
//START C5ProductDetailsFDT.jsp
function initC5ProductDetailsFDTEvents() {
    if ($('C5ProductDetailsFDT')) {
        lightBox.init($('C5ProductDetailsFDT'), 0.1);
//        alert('initiallize product details page!');
        //    setAddToCartButtonInitStatue();
        observeSelectSkuOptionsEvent();
        initPersonalizationFields();
        // wishlist function not needed until post launch
//        if($('C5ProductDetailsFDTaddToWishListButtonId')){
//            $('C5ProductDetailsFDTaddToWishListButtonId').observe('click', function() {
//                $('C5ProductDetailsFDTFormId').action = 'addProductToWishList.mtw';
//            });
//        }
        }

    // observe thumb click event
    observeThumbEvents();
}
var productDetailPageFirstLoad = true;
function initC5ProductDetailsFDTUI(){
    $$('input[name="selectSkuGoButton"]').each(function(goButton){
        goButton.remove();
    });

    showSwatchThumbs();
    disableSelectGroupForJSDisabled();
    if ($('l1SelectC5ProductDetailsFDT')) {
        // set product details image and tab content base on default shown sku options. (the orders are different)
        l1SkuOptionSelectChanged();
        productDetailPageFirstLoad = false;
    }
    if($('personalizationFieldsC5ProductDetailsFDT'))
        $('personalizationFieldsC5ProductDetailsFDT').addClassName('displayNone');

    if($$('input.flatProductIdInputFiledIndentifier').size() > 0){
        //when there it is a flat product
        var currentId = $F($$('input.flatProductIdInputFiledIndentifier')[0]);
        if($$('div.tabContentBody table.productCrossSell').size() == 0 && $('productDetailsCrossSellTab')){
            $('productDetailsCrossSellTab').addClassName('displayInvisible');
        }
    }



}
function showSwatchThumbs(){
    // show thumb first
    $$('div.detailsImageThumbsContainer').each(function (thumbContainer){
        thumbContainer.removeClassName('displayNone');
    });
    var swatchTapeSize = 2;
    $$('#productDetailsSwatchImagesContainerId div.swatchImageContainer').each(function(swatchImageContainer){
        swatchTapeSize = swatchTapeSize + swatchImageContainer.getWidth();
    });
}
function observeThumbEvents(){
    // attach events to thumbs
    $$('.detailsImageThumbsContainer .detailsImageThumbs').each(function (thumb){
        thumb.observe('click', function(e){
            $$('#productDetailsSwatchImagesContainerId div.border2DashedGrey').each(function (swatchImageContainer){
                swatchImageContainer.removeClassName('border2DashedGrey');
                swatchImageContainer.removeClassName('padding3px');
                swatchImageContainer.addClassName('padding5px')
            });
            this.up().addClassName('border2DashedGrey');
            this.up().addClassName('padding3px');
            this.up().removeClassName('padding5px');
            updateProductDetailsImages(this.readAttribute('skuId'));
            e.stop();
        });
    });
}

function setMostRecentlyViewedProducts(){
    var stringWithCurrentProductId;
    if(getCookieValue('recentlyViewedCookie') != 0){// cookie exists
        setCookieValue('recentlyViewedCookie',updateRecentlyViewedString(getCookieValue('recentlyViewedCookie'), getCurrentProductId()));
    }
    else{// cookie doesn't exist
        stringWithCurrentProductId = 'productIds.' + "1" + '=' + getCurrentProductId();
        setCookieValue('recentlyViewedCookie',stringWithCurrentProductId);
    }
}
function updateRecentlyViewedString(cookieValue, prodId){
    var listCounter;
    var isDuplicate = false;
    var recentlyViewedString = cookieValue;
    var arrayRecentlyViewedString = recentlyViewedString.split('&');
    var productListJson = cookieValue.toQueryParams();
    var shiftStartIndex = 1;
    // checking if there are duplicated values
    for(var x = 0; x < arrayRecentlyViewedString.length; x++){
        if(arrayRecentlyViewedString[x].split('=')[1] == prodId){
            isDuplicate = true;
            shiftStartIndex = x + 1;
        }
    }
    if(!isDuplicate && arrayRecentlyViewedString.length < 3){
            listCounter = parseInt(arrayRecentlyViewedString.length + 1);
            return (recentlyViewedString + '&' + 'productIds.' + listCounter + '=' + prodId);
    }
    else{
        // shift up products:
            // 1. shiftStartIndex == 1 means it is not a duplicate
            // 2. shiftStartIndex > 1  means it is a duplicate so move it to top (index 5)
        for(var count = shiftStartIndex; count < arrayRecentlyViewedString.length; count++){
            productListJson['productIds.' + count] = productListJson['productIds.' + (count + 1)];
        }
        productListJson['productIds.' + arrayRecentlyViewedString.length] = prodId;
        return Object.toQueryString(productListJson);
    }
}
function disableSelectGroupForJSDisabled() {
    $$('#jsDisabledL2SelectContainerC5ProductDetailsFDT select').each(function (select) {
        select.disable();
    });
//    if ($('jsDisabledL1SelectContainerC5ProductDetailsFDT')) {
//        $('jsDisabledL1SelectContainerC5ProductDetailsFDT').removeClassName('displayNone');
//    }
    $$('#jsDisabledL1SelectContainerC5ProductDetailsFDT').each(function (jsDisabledL1SelectContainerC5ProductDetailsFDT){
        jsDisabledL1SelectContainerC5ProductDetailsFDT.removeClassName('displayNone');
    });

//    if ($('jsDisabledL2SelectContainerC5ProductDetailsFDT')) {
//        $('jsDisabledL2SelectContainerC5ProductDetailsFDT').addClassName('displayNone');
//    }
    $$('#jsDisabledL2SelectContainerC5ProductDetailsFDT').each(function(jsDisabledL2SelectContainerC5ProductDetailsFDT){
        jsDisabledL2SelectContainerC5ProductDetailsFDT.addClassName('displayNone');
    });
//    if ($('jsEnabledC5ProductDetailsFDT')) {
//        $('jsEnabledC5ProductDetailsFDT').removeClassName('displayNone');
//    }
    $$('#jsEnabledC5ProductDetailsFDT').each(function(jsEnabledC5ProductDetailsFDT){
        jsEnabledC5ProductDetailsFDT.removeClassName('displayNone');
    });
    // enable level sku option select if it exist since it is disabled by default
//    if ($('l1SelectC5ProductDetailsFDT')) {
//        $('l1SelectC5ProductDetailsFDT').enable();
//    }
    $$('#l1SelectC5ProductDetailsFDT').each(function(l1SelectC5ProductDetailsFDT){
        l1SelectC5ProductDetailsFDT.enable();
    });
}
function observeSelectSkuOptionsEvent() {
//    if ($('l1SelectC5ProductDetailsFDT')) {
//        $('l1SelectC5ProductDetailsFDT').observe('change', l1SkuOptionSelectChanged);
//    }
    $$('#l1SelectC5ProductDetailsFDT').each(function(l1SelectC5ProductDetailsFDT){
        l1SelectC5ProductDetailsFDT.observe('change', l1SkuOptionSelectChanged);
    });
    $$('select.l2SkuOptionsSelects').each(function (l2Select) {
        l2Select.observe('change', l2SkuOptionSelectChanged)
    });
}
function initPersonalizationFields() {
    $$('#personalizationCheckC5ProductDetailsFDT').each(function(personalizationCheckBox){
        personalizationCheckBox.observe('click',function(event){
            if (event.element().checked == true) {
                $('personalizationFieldsC5ProductDetailsFDT').removeClassName('displayNone');
            }
            else {
                $('personalizationFieldsC5ProductDetailsFDT').addClassName('displayNone');
            }
        });
    });
}
function l1SkuOptionSelectChanged() {
    var selectedL1SkuOption = $F('l1SelectC5ProductDetailsFDT');
    // hide all l2selects
    $$('select.l2SkuOptionsSelects').each(function (l2Select) {
        if (selectedL1SkuOption != null && selectedL1SkuOption != "") {
            l2Select.addClassName('displayNone');
        }
        l2Select.disable();
    });
    // show selectedL2SkuOption
    if ($(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT')) {
        $(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT').enable().removeClassName('displayNone');
        updateSkuOptionTabContents($F(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT'));
        updateProductDetailsImages($F(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT'));
        updateSwatchImageHighLight($F(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT'));
        updateSkuInventoryMessage($F(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT'));
        updateSkuAvailableChannelMessage($F(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT'));
        updateHeavyWeightLogo(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT');
//        updateProductDetailsShowingPrice(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT');
        updateShowingAddons($F(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT'));
        updateShowingMappingProducts($F(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT'));
        updateProductDetailsShowingPrice($F(selectedL1SkuOption + 'L2SelectC5ProductDetailsFDT'));
    }
    else {
        // means there is only one sku options level
        updateSkuOptionTabContents(selectedL1SkuOption);
        updateProductDetailsImages(selectedL1SkuOption);
        updateSwatchImageHighLight(selectedL1SkuOption);
        updateSkuInventoryMessage(selectedL1SkuOption);
        updateSkuAvailableChannelMessage(selectedL1SkuOption);
//        updateProductDetailsShowingPrice('l1SelectC5ProductDetailsFDT');
        updateShowingAddons(selectedL1SkuOption);
        updateShowingMappingProducts(selectedL1SkuOption);
        updateProductDetailsShowingPrice(selectedL1SkuOption);
    }
}

function updateShowingAddons(skuOptionProductId){
    $$('div.productAddon').each(function (el){
        if(el.readAttribute('data_id') == 'productAddon_' + skuOptionProductId){
            el.removeClassName('displayNone');
            el.select('input', 'select', 'textarea').each(function(formEl){
                formEl.enable();
            });
        }
        else{
            el.addClassName('displayNone');
            el.select('input', 'select', 'textarea').each(function(formEl){
                formEl.disable();
            });
        }
    });
}

function updateShowingMappingProducts(skuOptionProductId){
    var hasCrossSell = false;
    var hasUpSell = false;
    $$('table.productCrossSell').each(function(table){
        if(table.readAttribute('data_id') == 'productCrossSell_' + skuOptionProductId){
            table.removeClassName('displayNone');
            hasCrossSell = true;
        }
        else{
            table.addClassName('displayNone');
        }
    });
    if(hasCrossSell && $('productDetailsCrossSellTab')){
        $('productDetailsCrossSellTab').removeClassName('displayInvisible');
    }
    else if ($('productDetailsCrossSellTab')){
        $('productDetailsCrossSellTab').addClassName('displayInvisible');
        if($('productDetailsCrossSellTab').hasClassName('selected')){
            highlightFirstTab();
        }
    }
//    $$('table.productUpSell').each(function(table){
//        if(table.readAttribute('data_id') == 'productUpSell_' + skuOptionProductId ){
//            table.removeClassName('displayNone');
//            hasUpSell = true;
//        }
//        else{
//            table.addClassName('displayNone');
//        }
//    });
//    if(hasCrossSell && $('productDetailsUpSellTab')){
//        $('productDetailsUpSellTab').removeClassName('displayNone');
//    }
//    else if ($('productDetailsCrossSellTab')){
//        $('productDetailsUpSellTab').addClassName('displayNone');
//    }
}
function highlightFirstTab(){
    if($$('#tabsContainerC5ProductDetailsTabsFDT li.first').size() > 0){
        var clickedLiNode = $$('#tabsContainerC5ProductDetailsTabsFDT li.first')[0];
        var selectedTabIndex = 0;
        $$('#tabsContainerC5ProductDetailsTabsFDT li.selected').each(function(selected){
            selected.removeClassName('selected');
        });
        // highlight the tab
        clickedLiNode.addClassName('firstSelected');
        // hide content,
        $$('#tabContentContainerC5ProductDetailsTabsFDT div.currentShowing').each(function(tab){
            tab.removeClassName('currentShowing').addClassName('displayNone');
        });
        // show selected content
        $$('#tabContentContainerC5ProductDetailsTabsFDT div.tabContentBody')[selectedTabIndex].removeClassName('displayNone').addClassName('currentShowing');
    }
}

function updateProductDetailsShowingPrice(selectId){
    $$('div.priceDisplayContainer').each(function (priceContainer){
        if(priceContainer.readAttribute('id') == 'productDetailsPriceContainer' + selectId +'Id'){
            priceContainer.style.display = "block";
        }
        else{
            priceContainer.style.display = "none";
        }
    });
    $$('p.productDetailsDesc').each(function (descContainer){
        if(descContainer.readAttribute('id') == 'productDetailsDescContainer' + selectId +'Id'){
            descContainer.style.display = "block";
        }
        else{
            descContainer.style.display = "none";
        }
    });
}

function updateSwatchImageHighLight(selectedL1SkuOption){
    $$('#productDetailsSwatchImagesContainerId div.border2DashedGrey').each(function(previousSelected){
        previousSelected.removeClassName('border2DashedGrey');
        previousSelected.removeClassName('padding3px');
        previousSelected.addClassName('padding5px');
    });
    $$('#productDetailsSwatchImagesContainerId .detailsImageThumbs[skuid='+selectedL1SkuOption+']').each(function(selectedSwatchImage){
        selectedSwatchImage.up().addClassName('border2DashedGrey');
        selectedSwatchImage.up().addClassName('padding3px');
        selectedSwatchImage.up().removeClassName('padding5px');
    });
}
function l2SkuOptionSelectChanged(event) {
    updateProductDetailsImages($F(this));
    updateSkuOptionTabContents($F(this));
    updateSwatchImageHighLight($F(this));
    updateSkuInventoryMessage($F(this));
    updateSkuInventoryMessage($F(this));
    updateHeavyWeightLogo($(this).id);
//    updateProductDetailsShowingPrice($(this).id);
    updateProductDetailsShowingPrice($F(this));
    updateShowingAddons($F(this));
    updateShowingMappingProducts($F(this));
}

// function to update sku option inventory message and enable/disable add to cart button
function updateSkuInventoryMessage(skuOptionProductId){
    $$('div.C5ProductDetailsFDTInventoryInfoContainer span').each(function(span){
        if(span.hasClassName("C5ProductDetailsFDTInventoryInfo" + skuOptionProductId)){
            span.removeClassName("displayNone");
            if(span.hasClassName('OUT_OF_STOCK')){
                $('addToCartBtnC5ProductDetailsFDT').disable();
                $('addToCartBtnC5ProductDetailsFDT').className = "multiClickSubmitButtonId bigSubmitButton lightboxOpener cursorPointer disabled";
            }
            else{
                $('addToCartBtnC5ProductDetailsFDT').enable();
                $('addToCartBtnC5ProductDetailsFDT').className = "multiClickSubmitButtonId bigSubmitButton lightboxOpener cursorPointer";
            }
        }
        else{
            span.addClassName("displayNone");
        }
    });
}
function updateSkuAvailableChannelMessage(skuOptionProductId){
    $$('div.C5ProductDetailsFDTAvailableChannelInfoContainer span').each(function(span){
        if(span.hasClassName("C5ProductDetailsFDTAvailableChannelInfo" + skuOptionProductId)){
            span.removeClassName("displayNone");
            if(span.hasClassName('true')){
                $('addToCartBtnC5ProductDetailsFDT').disable();
                $('addToCartBtnC5ProductDetailsFDT').className = "multiClickSubmitButtonId bigSubmitButton lightboxOpener cursorPointer disabled";
            }
            else{
                $('addToCartBtnC5ProductDetailsFDT').enable();
                $('addToCartBtnC5ProductDetailsFDT').className = "multiClickSubmitButtonId bigSubmitButton lightboxOpener cursorPointer";
            }
        }
        else{
            span.addClassName("displayNone");
        }
    });
}

// function to update product image base on selected sku option
function updateProductDetailsImages(skuOptionProductId) {
    $$('#flashC5ProductDetailsFDT > div.productImageContainer').each(function (flashDiv) {
        if (flashDiv.hasClassName('productImageContainerId' + skuOptionProductId)) {
            flashDiv.removeClassName('displayNone');
        }
        else {
            flashDiv.addClassName('displayNone');
        }
    });
}
// changed all tabs' content to reflect currently selected sku option
function updateSkuOptionTabContents(skuOptionProductId) {
    $$('#tabContentContainerC5ProductDetailsTabsFDT div.skuOptionTabContents').each(function (skuOptionTabContentDiv) {
        if (skuOptionTabContentDiv.hasClassName('C5ProductDetailsTabsFDT_tabContentId' + skuOptionProductId)) {
            skuOptionTabContentDiv.removeClassName('displayNone');
        }
        else {
            skuOptionTabContentDiv.addClassName('displayNone');
        }
    });
}
//END C5ProductDetailsFDT.jsp
//---------END ProductDetailsPage.mtw-----------//
//---------START searchResults.mtw -------------//
//-----START inc_C4PaginationContainer.jsp -----//
function initInc_C4PaginationContainerJSP() {
    if ($$('div.inc_C4PaginationConatinerJSP').size() != 0) {
        observeSortByChangedEvent();
        observeProductsPerPageChangedEvent();
    }
}
function observeSortByChangedEvent() {
    $$('select.sortBySelectInc_C4PaginationConatinerJSP').each(function (el) {
        el.removeClassName('displayNone');
        el.observe('change', sortAJAXCall);
    });
    $$('div.sortBySelectJSDisabledInc_C4PaginationConatinerJSP').each(function (el) {
        el.addClassName('displayNone');
    });
}
function observeProductsPerPageChangedEvent() {
    $$('select.productsPerPageSelectInc_C4PaginationConatinerJSP').each(function (el) {
        el.removeClassName('displayNone');
        el.observe('change', paginationAJAXCall);
    });
    $$('div.productsPerPageSelectJSDisabledInc_C4PaginationConatinerJSP').each(function (el) {
        el.addClassName('displayNone');
    });
}


function paginationAJAXCall(event) {
 	toggleWaitCurosr();
    // find which pagination parameter is changed, top or bottom
    var eventPaginationContainer = this.ancestors().find(function (ancestor) {
        return ancestor.hasClassName('paginationContainer');
    });
    var url = $F(eventPaginationContainer.select('select.productsPerPageSelectInc_C4PaginationConatinerJSP')[0]);


    url = url + "&tc=" + $F($$('input[name="tc"]')[0]);
	initInc_C4PaginationContainerJSP();
    window.location = url;
}

function sortAJAXCall(event) {
	toggleWaitCurosr();
    // find which pagination parameter is changed, top or bottom
    var eventPaginationContainer = this.ancestors().find(function (ancestor) {
        return ancestor.hasClassName('paginationContainer');
    });
 	var url = $F(eventPaginationContainer.select('select.sortBySelectInc_C4PaginationConatinerJSP')[0]);

    url = url + "&tc=" + $F($$('input[name="tc"]')[0]);
	initInc_C4PaginationContainerJSP();
    window.location = url;
}

function paginationOrSortAJAXCall(event, sourceSelect) {
    toggleWaitCurosr();
    // find which pagination parameter is changed, top or bottom
    var eventPaginationContainer = this.ancestors().find(function (ancestor) {
        return ancestor.hasClassName('paginationContainer');
    });
 	var url = $F(eventPaginationContainer.select(sourceSelect)[0]);

    url = url + "&tc=" + $F($$('input[name="tc"]')[0]);
	initInc_C4PaginationContainerJSP();
    window.location = url;
}
//-----END inc_C4PaginationContainer.jsp -------//
//---------END searchResults.mtw ---------------//
//----------start Shared methods----------------//
function toggleWaitCurosr() {
    $$('body')[0].toggleClassName('waiting');
}
function getCurrentActionName() {
    return window.location.href.split('?')[0];
}
//------------end Shared methods----------------//



// ---- begin for shopping cart and checkout pages --- //

/*******************************************************************************************
 *  Note: All class name has 'domReady_' will be catched by below function!!!!!!!!!!!
 *       This name fraction is the reserved name fraction for brookstone, and imr in js lib.
 *       Let me know if you guys have any questions.
 * *****************************************************************************************/

var domReadyInitFunctionsCollections = {
    go: function() {
        if (document.selection) {
            clearTimeout(ieDelay);
        }

        var hidemewhenjson = $$(".forjsoffsituation_off");
        var showmewhenjson = $$(".forjsoffsituation_on");
        if (hidemewhenjson) {
            hidemewhenjson.each(function(targetElement) {
                targetElement.addClassName("displayNone");
            })
        }
        if (showmewhenjson) {
            showmewhenjson.each(function(targetElement) {
                targetElement.removeClassName("displayNone");
            })
        }
    }
};

var domReadyEventFunctionsCollections = {
    doTest1: function(e, c) {
        alert("current class: " + c + " | event: " + e.element().className);
        Event.stop(e);
        return false;
    },
    doTest2: function(e, c) {
        var keyunicode = e.charCode || e.keyCode;
        if (keyunicode == 13) {
            alert("current class: " + c + " | event: " + e.element().className);
            Event.stop(e);
        }
        return false;
        //        Event.stop(e);
    },
    doEstimateShipCost:function(e, c) {
        var currentObj = e.element();
        var refreshNeedObj = $("hasRefreshedShippingMethods");
        if (currentObj) {
            if(refreshNeedObj){
                refreshNeedObj.value = true;
                if (currentObj.value != ""){
                    util.formSubmit("toReviewPayment");
                }
            }
        }
    },
    doSignatureReqSync:function(e, c) {
        var currentObj = e.element();
        if (currentObj) {
            var syncObj = $("d" + currentObj.id);
            if (syncObj) {
                syncObj.checked = currentObj.checked;
            }
        }
    },
    doUpdateTotal:function(e, c) {
        util.formSubmit("checkoutMultiShipReview", "checkoutMultiShipReview.mtw?shouldUpdateTotal=true");
    },
    doSwitchAddress:function(e, c) {
        if (gigo4bs) {
            var currentObj = e.element();
            var currentSurf;

            if (currentObj.id == "billAddrselector") {
                currentSurf = "bill"
            } else if (currentObj.id == "shipAddrselector") {
                currentSurf = "ship"
            }

            gigo4bs.addressList[currentObj.selectedIndex].fieldList.each(function(o) {
                try {
                    if ($(currentSurf + o.name).id == 'billAddrAlias' || $(currentSurf + o.name).id == 'shipAddrAlias'){
                        if((o.value == 'text.global.mydefaultbill' || o.value == 'text.global.mydefaultship')){
                            $(currentSurf + 'AddrAliasNone').style.display = "none";
                            $(currentSurf + 'AddrAliasDefault').style.display = "inline";
                        }
                        else{
                            $(currentSurf + 'AddrAliasDefault').style.display = "none";
                            $(currentSurf + 'AddrAliasNone').style.display = "inline";
                        }
                        $(currentSurf + 'AddrAlias').value = currentObj.options[currentObj.selectedIndex].text != 'New Address' ? currentObj.options[currentObj.selectedIndex].text : '';
                        $(currentSurf + 'AddrAliasNone').value = currentObj.options[currentObj.selectedIndex].text != 'New Address' ? currentObj.options[currentObj.selectedIndex].text : '';
                        $(currentSurf + 'AddrAliasDefault').value = currentObj.options[currentObj.selectedIndex].text != 'New Address' ? currentObj.options[currentObj.selectedIndex].text : '';
                        $(currentSurf + o.name).value = currentObj.options[currentObj.selectedIndex].text != 'New Address' ? currentObj.options[currentObj.selectedIndex].text : '';
                    }
                    else {
                        $(currentSurf + o.name).value = o.value;
                    }
                } catch(err) {
                    alert("can't find id : " + currentSurf + o.name);
                }
            })

        }
    },

    requestGiftCardBalance:function(e, c){
        var balanceCheckResult;
//        new Ajax.Request(url, {
//            onComplete: function(transport) {
//                balanceCheckResult = transport.evalJson();
//            }
//        });
        //TODO removed the mock data assignment balanceCheckResult since it should come from AJAX
        balanceCheckResult = {
            "errorMessage" : "No error message." + Math.floor(Math.random()*11),
            "currentBalance" : Math.floor(Math.random()*10000)/100
        }
        $('giftCardBalanceCheckErrorMessage').update(balanceCheckResult.errorMessage);
        $('currentAvailableBalanceId').update(' $' + balanceCheckResult.currentBalance);
        Event.stop(e);
    },

    billAddrCreateVip:function(e, c){
        if($("billAddrCreateVip").checked){
            $$(".vipLoginMust").each(function(targetElement){
                targetElement.removeClassName("displayNone");
            })
        }else{
            $$(".vipLoginMust").each(function(targetElement){
                targetElement.addClassName("displayNone");
            })
        }
    },

    confirmPrint:function(e, c){
        window.print();
    },
    reviewPrint:function(e, c){
        window.print();
    },
    giftCardEmailSaveAjax:function(e, c){
        var currentElement = e.element();
        var currentElementId = currentElement.identify();
        if(currentElementId.indexOf("_edit")>=0){

            var idPrefix = currentElementId.substring(0, currentElementId.indexOf("_edit")).strip();

            currentElement.addClassName("displayNone");




            $(idPrefix+"_save").removeClassName("displayNone");
            $(idPrefix).disabled = false;



        }else if(currentElementId.indexOf("_save")>=0){
            //do ajax call
//            var currentElementId = e.element().identify();
            var idPrefix = currentElementId.substring(0,currentElementId.indexOf('_save')).strip();
            var tagetInputsContainerId = idPrefix+"_section";
//            alert(tagetInputsContainerId);

            var arr = $(tagetInputsContainerId).select('.domSerializableField');
            if(arr.length>0){
                var params = Form.serializeElements(arr);
                url = "editGiftCard.mtw";

                new Ajax.Request(
                    url,
                    {
                        method: 'post',
                        parameters: params,
                        onSuccess: function(response){
                            var jsonObj = response.responseText.evalJSON();
                            if(jsonObj.hasError){
                                var errors = "";
                                jsonObj.errors.each(function(gError){
                                    errors = errors + gError.errorMessage;
                                })
                                $(idPrefix+"_error").innerHTML = errors;
                            }else{
                                // prepare for success msg
                                var errors = "";
                                $(idPrefix+"_error").innerHTML = errors;

                                $(idPrefix).disabled = true;
                                $(idPrefix+"_save").addClassName("displayNone");
                                $(idPrefix+"_edit").removeClassName("displayNone");
                            }

                        },
                        onFailure: function () {
//                            alert("failed");
                            $(idPrefix+"_error").innerHTML = "Ajax call failed!";
                        }
                    });

            }

        }
    },
    changeTab: function (event, c){
        var clickedLiNode = event.element().up();
        var selectedTabIndex = clickedLiNode.previousSiblings().size();
        $$('#tabsContainerC5ProductDetailsTabsFDT li.selected', '#tabsContainerC5ProductDetailsTabsFDT li.firstSelected').each(function(selected){
            selected.removeClassName('selected');
            selected.removeClassName('firstSelected');
        });
        // highlight the tab
        if(clickedLiNode.hasClassName('first')){
            clickedLiNode.addClassName('firstSelected');
        }
        else{
            clickedLiNode.addClassName('selected');
        }
        // hide content,
        $$('#tabContentContainerC5ProductDetailsTabsFDT div.currentShowing')[0].removeClassName('currentShowing').addClassName('displayNone');
        // show selected content
        $$('#tabContentContainerC5ProductDetailsTabsFDT div.tabContentBody')[selectedTabIndex].removeClassName('displayNone').addClassName('currentShowing');
        event.stop();
    },
    swatchSlideLeft: function(e, c){
        // the last value of the following
        var remainingTape = $('productDetailsSwatchImagesContainerId').getWidth() + parseInt($('productDetailsSwatchImagesContainerId').style.left.split('px')[0]) - $('productDetailsSwatchImageSlidingWindow').getWidth();
        if(remainingTape >0){
            var shiftDistance = remainingTape > $('productDetailsSwatchImageSlidingWindow').getWidth() ? $('productDetailsSwatchImageSlidingWindow').getWidth() : remainingTape;
    //        var currentShowing = $$('div.detailsImageThumbsContainer div.swatchShowing');
    //        if(currentShowing[currentShowing.size() - 1].next()){
    //            currentShowing[currentShowing.size() - 1].next().removeClassName('displayNone');
    //            currentShowing[currentShowing.size() - 1].next().addClassName('swatchShowing');
                new Effect.Move($('productDetailsSwatchImagesContainerId'), { x: -shiftDistance, transition: Effect.Transitions.sinoidal});
    //            currentShowing[0].addClassName('displayNone');
    //            currentShowing[0].removeClassName('swatchShowing');
    //        }
        }
            e.stop();
    },
    swatchSlideRight: function(e, c){
        var remainingTape = parseInt($('productDetailsSwatchImagesContainerId').style.left.split('px')[0]);
        if(remainingTape < 0){
            var shiftDistance = Math.abs(remainingTape) > $('productDetailsSwatchImageSlidingWindow').getWidth() ? $('productDetailsSwatchImageSlidingWindow').getWidth() : Math.abs(remainingTape);
    //        var currentShowing = $$('div.detailsImageThumbsContainer div.swatchShowing');
    //        if(currentShowing[0].previous()){
    //            currentShowing[0].previous().removeClassName('displayNone');
    //            currentShowing[0].previous().addClassName('swatchShowing');
                new Effect.Move($('productDetailsSwatchImagesContainerId'), { x: shiftDistance, transition: Effect.Transitions.sinoidal});
    //            currentShowing[currentShowing.size() - 1].addClassName('displayNone');
    //            currentShowing[currentShowing.size() - 1].removeClassName('swatchShowing');
    //        }
        }
        e.stop();
    },
    checkeGiftCardBalance : function(e, c){
        var eGiftCardBalanceResult;
        var url = 'giftCardBalancePage.mtw?' + $('eGiftCardBalanceForm').serialize();
        $('eGiftBalanceCheckMessageContainer').update('');
        new Ajax.Request(url, {
            onComplete: function(transport) {
                eGiftCardBalanceResult = transport.responseJSON;
                if(eGiftCardBalanceResult['success'] && $('currentAvailableBalanceField')){
                    $('currentAvailableBalanceField').update(eGiftCardBalanceResult['balance']);
                }
                else{
                    if($('eGiftBalanceCheckMessageContainer')){
                        var messageContent = '';
                        for(var n = 0; n < eGiftCardBalanceResult['messages'].length ; n++){
                            messageContent = messageContent + "<div  class=\"errorMessage padding5px\">" + eGiftCardBalanceResult['messages'][n] + "</div>";
                        }
                        $('eGiftBalanceCheckMessageContainer').update(messageContent);
                    }
                }
            }
        });
    },
    printPage : function(e, c){
        window.print();
        Event.stop(e);
        return false;



//        e.stop();
    }
};

var classNamesJSONObj = {
    "domReady_test1":domReadyEventFunctionsCollections.doTest1,
    "domReady_test2_keypress":domReadyEventFunctionsCollections.doTest2,
    "domReady_estimateShipCost":domReadyEventFunctionsCollections.doEstimateShipCost,
    "domReady_signatureReqSync":domReadyEventFunctionsCollections.doSignatureReqSync,
    "domReady_updateTotal":domReadyEventFunctionsCollections.doUpdateTotal,
    "domReady_requestGiftCardBalance":domReadyEventFunctionsCollections.requestGiftCardBalance,
    "domReady_billAddrCreateVip":domReadyEventFunctionsCollections.billAddrCreateVip,
    "domReady_confirmPrint":domReadyEventFunctionsCollections.confirmPrint,
    "domReady_reviewPrint":domReadyEventFunctionsCollections.reviewPrint,
    "domReady_productDetailsTabs":domReadyEventFunctionsCollections.changeTab,
    "domReady_swatchImageLeft":domReadyEventFunctionsCollections.swatchSlideRight,
    "domReady_swatchImageRight":domReadyEventFunctionsCollections.swatchSlideLeft,
    "domReady_giftCardEmailSaveAjax":domReadyEventFunctionsCollections.giftCardEmailSaveAjax,
    "domReady_checkeGiftCardBalance":domReadyEventFunctionsCollections.checkeGiftCardBalance,
    "domReady_printPageButton": domReadyEventFunctionsCollections.printPage
};

document.observe("dom:loaded", function() {
    var obj = $("main_table");
    Event.observe(obj, 'click', domReadyListener.handler.bindAsEventListener());
    Event.observe(obj, 'keypress', domReadyListener.handler.bindAsEventListener());

    /** other event binding ... **/
    var bsMyAddressObjs = $$(".bs_Addrselector");
    if (bsMyAddressObjs) {
        bsMyAddressObjs.each(function(o) {
            Event.observe(o, 'change', domReadyEventFunctionsCollections.doSwitchAddress);
        })
    }

    var bsShipMethodObj = $("bs_shipMethod");
    if (bsShipMethodObj) {
        Event.observe(bsShipMethodObj, 'change', domReadyEventFunctionsCollections.doEstimateShipCost);
    }

/*
    var billAddrCreateVip = $("billAddrCreateVip");
    if(billAddrCreateVip){
        Event.observe(billAddrCreateVip, '', domReadyEventFunctionsCollections.doBillAddrCreateVip);
    }
*/

    // function need to run after dom loaded
    if (document.selection) {
        ieDelay = setTimeout("domReadyInitFunctionsCollections.go()", 50);
    } else {
        domReadyInitFunctionsCollections.go();
    }

    //add Event.observe below for any events you like to bind to specific element except $("main_table").------------------------------

});
document.observe("dom:loaded", function() {
    $$('body')[0].observe('click', function(event) {
        if(event.element().tagName == 'A' && event.element().up().hasClassName('pr-snippet-read-reviews')){
            readReview(event);
        }
    })
});
var novatorUtil = {
    // same as prototype clonePostion when IE 7 have problem use prototype clonePosition use this one
    /*
        parameters:
            elm: element to be positioned.
            source: the element whose position will be take as reference
            isCovert: if set to true, then elm's height and width will be 4 px larger than the reference.
                      This is used to make elm cover source element so source element will not be clickable
     */
    clonePosition : function(elm, source, overSize){
        var sourceOffset = source.cumulativeOffset();
        $(elm).absolutize();
        $(elm).style.left = sourceOffset.left - overSize + 'px';
        $(elm).style.top = sourceOffset.top - overSize + 'px';
        $(elm).style.width = source.getWidth() + overSize * 2 + 'px';
        $(elm).style.height = source.getHeight() + overSize * 2  + 'px';
    }
}
var previousClickedSubmit;
var domReadyListener = {
    handler: function(e) {
        var currentElement = e.element();
        // check if a submit button is clicked and if it is not a multiClickSubmitButtonId then disable it
        if(currentElement.tagName == 'INPUT'
                && currentElement.readAttribute('type') == 'submit'
                && !currentElement.hasClassName('multiClickSubmitButtonId')
                && (e.charCode == 13 || e.keyCode == 13 || e.charCode == undefined || e.keyCode == undefined)){
            var overSize = 0;
            if(currentElement.up().hasClassName('buttonBodyWrapper')){
                overSize = 6;
            }
            novatorUtil.clonePosition($('disabledButtonCoverLayer'), currentElement, overSize);
        }
/*
    // alternate way to get binded events which will fix the problem when even is fire on a element inside a binded element
    // keep it here in case the original have problem in the future.

        var domReadyFunctionClassName = getDomReadyBinded(currentElement);
        if(domReadyFunctionClassName != undefined){
            if (domReadyFunctionClassName.include("_keypress")) {// if class name include _keypress, do function only when key pressed
                if (e.charCode || e.keyCode) {
                    classNamesJSONObj[domReadyFunctionClassName](e, domReadyFunctionClassName);
                }
            } else if(e.type=="click"){
                classNamesJSONObj[domReadyFunctionClassName](e, domReadyFunctionClassName);
            }
        }
*/


        if (currentElement.classNames().size() > 0) {
            currentElement.classNames().each(function(c) {
                if (c.include("domReady_")) {
                    if (c.include("_keypress")) {// if class name include _keypress, do function only when key pressed
                        if (e.charCode || e.keyCode) {
                            classNamesJSONObj[c](e, c);
                        }
                    } else if(e.type=="click"){
                        classNamesJSONObj[c](e, c);
                    }
                }
            })
        }
    }
};
function getDomReadyBinded(el){
    var domReadyClassName = el.classNames().find(function(className){
        return className.include("domReady_");
    });
    if(domReadyClassName != undefined){
        return domReadyClassName;
    }
    else{
        if(el.up() != undefined && el.up().tagName.capitalize() != "Html"){
            return getDomReadyBinded(el.up());
        }
        else{
            return undefined;
        }
    }
}
var util = {
    formSubmit: function(formName, suffix) {
        if (suffix != null && suffix.length > 0) {
            document.forms[formName].action = suffix;
        }
        document.forms[formName].submit();
    }
}

    // ---- end for shopping cart and checkout pages --- //
// ajax functions for lightbox
var lightBoxAjaxFunctions = {
    'addToCartAjax' : function (eventNode, popupLayer){
        var url;
        if(eventNode.tagName == 'INPUT'){
            // this is a add to cart submit button
            var params = $(eventNode.form).serialize()
            url = 'addToCart.mtw?ajax=true&' + params;
        }
        else{
            // this is a add to cart link
            url = eventNode.href + '&ajax=true';
            eventNode.up(2).insert(popupLayer.remove(), 'before');
        }
        var layerMessageNode = popupLayer.getElementsBySelector('div.addToCartSucesssMessage')[0];
//        layerMessageNode.update('');
        popupLayer.getElementsBySelector('div.addToCartAjaxLoading')[0].removeClassName('displayNone');
        popupLayer.getElementsBySelector('div.addToCartPopuplayerButtons')[0].addClassName('displayNone');
        popupLayer.getElementsBySelector('div.addToCartSucesssMessage')[0].addClassName('displayNone');

        popupLayer.removeClassName('positionRight');
        popupLayer.removeClassName('positionLeft200px');
        if(eventNode.up().up().readAttribute('data_set')){
            popupLayer.addClassName(eventNode.up().up().readAttribute('data_set'));
        }
        lightBox.showLayer(popupLayer);
        lightBox.positionOverlay();
        new Ajax.Request(url, {
          method: 'post',
          onSuccess: function(transport) {
              var jsonObjectValue = transport.responseJSON;
              popupLayer.getElementsBySelector('div.addToCartAjaxLoading')[0].addClassName('displayNone');
              layerMessageNode.removeClassName('displayNone');
              updateAddToCartMessage(layerMessageNode,jsonObjectValue);
              popupLayer.getElementsBySelector('div.addToCartSucesssMessage')[0].removeClassName('displayNone');
              lightBox.positionOverlay();
          }
        });
    },
    'addToWishListAjax' : function(eventNode, popupLayer){
        var url;
        // this is a add to cart submit button
        var params = $(eventNode.form).serialize()
        url = 'addProductToWishList.mtw?ajax=true&' + params;
        var layerMessageNode = popupLayer.getElementsBySelector('div.addToWishListSucesssMessage')[0];
//        layerMessageNode.update('');
        popupLayer.getElementsBySelector('div.wishListAjaxLoading')[0].removeClassName('displayNone');
        popupLayer.getElementsBySelector('div.addToWishListPopuplayerButtons')[0].addClassName('displayNone');
        popupLayer.getElementsBySelector('div.addToWishListSucesssMessage')[0].addClassName('displayNone');
        lightBox.showLayer(popupLayer);
        lightBox.positionOverlay();
        new Ajax.Request(url, {
          method: 'post',
          onSuccess: function(transport) {
              var jsonObjectValue = transport.responseJSON;
//              Mock json respond
//              var jsonObjectValue = {
//                                        "numWishListItems":3,
//                                        "addToWishListSuccess":true,
//                                        "productPrettyName":"\"Born Cool\" Gray Plaid Hoodie - Testing > Extra Small"
//                                    };
              popupLayer.getElementsBySelector('div.wishListAjaxLoading')[0].addClassName('displayNone');
              layerMessageNode.removeClassName('displayNone');
              updateAddToWishListMessage(layerMessageNode,jsonObjectValue);
              popupLayer.getElementsBySelector('div.addToWishListSucesssMessage')[0].removeClassName('displayNone');
              lightBox.positionOverlay();
          }
        });
    },
   'reorderProductAjax' : function (eventNode, popupLayer){
        eventNode.up(2).insert(popupLayer.remove(), 'before');
        popupLayer.getElementsBySelector('div.orderHistorySuccess')[0].addClassName('displayNone');
        popupLayer.getElementsBySelector('div.orderHistoryAjaxLoading')[0].removeClassName('displayNone');
        lightBox.showLayer(popupLayer);

        var errorFlag = false;

        new Ajax.Request(eventNode.readAttribute('href'), {
            onSuccess: function(transport) {
                var jsonObj = transport.responseJSON;
                if (!jsonObj.orderHistoryReorder){
                    popupLayer.getElementsBySelector('div.orderHistorySuccess')[0].addClassName('displayNone');
                    popupLayer.getElementsBySelector('div.orderHistoryFail')[0].removeClassName('displayNone');
                }
                else {
                    popupLayer.getElementsBySelector('div.orderHistoryFail')[0].addClassName('displayNone');
                    popupLayer.getElementsBySelector('div.orderHistorySuccess')[0].removeClassName('displayNone');
                    $('scQtyId').innerHTML = jsonObj.numShopCartItems;
                }
                popupLayer.getElementsBySelector('div.orderHistoryAjaxLoading')[0].addClassName('displayNone');
                lightBox.positionOverlay();
            }
        });
    }
}

function updateAddToWishListMessage(layerMessageNode,ajaxResponse){
    if($$('div.addToWishListPopuplayerButtons')[0]){
        $$('div.addToWishListPopuplayerButtons')[0].removeClassName('displayNone');
    }

    $$('div.addToWishListSuccessPopuplayer').each(function (el){
        el.removeClassName('displayNone');
    });

    $$('div.addToWishListLoginRequiredPopuplayer').each(function (el){
        el.addClassName('displayNone');
    });
    layerMessageNode.select('div.errorMessageContainer')[0].update('');
    if(ajaxResponse.addToWishListSuccess){
        $$('fieldset.addToWishListSuccessMessage').each(function(addToWishListSuccessMessage){
            addToWishListSuccessMessage.removeClassName('displayNone');
        });
        $$('div.addToWishListPopuplayerButtons').each(function(el){
            el.removeClassName('displayNone');
        });
        $$('h4.addToWishListSuccessHeader').each(function (successHeader){
            successHeader.removeClassName('displayNone');
        });
        /* Error container might still show if previously shown with errors, would need to clearn and hide */
        layerMessageNode.select('div.errorMessageContainer')[0].update('').hide();
        $("modalWishListSuccessMessage").update(ajaxResponse.productPrettyName);
        $("modalTotalWishListItems").update(ajaxResponse.numWishListItems);
        $$('#wlQtyId').each(function(wlQtyId){
            wlQtyId.update(ajaxResponse.numWishListItems);
        });
    }
    else if(ajaxResponse.addToWishListErrors && ajaxResponse.addToWishListErrors.size() > 0){
        // add to wish list got error
        $("errorMessageContainer").show().insert({top: new Element('ul',{className:"errorMessage"})});
        ajaxResponse.addToWishListErrors.each(function(errorMessageObject){
            $("errorMessageContainer").firstDescendant().insert({
                top: new Element('li').update(errorMessageObject.errorMessage)
            });
        });
    }
    else{
        // user need to login
        $$('div.addToWishListLoginRequiredPopuplayer').each(function (el){
            el.removeClassName('displayNone');
        });
        $$('div.addToWishListSuccessPopuplayer').each(function (el){
            el.addClassName('displayNone');
        });
    }
}
function updateAddToCartMessage(layerMessageNode,ajaxResponse){
    if($$('div.addToCartPopuplayerButtons')[0]){
        $$('div.addToCartPopuplayerButtons')[0].removeClassName('displayNone');
    }
    $("errorMessageContainer").update('');
    if(!ajaxResponse.addToCartSuccess){
        $$('fieldset.addToCartSuccessMessage').each(function(addToCartSuccessMessage){
            addToCartSuccessMessage.hide();
        });
        if($('addToCartPopupLayerViewCartButton')){
            $('addToCartPopupLayerViewCartButton').hide();
        }
        $$('h4.addToCartSuccessHeader').each(function (successHeader){
            successHeader.addClassName('displayNone');
        });
        /* Verified if object exists */
        if(ajaxResponse.addToCartErrors != null){
            /* Semantic : If only one error, generate <P> tag, else, generate a <UL> list */
            if(ajaxResponse.addToCartErrors.length == 1){
                ajaxResponse.addToCartErrors.each(function(errorMessageObject){
                    $("errorMessageContainer").show().insert({
                        top: new Element('div',{className:"errorMessage"}).update(errorMessageObject.errorMessage)
                    });
                });
            }else{
                $("errorMessageContainer").show().insert({top: new Element('ul',{className:"errorMessage"})});
                ajaxResponse.addToCartErrors.each(function(errorMessageObject){
                    $("errorMessageContainer").firstDescendant().insert({
                        top: new Element('li').update(errorMessageObject.errorMessage)
                    });
                });
            }
        }
    }else{

        $$('fieldset.addToCartSuccessMessage').each(function(addToCartSuccessMessage){
            addToCartSuccessMessage.show();
        });
        if($('addToCartPopupLayerViewCartButton')){
            $('addToCartPopupLayerViewCartButton').show();
        }
        $$('h4.addToCartSuccessHeader').each(function (successHeader){
            successHeader.removeClassName('displayNone');
        });
        /* Error container might still show if previously shown with errors, would need to clearn and hide */
        $("errorMessageContainer").update("").hide();
        $("modalCartSuccessMessage").update(ajaxResponse.productPrettyName);
        $("modalTotalCartItems").update(ajaxResponse.numShopCartItems);
        $$('#scQtyId').each(function(scQtyId){
            scQtyId.update(ajaxResponse.numShopCartItems);
        });
    }
    //omniture - updating values
    var omnitureValuesObj = ajaxResponse.omnitureValues;
    for(var x = 0 ; x < omnitureValuesObj.length ; x++){
        eval("s." + omnitureValuesObj[x].key + "= '" + omnitureValuesObj[x].value + "'");
    }
    s_code=s.t();if(s_code)document.write(s_code);
}
//--------------------------------------light box-------------------------------------------//
/* lightbox */
/*
    How to use:
    1. All elements to show the layer must contain class "lightboxOpener"
    2. The lightboxOpener must have attribute "rel" with value of the popup layers's id
    3. All elements to hide the layer must contain class "lightboxCloser"
    4. The following css wil required:
        .leightbox {
            color: #333;
            display: none;
            position: absolute;
            background-color: white;
            z-index:1001;
            overflow: auto;
        }

        div.lightboxOverlay{
            position:absolute;
            z-index:1000;
            background-color:#333;
        }

    5. To initiallize: Call lightBox.init(refNode, opacity) to make current page lightbox capatiable.
        refNode: is the node where the overlay layer tobe inserted it can be any node in the page. If the popuplayer is
                under the overlay layer simply change it to use another node.
        opacity: The opacity of the overlay layer
        lightBoxEffect: flag for use effect on popup or not, lightBox need to be hide by css class "displayNone"
        overlayEffect: flag for use effect on overlay layer or not

    6. Ajax support: ajax function name must be combined in lightboxOpener's ref attributes as "_lightBoxAjax..._functionName"
        and the ajax function will have one paramter which is the lightboxOpener being clicked and another which is the
        popup layer node. lightBox.showLayer(popUpLayer need to be the ajax call back function).

 */

var lightBox = {
    inited : false,
    opacity : 0.5,
    lightBoxEffect : true,
    overlayEffect : true,
    init : function(refNode, opacity){
        if(!lightBox.inited){
            this.opacity = opacity;
            this.createOverlay(refNode, opacity);
            this.attachOpenEvents();
            this.attachCloseEvents();
            Event.observe(document.onresize ? document : window, "resize", this.positionOverlay);
            lightBox.inited = true;
        }
    },
    createOverlay : function(refNode, opacity){
        //var overlay = new Element('div', { class: 'lightboxOverlay' });// doesn't work for IE8
        var overlay = new Element('div');
        overlay.addClassName('lightboxOverlay');
        $(refNode).insert(overlay, 'after');
        overlay.setOpacity(opacity);
        lightBox.positionOverlay();
        $$('div.lightboxOverlay')[0].hide();
    },
    positionOverlay : function(){
        if($$('div.lightboxOverlay')[0]){
            $$('div.lightboxOverlay')[0].clonePosition($$('body')[0]);
        }
    },
    attachOpenEvents : function(){
        $$('.lightboxOpener').each(function (lightboxOpener){
                lightboxOpener.observe('click',function(e){
                    var layerNode = $(this.readAttribute('rel'));
                    // add ajax support
                    var ajaxFunction = this.readAttribute('rel').split('_lightBoxAjax_')[1];
                    if(typeof lightBoxAjaxFunctions[ajaxFunction] == 'function'){
                        // if this is an ajax function
                        lightBoxAjaxFunctions[ajaxFunction](this, layerNode);
                    }
                    else{
                        // if this is not an ajax function
                        lightBox.showLayer(layerNode);
                    }
                e.stop();
            });
        });
    },
    showLayer: function(layerNode){
//        layerNode.getElementsByTagName('a')[0].visibility = "visible";
//        layerNode.getElementsByTagName('a')[0].focus();
        this.positionOverlay();
        $$('div.lightboxOverlay').each(function(overlay){
            if(lightBox.overlayEffect){
                overlay.appear({ duration: 0.5, to :  lightBox.opacity});
            }
            else{
                overlay.show();
            }
        });
        layerNode.hide();
        layerNode.removeClassName('displayNone');
        if(lightBox.lightBoxEffect){
            layerNode.absolutize().appear({ duration: 0.0 });// keep as 0.0 otherwise we can't move the focus to anchor tag (see below)
        }
        else{
            layerNode.absolutize().show();
        }
        // next line is to allow the focus to move to the anchor tag
        layerNode.style.display = "block";
        layerNode.getElementsByTagName('a')[0].focus();
    },
    centreLayer : function(layerNode, top){
        layerNode.absolutize().style.left = Math.ceil($$('body')[0].getDimensions().width / 2 - layerNode.getDimensions().width) + 'px';
        layerNode.style.top = top + 'px';
    },
    attachCloseEvents : function(){
        $$('.lightboxCloser').each(function (lightboxCloser){
            lightboxCloser.observe('click', function(e){
                // find the closest ancestor which is the light box and hide it
                if(lightBox.lightBoxEffect){
                    (this.ancestors().find(function (ancestor){
                        return ancestor.hasClassName('lightbox');
                    })).fade({ duration: 0.5 });
                }
                else{
                    this.ancestors().find(function (ancestor){
                        return ancestor.hasClassName('lightbox');
                    }).style.display =  'none';
                }
                if(lightBox.overlayEffect){
                    $$('div.lightboxOverlay').each(function (overlay){
                        overlay.fade({ duration: 0.5 });
                    });
                }
                else{
                    $$('div.lightboxOverlay').each(function (overlay){
                        overlay.hide();
                    });
                }
                e.stop();
            });
        });
    }
};
/* add this variables */
var addthis_config = {
//    ui_cobrand: "BigAls",
    ui_header_color:"#000000",
    ui_header_background:"#eeeeee",
    services_compact: 'facebook, myspace, google, twitter, more'
}

/*Start initC4MyOrderHistoryFDT init*/

    /*end initC4MyOrderHistoryFDT init*/





function searchOrders(event){
    $('searchOrderForm').action = "viewOrderHistory.mtw";
    $('searchOrderForm').submit();
}

function orderHistoryFDTPaginationAjax(event) {
    var url = this.readAttribute('href') + "&fromDate=" + $('fromDateCal_display').value + "&toDate=" + $('toDateCal_display').value + "&itemsPerPage=" + $("itemsPerPageOrderHistory").value;

    if (this.readAttribute('id') == "itemsPerPageOrderHistory") {
        url = "viewOrderHistory.mtw?fromDate=" + $('fromDateCal_display').value + "&toDate=" + $('toDateCal_display').value + "&itemsPerPage=" + $("itemsPerPageOrderHistory").value;
    }
    $('orderHistoryForm').action = url;
    $('orderHistoryForm').submit();
    event.stop();
}
function viewOrderHistoryDetailsAjax(event) {
    if($('viewOrder' + this.readAttribute('orderNumber'))){
        if(this.readAttribute('action') == 'view'){
            $('viewOrder' + this.readAttribute('orderNumber')).className = "displayNone";
            $('order' + this.readAttribute('orderNumber') + 'Details').className = "details";
            $('hideOrder' + this.readAttribute('orderNumber')).className = "";
        }
        else{
            $('hideOrder' + this.readAttribute('orderNumber')).className = "displayNone";
            $('order' + this.readAttribute('orderNumber') + 'Details').className = "details displayNone";
            $('viewOrder' + this.readAttribute('orderNumber')).className = "";
        }
        event.stop();
    }
}
//---------END C4MyOrderHistoryFDT----------------------//
