/*
LIV
 */



// NOT GENERAL ON PURPOSE. Think hard before opening this to whatever random URL is in the request,
// or moving this later in the page life cycle.
(function() {

    var redirect_param = location.search.match(/[&?]go_to_page=(\w+)/);

    if(redirect_param) {

        var destination = {
            BILLING_ADDRESS : "/store/myaccount.html?mode=billingaddress",
            PURCHASE_HISTORY : "/store/myaccount.html?mode=vieworder",
            SHIPPING_ADDRESS : "/store/myaccount.html?mode=shippingaddress",
            GIFT_CERTIFICATES : "/store/myaccount.html?mode=giftcertcodes"
        }
        [redirect_param[1]];

        if(destination) {
            location.href = location.protocol + "//" + location.host + destination;
        }
    }
})()
function load_external_js(jsfilename){
    var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript= document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src=jsfilename;
    oHead.appendChild(oScript);
}

function guess_go_to_page(url) {

    var ret = undefined;
    var mode_param = url.match(/(^|\/)myaccount.html.*[?&]mode=(\w+)/);

    if(mode_param) {
        var account_destination = {

            billingaddress     : 'BILLING_ADDRESS',
            vieworder          : 'PURCHASE_HISTORY',
            shippingaddress : 'SHIPPING_ADDRESS',
            giftcertcodes      : 'GIFT_CERTIFICATE'

        }
        [ mode_param[2] ];

        ret = account_destination;
    }

    return ret;

}

if (typeof resHash == "undefined") {
    load_external_js('/scripts/resources.js');
}
var userName = 'Benjamin';
ldmode = false;


// flag to indicate if search tray can animate
var searchIsFree = true;


function scanFields(){
    allforms = $$('.sform input');
    allforms.each(function(item){
        Element.extend(item);
        Event.observe(item, 'click', function(){
            this.select();
        });
		
	
    });

}



// form controls
function focuser(){
    this.addClassName('active');
    if(this.getValue() == this.defaulter){	
			
				
			
        this.value = '';
        this.addClassName('exists');
        if(this.ftype == 'password'){
            setType(this, 'password', true);	
        }
				
				
    }
}

function blurer(){
    this.removeClassName('active');
    if(this.getValue() == ''){
				
        this.value = this.defaulter;
        this.removeClassName('exists');
				
        if(this.ftype == 'password'){
            setType(this, 'text', false);	
        }
    }	
}

function setType(item, typer, act){
    var input=item;
    //var input2= input.cloneNode(false);
			
    var input2 = document.createElement('input');
    Element.extend(input2);
    input2.autoselect = item.autoselect;
			
    input2.setAttribute('name', input.name);
    input2.setAttribute('type', typer);
    input2.setAttribute('value', input.value);
    input2.onfocus = focuser;
    input2.onblur = blurer;
    input2.ftype = item.ftype;
    input2.defaulter = item.defaulter;
			
    item.onblur = function() { };
    item.blur();
    item.parentNode.replaceChild(input2,item);
			
    if(!act){
        input2.removeClassName('exists');
    } else{
        input2.activate();
        input2.addClassName('exists');
    }

}


function setModalDefaults() {
    var formses = $$('.inputform input');
	
    for(i = 0; i<values.length; i++){
        formses[i].value = values[i];
    };
    formses[0].activate();

    formses.each(function(item){
        item.blur();
        item.defaulter = item.value;
        item.ftype = item.type;
        if(item.ftype =='password'){
            setType(item, 'text', false);
        }
		
        item.onfocus = focuser;
        item.onblur = blurer;
    });
	
    if($('loginContainer')) {
        form = $$('#loginContainer form')[0]
    } else if($('accountContainer')) {
        form = $$('#accountContainer form')[0]
    } else if($('forgotContainer')) {
        form = $$('#forgotContainer form')[0]
    }
	
	
    if(typeof inStore != "undefined" && inStore) {
        var newField = document.createElement('input');
        Element.extend(newField);
		
        newField.setAttribute('name', 'insideStore');
        newField.setAttribute('type', 'hidden');
        newField.setAttribute('value', 'true');
		
        form.appendChild(newField);
    }
    protectLogin();
}




function loginModalSuccess() {
    // don't just reload the page, it'll ask if you want to resubmit the form
	
    if(arguments.length > 0) {
        token = arguments[0];
    } else {
        token = "";
    }

    currentURL = location.href;
	
    if(urlAfterLogin) {
        currentURL = urlAfterLogin;
        urlAfterLogin = null;
    }

    // remove hash
    hashIndex = currentURL.indexOf("#");
    if(hashIndex != -1) {
        hashString = currentURL.substr(hashIndex);
        currentURL = currentURL.substr(0, hashIndex);
    } else {
        hashString = "";
    }
	
    // if the login redirects to a specific page, go ahead to that page
    if(typeof inStore != "undefined" && inStore) {
        pagesThatDontAcceptToken = ['/signin.html', '/asearch.html', '/advancedsearch.html', '/myaccount.html' ];
        matchURL = currentURL.toLowerCase();
        var exit = false;
        $A(pagesThatDontAcceptToken).each(function(page) {
            if(matchURL.indexOf(page) > 0) {
                location.href = "/store/store.html";
                exit = true;
                return;
            }
        });
        if(exit) return;
    }
	
    // append lg
    qstnIndex = currentURL.indexOf("?");
    if(token) {
        if(qstnIndex != -1) currentURL = currentURL + "&lg=" + token;
        else currentURL = currentURL + "?lg=" + token;
    } else {
        if(qstnIndex != -1) currentURL = currentURL + "&loggedIn=1";
        else currentURL = currentURL + "?loggedIn=1";
    }
	
    if(hashString) currentURL += hashString;
	
    location.href = currentURL;
}

function setOrderDefaults() {
    setFormDefaults('orderForm');
}

function setFormDefaults(formId) {
    $(formId).getElements().each(function(item) {
        if (formDefaults[item.name] != null) {
            item.value = formDefaults[item.name];
        }
        item.blur();
    });
}

function updateField(elem) {
    if (elem.value == formDefaults[elem.name]) {
        elem.value = '';
    }
    elem.removeClassName('error');
}

function updatePwdField(elem) {
    if (elem.value == formDefaults[elem.name]) {
        elem.value = '';
        elem.type = 'password';
    }
}

function resetPwdField(elem) {
    if (elem.value == '') {
        elem.value = formDefaults[elem.name];
        elem.type = 'text';
    }
    elem.removeClassName('error');
}

// Modalbox functions
urlAfterLogin = null;


function addParameters(search_root, params) {
    var newparam_clauses = []
    for(pk in params) {
        var newclause = encodeURIComponent(pk) + "=" + encodeURIComponent(params[pk]);
        newparam_clauses.push(newclause)
    }

    var newparams = newparam_clauses.join("&");

    if(newparams) {
        if(search_root) {
            newparams = search_root + "&" + newparams;
        }
        else {
            newparams = "?" + newparams;
        }
    }

    return newparams;
}


/*******
  Takes an optional argument, andThen_go_to, which controls redirect
  behavior after successful login. The argument is interrogated in this order

  1) { href: a url }, - go to the indicated url
  2) { go_to_page : one of "BILLING_ADDRESS", "GIFT_CERTIFICATES", etc,
       via: url to use as an intermediate step before go_to_page. Defaults to the current window.location }
         - go to the specified page via the 'go_to_page' param (see
	       the top of this file for known values.) If given, use the url in via to get there.
  3) { preserve_state: true }
         - leave redirect state unchanged (if earlier calls set a redirect,
	   keep it, otherwise don't set anything else)
  4) { from_url: a url parameter name }, 
         - go to the URL indicated with the value of the given parameter name, associated with the CURRENT url
  4) Undefined/not provided - no redirect, remove any current redirect.

 ***********/
function showLogin(andThen_go_to) {

    var old_state = urlAfterLogin;
    urlAfterLogin = false;

    if(andThen_go_to) {

        if("undefined" != typeof andThen_go_to["href"]) {
            urlAfterLogin = andThen_go_to.href;
        }
        else if("undefined" != typeof andThen_go_to["go_to_page"]) {
            var via = window.location.toString();

            if("undefined" != typeof andThen_go_to["via"]) {
                via = andThen_go_to["via"];
            }

            var destination = via;
            if(destination.indexOf('?') < 0) {
                destination = destination + '?';
            }
            else {
                destination = destination + '&';
            }
            
            destination = destination + 'go_to_page=' + andThen_go_to.go_to_page;

            urlAfterLogin = destination;
        }
        else if( ("undefined" != typeof andThen_go_to["preserve_state"]) &&
            andThen_go_to.preserve_state) {
            urlAfterLogin = old_state;
        }

    }

    Modalbox.show(userLoginDA, {
        title: resHash['Log In'],
        width: resHash['Log In width'],
        afterLoad: setModalDefaults
    });
}

function showSignup() {
    Modalbox.show(newAccountDA, {
        title: resHash['Sign Up'], 
        width: resHash['Sign Up width'], 
        afterLoad: setModalDefaults
    });
}

function showForgotPwd() {
    Modalbox.show(forgotPassDA, {
        title: resHash['Forgot Password'], 
        width: resHash['Forgot Password width'], 
        afterLoad: setModalDefaults
    });
}

//--------------------------------------------------------
// Tray functions

// toggle search/username tray
function toggleTray() {
    if (searchIsFree) {
        searchIsFree = false;

        if ($('searchForm') != null) {
            var wrapperH = $('utray_wrapper').getHeight();
            new Effect.MoveBy('utray_wrapper', -(wrapperH), 0, {
                duration: .5, 
                afterFinish: showUser
            }); 
        }
        else if ($('pillUsername') != null) {
            var wrapperH = $('utray_wrapper').getHeight();
            new Effect.MoveBy('utray_wrapper', -(wrapperH), 0, {
                duration: .5, 
                afterFinish: showSearch
            });
        }
        else {
            showSearch();
        }
    }
}

function showSearch() {
    // set utray contents and move up to hide
    var utray = $('utray');
    utray.innerHTML = $('searchCache').innerHTML;
    $('utray_wrapper').style.top = '-1000px';

    // get slide distance and set ids
    var wrapperH = $('utray_wrapper').getHeight();           
    var searchForm = utray.select('.searchForm')[0];          
    var results = utray.select('.results_container')[0];
    searchForm.id = 'searchForm';
    results.id = 'searchResults';

    $('utray_wrapper').style.display = 'block';
    $('utray_wrapper').style.top = -(wrapperH) + 'px';

    new Effect.MoveBy('utray_wrapper', wrapperH, 0, {
        duration: .5, 
        afterFinish: function(effect) {
            searchIsFree = true;
        }
    });
}

function showUser() {
    if (userName != '') {
        var utray = $('utray');
        utray.innerHTML = $('usernameCache').innerHTML;
        $('utray_wrapper').style.top = '-1000px';

        var wrapperH = $('utray_wrapper').getHeight();
        var userElem = $$('.traycontent')[0];
        userElem.id = 'pillUsername';
        userElem.innerHTML = userName;

        $('utray_wrapper').style.top = -(wrapperH) + 'px';

        new Effect.MoveBy('utray_wrapper', wrapperH, 0, {
            duration: .5, 
            afterFinish: function(effect) {
                searchIsFree = true;
            }
        });
    }
    else {
        searchIsFree = true;
        $('utray').innerHTML = '';
    }
}

// cart tab show/hide functions
function showCartTab(cartVal) {       
    $('items').innerHTML = cartVal;
    var cartH = $('ucart_wrapper').getHeight();
    $('ucart_wrapper').style.top = cartH + 'px';
    
    new Effect.MoveBy('ucart_wrapper', -(cartH), 0, {
        duration: .5
    });
}

function hideCartTab() {
    var cartH = $('ucart_wrapper').getHeight();
    $('ucart_wrapper').style.top = '0px';
    new Effect.MoveBy('ucart_wrapper', cartH, 0, {
        duration: .5
    });
}

//--------------------------------------------------------


//--------------------------------------------------------
// Product viewer

// grow image test
var imageAnimating = false;

function growImage() {
    if(imageAnimating) return;
    imageAnimating = true;
    var srcImg = $$('div#imgBrwsThumbs img')[imgScroll.currImg];
    var closeX = $$('div.imgBrws img.close')[0];
    var elem = $('imgBrwsGrowWin');
    var node = Builder.node('img', {
        src: srcImg['src'], 
        height: srcImg.getHeight(), 
        width: srcImg.getWidth()
    });

    srcImg.onRelease = null;

    elem.innerHTML = '';
    elem.appendChild(node);
    Element.setOpacity(elem, 0);
    elem.show();

    new Effect.Parallel([ new Effect.Scale(node, 300, {
        sync: true, 
        scaleFrom: 100.0
    }),
    new Effect.Opacity(elem, {
        sync: true, 
        from: 0, 
        to: 1.0
    }),
    new Effect.Opacity(node, {
        sync: true, 
        from: 0, 
        to: 1.0
    }),
    new Effect.Appear(closeX, {
        sync: true
    }) ],
    {
        duration: .7, 
        afterFinish: function(effect) { 
            $('imgBrwsGrowWin').onmouseup = shrinkImage; 
            $(closeX).onmouseup = shrinkImage;
            imageAnimating = false;
        }
    });				
}


function shrinkImage() {
    if(imageAnimating) return;
    imageAnimating = true;
    var elem = $('imgBrwsGrowWin');
    var closeX = $$('div.imgBrws img.close')[0];
    var node = elem.childElements()[0];
 
    elem.onmouseup = null;
    closeX.onmouseup = null;

    new Effect.Parallel([ new Effect.Scale(node, 33, {
        sync: true
    }),
    new Effect.Opacity(elem, {
        sync: true, 
        from: 1.0, 
        to: 0
    }),
    new Effect.Opacity(node, {
        sync: true, 
        from: 1.0, 
        to: 0
    }),
    new Effect.Fade(closeX, {
        sync: true
    }) ],
    {
        duration: .7, 
        afterFinish: function(effect) {
            $('imgBrwsGrowWin').hide();
            imageAnimating = false;
        }
    });
}

function initScrollButtons() {
    if (imgScroll.currImg > 0) {
        $('imgBrwsBtn_lft').removeClassName('disabled');
        $('imgBrwsBtn_lft').onmouseup = prevImage;	
    }
    else {
        $('imgBrwsBtn_lft').addClassName('disabled');
        $('imgBrwsBtn_lft').onmouseup = null;
    }

    if (imgScroll.currImg < (imgScroll.imgSetLength-1)) {
        $('imgBrwsBtn_rt').removeClassName('disabled');
        $('imgBrwsBtn_rt').onmouseup = nextImage;
    }
    else {
        $('imgBrwsBtn_rt').addClassName('disabled');
        $('imgBrwsBtn_rt').onmouseup = null;
    }

    $('imgGrowBtn').onmouseup = growImage;
    $$('div#imgBrwsThumbs img')[imgScroll.currImg].onmouseup = growImage;
}

function prevImage() {
    clearScrollButtons();
    imgScroll.goBack();
}

function nextImage() {
    clearScrollButtons();
    imgScroll.goNext();
}

function clearScrollButtons() {
    $('imgBrwsBtn_lft').onmouseup = null;
    $('imgBrwsBtn_rt').onmouseup = null;
    $('imgGrowBtn').onmouseup = null;
    $$('div#imgBrwsThumbs img')[imgScroll.currImg].onmouseup = null;

}


//--------------------------------------------------------


//--------------------------------------------------------
// Tabs

function showProductTab(tab, num) {
    $$('div.tabContent').each( function(item) {
        item.hide();	   
    });
    $$('div.tabs div.tab').each( function(item) {
        item.removeClassName('selected');
    });
   
    $$('div.tabContent')[num].show();
    $(tab).addClassName('selected');
}

//--------------------------------------------------------


//--------------------------------------------------------
// Order form functions

// order form functions
function copyAddress(elem) {
    var elemList = ['firstName', 'lastName', 'address01', 'city', 'state', 'zip', 'phone'];

    elemList.each(function(item) {
        $(item + '_shipping').value = $F(item + '_billing');
        $(item + '_shipping').removeClassName('error');
    });

    $('sameShipping').addClassName('checked');
}

function validateOrder() {
}


//-----------------------------
// Utilities

function validateEmail(email) {
    var emailMatch = "[a-zA-Z][\w\.\'-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]";
    if ((email != '') && (email.match(emailMatch))) {
        return true;
    }
    else {
        return false;
    }
}

function decodeHTMLEntities(str) {
    var elem = document.createElement('div');
    var cleanishString = str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
    elem.innerHTML = cleanishString;

    var ret = '';
    if(elem.innerText) {
        ret = elem.innerText;
    }
    else {
        ret = elem.textContent;
    }

    return ret;
}

//-----------------------------

function clearShippingCheck() {
}

function updateStateField() {
}

function toggleCreditCard(elem) {
    if (elem.value == 'paypal') {
        $$('div.lcol div.modified')[0].hide();
    }
    else {
        $$('div.lcol div.modified')[0].show();
    }
}

function toggleShipping(elem) {
    if (elem.value == 'fedex') {
        $$('div.rcol div.modified')[0].show();
        $$('div.rcol div.modified')[1].hide();
    }
    else {
        $$('div.rcol div.modified')[0].hide();
        $$('div.rcol div.modified')[1].show();
    }
}

function showCVV(elem) {
    var payment = Form.getInputs('orderForm','radio','paymentType').find(function(radio) {
        return radio.checked;
    }).value;
    var cvvSrc  = (payment == 'Amex') ? $$('div#cvvImg img')[0] : $$('div#cvvImg img')[1];
    $$('#ExpMonth SELECT')[0].setStyle({
        visibility: 'hidden'
    });

								   
								   
								   
    $$('#ExpYear SELECT')[0].setStyle({
        visibility: 'hidden'
    });
    elem.blur();
    Element.setOpacity(cvvSrc, 0);
    cvvSrc.show();
    $('cvvImg').show();
    cvvSrc.style.height = cvvSrc.readAttribute('height') + 'px';
    cvvSrc.style.width = cvvSrc.readAttribute('width') + 'px';

    new Effect.Parallel([
        new Effect.Opacity(cvvSrc, {
            sync: true, 
            from: 0, 
            to: 1.0
        }) ],
        {
            duration: 1.0, 
            afterFinish: function(effect) {
                $('cvvImg').onmouseup = function() {
                    hideCVV(cvvSrc)
                };            
            }
        });
}

function hideCVV(elem) {
    elem.onmouseup = null;
    new Effect.Parallel([ 
        new Effect.Opacity(elem, {
            sync: true, 
            from: 1.0, 
            to: 0
        }) ],
        {
            duration: 1.0, 
            afterFinish: function(effect) {
                $$('#ExpMonth SELECT')[0].setStyle({
                    visibility: 'visible'
                });
                $$('#ExpYear SELECT')[0].setStyle({
                    visibility: 'visible'
                });
                $('cvvImg').hide();
            } 
        });
}

//-----------------------------
// Overview horizontal scroller

function init_feat_slider(numitems, widex) {
    if(!widex){
        extent = 5;
        wide = 93;
    } else {
        extent = numitems;
        wide = widex;
    }



    var window = $$('div.featScroller_overflow')[0];
    var container = $$('div.featScroller_content')[0];
    var lfArrow = $$('div.featScroller img.arrowLft')[0];
    var rtArrow = $$('div.featScroller img.arrowRt')[0];
    var items = $$('div.featScroller_content div.fileContainer');
    var itemWidth = wide;
    var isFree = true;

    container.setStyle({
        width: (items.length * itemWidth) + 'px', 
        left: '0px'
    });
    container.show();

    lfArrow.onclick = function() {
        if (isFree) {
            isFree = false;
            new Effect.MoveBy(container, 0, (extent * itemWidth), {
                queue: {
                    position: 'end', 
                    scope: 'feat', 
                    limit: 1
                }, 
                beforeStart: function() {
                    if (parseInt(container.style.left) >= 0) {
                        var curItems = $$('div.featScroller_content div.fileContainer');
                        for (var i=curItems.length-extent; i<curItems.length; i++) {
                            container.insertBefore(curItems[i].remove(), curItems[0]);
                        }
                        container.setStyle({
                            left: -(itemWidth * extent) + 'px'
                        });
                    }
                },
                afterFinish: function() {
                    isFree = true;
                }
            });
        }
    };

    rtArrow.onclick = function() {
   
        if (isFree) {
            isFree = false;
            new Effect.MoveBy(container, 0, -(extent * itemWidth), {
                queue:  {
                    position: 'end', 
                    scope: 'feat', 
                    limit: 1
                }, 
                beforeStart: function() {
                    if (parseInt(container.style.left) < 0) {
                        var curItems = $$('div.featScroller_content div.fileContainer');
                        var clearDiv = $$('div.featScroller_content div.clear')[0];
                        for (var i=0; i<extent; i++) {
                            container.insertBefore(curItems[i].remove(), clearDiv);
                        }
                        container.setStyle({
                            left: '0px'
                        });
                    }
                },
                afterFinish: function() {
                    isFree = true;
                }
            });
        }
    };
}

function init_feat_slider_no_wrap() {
    var window = $$('div.featScroller_overflow')[0];
    var container = $$('div.featScroller_content')[0];
    var lfArrow = $$('div.featScroller img.arrowLft')[0];
    var rtArrow = $$('div.featScroller img.arrowRt')[0];
    var items = $$('div.featScroller_content div.fileContainer');
    var itemWidth = 93;

    container.setStyle({
        width: (items.length * itemWidth) + 'px', 
        left: '0px'
    });
    container.show();

    lfArrow.onclick = function() {
        if (parseInt(container.style.left) < 0) {
            new Effect.MoveBy(container, 0, (5 * itemWidth), {
                queue: {
                    position: 'end', 
                    scope: 'feat', 
                    limit: 1
                }, 
                afterFinish: updateFeatBtns
            });
        }
    };
    
    rtArrow.onclick = function() {
        if (parseInt(container.style.left) > -((items.length * itemWidth) - (5 * itemWidth))) {
            new Effect.MoveBy(container, 0, -(5 * itemWidth), {
                queue:  {
                    position: 'end', 
                    scope: 'feat', 
                    limit: 1
                }, 
                afterFinish: updateFeatBtns
            });
        }
    };

    lfArrow.onmouseover = function() {
        $$('div.featScroller img.arrowLft')[0].src = '/images/layout/cons/btn_arrowLft_ovr.png';
    };

    rtArrow.onmouseover = function() {
        $$('div.featScroller img.arrowRt')[0].src = '/images/layout/cons/btn_arrowRt_ovr.png';
    };

    lfArrow.onmouseout = function() {
        $$('div.featScroller img.arrowLft')[0].src = '/images/layout/cons/btn_arrowLft.png';
    };

    rtArrow.onmouseout = function() {
        $$('div.featScroller img.arrowRt')[0].src = '/images/layout/cons/btn_arrowRt.png';
    };

    updateFeatBtns();
}

function updateFeatBtns() {
    var container = $$('div.featScroller_content')[0];
    var lfArrow = $$('div.featScroller img.arrowLft')[0];
    var rtArrow = $$('div.featScroller img.arrowRt')[0];
    var items = $$('div.featScroller_content div.fileContainer');
    var itemWidth = 93;

    if (parseInt(container.style.left) >= 0) {
        lfArrow.setOpacity(.50);
    }
    else {
        lfArrow.setOpacity(1);
    }

    if (parseInt(container.style.left) <= -((items.length * itemWidth) - (5 * itemWidth))) {
        rtArrow.setOpacity(.50);
    }
    else {
        rtArrow.setOpacity(1);
    }
}

function setStage(stage){
    $('shopping_stage_progress_bar').setStyle({
        backgroundPosition: 'left -'+((stage-1)*10)+'px'
    });
	
}
function LoginOverLay() {
    var overlay = "<div id='loginOverlay' style='position: absolute; top: 0px; left: 0px; height: 100%; width: 100%; background-color:#fff; opacity:0.5; filter:alpha(opacity=50);'></div>";
    $('loginContainer').relativize();
    $('loginContainer').insert(overlay);
    
}

function protectLogin() {
    if($("logIn")) {
        $("logIn").setAttribute('onclick', '');    
        $("logIn").observe('click', function(event) {
            LoginOverLay();
            ASB.update('loginContainer',this.form,null,{
                _asbn:'1.1.1.13'
            })
        });
    }
}
    
