function printPage()
{
        if (window.print)
        {
                window.print();
        }
}

/**
* a javascript collection object of all of the window popup options
*/
function popupOptions()
{
    this.height         = screen.availHeight / 2;
    this.width          = screen.availWidth / 2;
    this.top            = 0;
    this.left           = 0;
    this.toolbar        = false;
    this.location       = false;
    this.directories    = false;
    this.status         = false;
    this.menubar        = false;
    this.scrollbars     = false;
    this.resizable      = false;
    this.dependent      = false;

    this.build          = _buildOptions;
}

/**
* a private javascript method for popupOptions which is used
* to build a popup option string
*/
function _buildOptions()
{
    var sTemp = "";

    sTemp += "height=" + this.height + ",";
    sTemp += "width=" + this.width + ",";
    sTemp += "top=" + this.top + ",";
    sTemp += "left=" + this.left + ",";
    sTemp += "scrollbars=" + ((this.scrollbars) ? "yes" : "no") + ",";
    sTemp += "toolbar=" + ((this.toolbar) ? "yes" : "no") + ",";
    sTemp += "location=" + ((this.location) ? "yes" : "no") + ",";
    sTemp += "directories=" + ((this.directories) ? "yes" : "no") + ",";
    sTemp += "status=" + ((this.status) ? "yes" : "no") + ",";
    sTemp += "menubar=" + ((this.menubar) ? "yes" : "no") + ",";
    sTemp += "resizable=" + ((this.resizable) ? "yes" : "no") + ",";
    sTemp += "dependent=" + ((this.dependent) ? "yes" : "no");

    return(sTemp);
}

// used to track different window popups
var aWin = new Array();

/**
* creates a popup window
*
* @param string window url
* @param string window name
* @param string [optional] window width
* @param string [optional] window height
* @param boolean [optional] whether window is scrollable or not
* @param boolean [optional] whether window has a toolbar or not
* @param boolean [optional] whether window is resizable or not
*/
function popup(winlink, winname)
{
    var winwidth        = (arguments.length >= 3) ? arguments[2] : screen.availWidth / 2;
    var winheight   = (arguments.length >= 4) ? arguments[3] : screen.availHeight / 2;
    var winscroll   = (arguments.length >= 5) ? ((arguments[4] == '1') ? true : false) : false;
    var wintoolbar  = (arguments.length >= 6) ? ((arguments[5] == '1') ? true : false) : false;
    var winresize   = (arguments.length >= 7) ? ((arguments[6] == '1') ? true : false) : true;
    //Liz Ng 3.23.2004:
    var winmenubar      = (arguments.length >= 8) ? ((arguments[7] == '1') ? true : false) : false;

    var oOption = new popupOptions();

    oOption.width               = winwidth;
    oOption.height              = winheight;
    oOption.scrollbars  = winscroll;
    oOption.toolbar             = wintoolbar;
    oOption.resizable   = winresize;
    //Liz Ng 3.23.2004:
    oOption.menubar             = winmenubar;

    // these values are hard coded
    oOption.top                 = ((screen.availHeight / 2) - (winheight / 2));
    oOption.left                = ((screen.availWidth / 2) - (winwidth / 2));
    oOption.location    = false;
    oOption.directories = false;
    oOption.status              = false;
    oOption.dependent   = false;

    var sOptions = oOption.build();

    oWin = window.open(winlink, winname, sOptions);
    oWin.focus();
}

function toggle_recent () {
    var b = document.getElementById('list_recent_items');
    var oldHeight = b.style.height;
    var dir = oldHeight == "0px" ? "up" : "down";
    if(dir == "down"){
        if(document.getElementById('size_select_0'))
            document.getElementById('size_select_0').style.display = "";
        if(document.getElementById('qty_select_0'))
            document.getElementById('qty_select_0').style.display = "";
    }
    blindRecent(dir);
    var r=document.getElementById('recent_items');
    var arrows = r.getElementsByTagName('IMG');
    var arrow = null;
    var dirArrow = oldHeight == "0px" ? "down" : "up";
    for(var i = 0; i < arrows.length; i++){
        arrow = arrows[i];
        arrow.src = "/images/fltrArrow"+dirArrow.substr(0,1).toUpperCase()+dirArrow.substr(1)+".gif";
    }
}

function showQuickview (thumb) {
        divs=thumb.getElementsByTagName('div');
        divs[0].style.display="block";
}

function hideQuickview (thumb) {
        divs=thumb.getElementsByTagName('div');
        divs[0].style.display="none";
}

function swap_text(id, text, style, on_style)
{
    e = document.getElementById(id);
    e.className = on_style;
    if (e.value == '' || e.value == text) {
        e.value = '';
    };
    e.onblur = new Function("e = document.getElementById('"+id+"');if (e.value == '') {e.className = '"+style+"';e.value='"+text+"'}");
}

function blindRecent(dir){
    var obj = document.getElementById('list_recent_items');
    var targetHeight = obj.getElementsByTagName('TABLE')[0].offsetHeight;
    var r=document.getElementById('recent_items');
    var h = parseInt(obj.style.height);
    var inc = dir == 'up' ? 20 : -20;

    if((dir == 'up' && parseInt(obj.style.height) < targetHeight)||
       (dir == 'down' && parseInt(obj.style.height) > 0)){
        h =  h + inc;

        if(h > targetHeight){
            h = targetHeight;
            if(document.getElementById('size_select_0'))
                document.getElementById('size_select_0').style.display = "none";
            if(document.getElementById('qty_select_0'))
                document.getElementById('qty_select_0').style.display = "none";
        }
        if(h < 0){
            h = 0;
        }

        obj.style.height = h+'px';
        obj.style.marginTop = '-'+obj.offsetHeight+'px'
        r.style.margin = (-26-obj.offsetHeight)+"px 0px "+obj.offsetHeight+"px";
        setTimeout("blindRecent('"+dir+"')",1);
    }
}

function updateRecent(){
    var callback = {
        success: function(o) {
            var responses = o.responseText.split('<SPLIT>');
            var count = parseInt(responses[0].replace(/^\n*/,''));
            var win_recent = document.getElementById('recent_items_header');
            if(count > 0){
                var counter = document.getElementById('counter_recent_items');
                if (counter) counter.innerHTML = count;
                var recent = document.getElementById('list_recent_items');
                if (recent) recent.innerHTML = responses[1];
                if(!recent)
                    createRecentObj();
            }
            if (win_recent) win_recent.style.visibility = count > 0 ? 'visible' : 'hidden';
        },
        failure: function (o) {

        }
    }
    YAHOO.util.Connect.asyncRequest('POST',"/main/updaterecent",callback,'');
}

var recent = null;
function createRecentObj(){
    recent = new YAHOO.widget.Panel("recent_items",
    {
        constrainttoviewport: true,
        close: false,
        visible: false,
        draggable: false,
        modal:false,
        context: ['list_recent_items', 'tr', 'br']
    });
    recent.show();
}

//for ie6
function hide_selects()
{
    els = document.getElementsByTagName('select');
    for (i in els) {
        if (els[i].style) {
            els[i].style.visibility = "hidden";
        }
    }
}

function show_selects()
{
    els = document.getElementsByTagName('select');
    for (i in els) {
        if (els[i].style) {
            els[i].style.visibility = "visible";
        }
    }
}


//      + These functions show the sizecharts on customer service section
//              might be used in other parts of the site as well.

var sizecharts_panel;
function show_sizecharts(category_url) {

    if (category_url == "tops")
        category_url = '01_tops';
    else if (category_url == "pants")
        category_url = '02_pants';
    else if (category_url == "denim")
        category_url = '03_denim';
    else if (category_url == "skirts-dresses")
        category_url = '04_skirts_dresses';
    else if (category_url == "suits")
        category_url = '05_suits';
    else if (category_url == "jackets-outerwear")
        category_url = '06_jackets_outwear';
    else if (category_url == "denim")
        category_url = '01_tops';
    else if (typeof category_url == "undefined")
        category_url = '01_tops';

    //if (typeof sizecharts_panel != "undefined") { sizecharts_panel.show(); return;}
    sizecharts_panel = new YAHOO.widget.Panel("sizecharts_p", {
        close:false,
        visible:false,
        draggable:false,
        modal:true,
        zIndex:500,
        xy:[234,69],
        underlay:"none"
    });

    switch_sizecharts(category_url);
    hide_selects();
    sizecharts_panel.render(document.body);
    sizecharts_panel.show();
}

function recall_sizecharts(schrt_id) {
    //alert ("schrt_id = "+schrt_id);
    sizecharts_panel.destroy();
    show_sizecharts(schrt_id);
}

//      + switch_sizecharts(schrt_id)
//      params: schrt_id        //  contains the name of the image for the size chart in
                                                // /images/customer_service/categories_sizecharts/
function switch_sizecharts(schrt_id) {
        var width = 695;
        var height = 710;
        if (schrt_id == '02_pants' || schrt_id == '03_denim' || schrt_id == '06_jackets_outwear'){
                height = 588;
        } else if (schrt_id == '04_skirts_dresses'){
                height = 678;
        } else if (schrt_id == '05_suits'){
                height = 738;
        }
        var sizecharts_body = '<img src="/images/customer_service/categories_sizecharts/'+
                schrt_id +'.jpg" width="'+width+'" height="'+height+'" border="0" usemap="#linksmap" id="sizecharts_p" />' +
                 '<map name="linksmap" id="linksmap">' +
                                '<area shape="rect" coords="678,2,693,19"   href="javascript:show_selects();sizecharts_panel.hide();" />' +
                                '<area shape="rect" coords="14,83,77,106"   href="javascript:recall_sizecharts(\'01_tops\');" />' +
                                '<area shape="rect" coords="78,83,131,106"  href="javascript:recall_sizecharts(\'02_pants\');" />' +
                                '<area shape="rect" coords="133,83,189,106" href="javascript:recall_sizecharts(\'03_denim\');" />' +
                                '<area shape="rect" coords="192,83,301,106" href="javascript:recall_sizecharts(\'04_skirts_dresses\');" />' +
                                '<area shape="rect" coords="304,83,358,106" href="javascript:recall_sizecharts(\'05_suits\');" />' +
                                '<area shape="rect" coords="359,83,489,106" href="javascript:recall_sizecharts(\'06_jackets_outwear\');" />' +
                 '</map>';
    sizecharts_panel.setBody(sizecharts_body);
    sizecharts_panel.render(document.body);
    sizecharts_panel.show();

    var underlay = document.getElementById('sizecharts_p_mask');
    if (underlay) YAHOO.util.Event.addListener(underlay, "click", function(){show_selects();sizecharts_panel.hide();});
    return false;
}


//the following functions are used to send item details in subcategories, fashin and favorites

function showSendFavorites(is_wishlist) {
    var inputs = YAHOO.util.Dom.getElementsByClassName('thumb','a');
    var checked_items = new Array();
    var itemId = "";
    var colorId = "";
    var itemQueue = new Array();
    var colorQueue = new Array();
    for (var i = 0; i < inputs.length; i++) {
        itemId = "" + YAHOO.util.Dom.getFirstChildBy(inputs[i],function (node) {
                            return node.nodeName.toUpperCase() == "IMG";
                        }).src.match(/\d+_/);
        colorId = "" + YAHOO.util.Dom.getFirstChildBy(inputs[i],function (node) {
                            return node.nodeName.toUpperCase() == "IMG";
                        }).src.match(/_\d+/);
        itemQueue[itemQueue.length] = itemId.replace("_", "");
        colorQueue[colorQueue.length] = colorId.replace("_", "");
    };

    if(itemQueue.length > 0){
        var callback = {
            success: function(o) {
                pwidth = 514;
                if(is_wishlist == 'wishlist')pwidth = 344;
                send_details = new YAHOO.widget.Panel("send_details", {
                            width: pwidth+"px",
                            x: (document.documentElement.clientWidth - pwidth)/2,
                            y: 145,
                            close:false,
                            zindex:101,
                            visible:false,
                            draggable:false,
                            modal:true,
                            underlay: 'none'
                });

                send_details.setBody(o.responseText);

                send_details.render(document.body);
                if (typeof quickViewPanel != 'undefined') {
                    quickViewPanel.hide();
                };
                hide_selects();
                scroll(0,0);
                send_details.show();
            },
            failure: function (o) {}
        };
        send_wishlist = 'false';
        if(is_wishlist == 'wishlist') send_wishlist = 'true';
        YAHOO.util.Connect.asyncRequest(
           'POST',
           '/detail/sendDetailsToFriend/',
           callback,
           'item=' + itemQueue + '&color=' + colorQueue + '&wishlist=' + send_wishlist
        );
    }
}


//  +   validate_email_adresses
//      checks input for valid email adress(es) match
//      returns boolean, true if adresses are correct
//      +
function validate_email_adresses(email_adress){
    //  single email match expression...
    var email_1_regexp =  /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    //  multiple, separated by commas email adresses list
    var email_n_regexp = /^(((\s)*(\,){1}(\s)*){1}([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+)+$/;
    //  adding a comma at the beginning simplfies the multiple addresses expression a lot...
    return String(","+email_adress).search (email_n_regexp) != -1;
}

function SendDetails() {
    var item_id = document.getElementById('send_item_id').value;
    var color_id = document.getElementById('send_color_id').value;
    var from_name = document.getElementById('from_name').value;
    var from_mail = document.getElementById('from_mail').value;
    var to_mail = document.getElementById('to_mail').value;
    var message_content = document.getElementById('message').value;

    if (!from_mail || !to_mail || !from_name){
        alert("Please fill in all the fields marked with *");
        return;
    }

    if (!validate_email_adresses(to_mail)){
        alert("Please enter valid e-mail address(es).");
        return;
    }
    if (!validate_email_adresses(from_mail)){
        alert("Please enter a valid e-mail address.");
        return;
    }

    var postData = 'item=' + item_id
                + '&color=' + color_id
                + '&from_name=' + from_name
                + '&from_mail=' + from_mail
                + '&to_mail=' + to_mail
                + '&message_content=' + message_content;

    var sUrl = "/send/details";

    var callback = {
        success:function(o) {
            hide_selects();
            scroll(0,0);
            send_details.setBody(o.responseText);
        },
        failure:function(o) {
            alert("Your mail couldn't be sent");
        }
    };

    YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
}

//  +   SendSweepstakes(sUrl)
//      @param  sUrl: the url of the email action in module/action syntax
//      @todo: extend and normalize SendDetails to do this job as well
//      +
function SendSweepstakes(sUrl) {

    //var item_id = document.getElementById('send_item_id').value;
    //var color_id = document.getElementById('send_color_id').value;
    var from_name = document.getElementById('from_name').value;
    var from_mail = document.getElementById('from_mail').value;
    var to_mail = document.getElementById('to_mail').value;
    var message_content = document.getElementById('message').value;

    if (!from_mail || !to_mail || !from_name){
        alert("Please fill in all the fields marked with *");
        return;
    }

    if (!validate_email_adresses(to_mail)){
        alert("Please enter valid e-mail address(es).");
        return;
    }
    if (!validate_email_adresses(from_mail)){
        alert("Please enter a valid e-mail address.");
        return;
    }

    var postData = '&from_name=' + from_name
                + '&from_mail=' + from_mail
                + '&to_mail=' + to_mail
                + '&message_content=' + message_content;

    //var sUrl = "/send/sweepstakes";

    var callback = {
        success:function(o) {
            urchinTracker('/sweepstakes/refer_a_friend_success');	//	+ urchin stats, log this email submission
            hide_selects();
            scroll(0,0);
            send_details.setBody(o.responseText);
        },
        failure:function(o) {
            alert("Your mail couldn't be sent");
        }
    };

    YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
}

function prepareSearch(){
    var txt = document.getElementById('search_kw');
    var kws = txt.alt;
    var input = txt.value;
    if(input == 'Search again' || input == '')
        input = kws;
    return true;
}

function hideSendDetails() {
    if(document.getElementById('subscribe'))
        document.getElementById('subscribe').checked = false;
    show_selects();
    send_details.hide();
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

function signUpEmailPopup() {

    var body = '<div id="ty_panel" style="position: relative;"><img src="/images/homepage/email-thanks-overlay.jpg" usemap="#PopupMap" border="none"><div style="padding: 5px 30px 0px; top:95px; left:15px; position:absolute;"><p style="color: #522c1b; padding-top: 3px;">You will now receive special mail offers, news about events, and Shopko advertisments.</p></div></div>';

    tyPanel = new YAHOO.widget.Panel("ty_panel", {
                        width:"591px",
                        height:"153px",
                        constraintoviewport: true,
                        fixedcenter: true,
                        underlay:"none",
                        close:false,
                        visible:false,
                        draggable:false,
                        modal: true
                    });
    tyPanel.setBody(body);

    tyPanel.render(document.body);

    var email = document.getElementById('email_signup').value;
    var email_error = document.getElementById('email_error');
    var postData = "email=" + email;
    var callback = {
        success: function(o) {
            if (o.responseText == 'invalid_email') {
                email_error.innerHTML = 'Please verify your email address.';
            } else if (o.responseText == 'user_exists') {
                email_error.innerHTML = 'This email has already been registered.';
            } else {
                email_error.innerHTML = '';
                tyPanel.show();
            }
        },
        failure: function (o) {}
    };

    YAHOO.util.Connect.asyncRequest(
        'POST',
        '/email_signup',
        callback,
        postData);
}

function hideSignUpEmailPopup() {
    tyPanel.hide(true);
}


function openExtraSavingsWindow(){
        extrasavings = window.open('/extraSavings','Extra_Savings','width=340,height=650,scrollbars=no');
}

function setSelectValue(combo, val){
    var select = document.getElementById(combo);
    for(index = 0;index < select.length;index++) {
        if(select[index].value == val)
            select.selectedIndex = index;
    }
}


// An ie6 hack
function buildIframe (name) {
    name = name || 'det';
    var el = '';
    if (YAHOO.lang.isString(name)) {
        el = YAHOO.util.Dom.get(name);
    } else if (YAHOO.lang.isObject(name)){
        el = name;
    };
    destroyIframe();

    //For YUI menu we need the child of the element
    //shopko contains a special menu entry where 2 ul are inside 1 entry
    var double_width = false;
    if (el.className.substr(0, 7) == 'yuimenu') {
        el = YAHOO.util.Dom.getElementsBy(function(o){if(o.nodeName == 'UL') return true;}, 'ul', el);
        if(el.length==2) double_width = true;
        el = el[0];
    }

    var size = YAHOO.util.Dom.getRegion(el);

    var iframe = document.createElement('iframe');
    iframe.style.border     = "medium none";
    iframe.style.margin     = "0pt";
    iframe.style.padding    = "0pt";
    iframe.style.opacity    = "0";
    iframe.style.filter     = "alpha(opacity=0)";
    iframe.style.position   = "absolute";
    iframe.style.display    = "block";
    iframe.style.width      = (size.right - size.left) + 'px';
    iframe.style.height     = (size.bottom - size.top) + 'px';
    //commented this out because otherwise YAHOO menu becaomes unusable because you,
    //can't set zindex to a yahoo menu with property "position" = static (all sites)
    //iframe.style.zIndex     = "1";
    iframe.id               = "hack";
    iframe.style.left       = (parseInt(size[0])-2) + 'px';
    iframe.style.top        = size[1] + 'px';

    //double the width if neccesary
    if(double_width == true) iframe.style.width = (size.right - size.left)*2 + 'px';

    document.body.appendChild(iframe);

    return iframe;
}

function destroyIframe (name) {
    name = name || 'hack';
    var old = document.getElementById('hack');
    if (old) document.body.removeChild(old);
}


//effect used in the homepage to show the online wrap
function onlineWrapEffect(overlay, dur) {
    var onlineWrapEffect = new YAHOO.widget.ContainerEffect(overlay, { attributes:{opacity: {from:1, to:1}}, duration:dur, method:YAHOO.util.Easing.easeIn }, { attributes:{opacity: {to:0}}, duration:dur, method:YAHOO.util.Easing.easeOut}, overlay.element );

    onlineWrapEffect.handleStartAnimateIn = function(type,args,obj) {
        YAHOO.util.Dom.addClass(obj.overlay.element, "hide-select");
        
        if (! obj.overlay.underlay) {
            obj.overlay.cfg.refireEvent("underlay");
        }

        if (obj.overlay.underlay) {
            obj.initialUnderlayOpacity = YAHOO.util.Dom.getStyle(obj.overlay.underlay, "opacity");
            obj.overlay.underlay.style.filter = null;
        }

        YAHOO.util.Dom.setStyle(obj.overlay.element, "visibility", "visible"); 
        YAHOO.util.Dom.setStyle(obj.overlay.element, "opacity", 1);
    };

    onlineWrapEffect.handleCompleteAnimateIn = function(type,args,obj) {
        YAHOO.util.Dom.removeClass(obj.overlay.element, "hide-select");

        if (obj.overlay.element.style.filter) {
            obj.overlay.element.style.filter = null;
        }           
        
        if (obj.overlay.underlay) {
            YAHOO.util.Dom.setStyle(obj.overlay.underlay, "opacity", obj.initialUnderlayOpacity);
        }

        obj.overlay.cfg.refireEvent("iframe");
        obj.animateInCompleteEvent.fire();
    };

    onlineWrapEffect.handleStartAnimateOut = function(type, args, obj) {
        YAHOO.util.Dom.addClass(obj.overlay.element, "hide-select");

        if (obj.overlay.underlay) {
            obj.overlay.underlay.style.filter = null;
        }
    };

    onlineWrapEffect.handleCompleteAnimateOut =  function(type, args, obj) { 
        YAHOO.util.Dom.removeClass(obj.overlay.element, "hide-select");
        if (obj.overlay.element.style.filter) {
            obj.overlay.element.style.filter = null;
        }               
        YAHOO.util.Dom.setStyle(obj.overlay.element, "visibility", "hidden");
        YAHOO.util.Dom.setStyle(obj.overlay.element, "opacity", 1); 

        obj.overlay.cfg.refireEvent("iframe");

        obj.animateOutCompleteEvent.fire();
    };  

    onlineWrapEffect.init();
    return onlineWrapEffect;
}; 

//the following segment is just required during dec 2009
var freeship;
function openFreeShip(){
    var callback = {
        success: function(o) {            
            freeship = new YAHOO.widget.Panel("freeship", { 
                    width:"700px", 
                    visible:false, 
                    draggable:false, 
                    fixedcenter: true,
                    underlay:"none",
                    modal: true,
                    close:false } ); 
            freeship.setBody(o.responseText);
            freeship.render('freeship_container');
            freeship.show();
        },
        failure: function (o) {}
    };
    YAHOO.util.Connect.asyncRequest(
        'POST',
        '/free_ship_popup',
        callback,
        '');
    
}
