/////// Library functions ///////
function addOption(select_elem, label, value) {
    if (typeof label == 'undefined') return;
    var opt = new Option(label, value);
    try {
        select_elem.add(opt, null); // standards compliant
    } catch(ex) {
        select_elem.add(opt); // IE only
    }
}

function showSwatchName(obj) {
    var left = YAHOO.util.Dom.getX(obj);
    var sw = YAHOO.util.Dom.getElementsByClassName('color_name', 'div', obj);
    sw[0].style.display = 'block';
    sw[0].style.left=YAHOO.util.Dom.getX(obj)-YAHOO.util.Dom.getX('det');
}

// this hides all labels to avoid having more than one showing
function hideSwatchName(id) {
    var swatches = document.getElementById('swatches_' + id);
    var elements = YAHOO.util.Dom.getElementsByClassName('color_name', 'div', swatches);
    for (var i=0; i < elements.length; i++) {
        elements[i].style.display='none';
    };
}

function addGCtoBag () {
    var amount = document.getElementById('size_select_0');
    var qty = document.getElementById('qty_select_0');

    if (amount.value == '' || qty.value == '') {
        return;
        // or do something
    };

    var postData = 'i=G1000000&c=001' + '&s=' + amount.value + '&q=' + qty.value;

    var sUrl = "/shopping_bag/ajaxadd";

    var callback = {
        success:function(o) {
            if (typeof weAreInCart != "undefined" && weAreInCart == true) {
                window.location.reload();
                return;
            }
            if (o.responseText == undefined) return;
            if (typeof wait != 'undefined') wait.hide();
            responses = o.responseText.split('<SPLIT>');
            open_header_cart(responses[0]);
            document.getElementById('shopping_bag_counter').innerHTML = responses[1];
            updateRecent();
        },
        failure:function(o) {
            if (o.responseText == undefined) return;
            open_header_cart("There was an error while adding the item to your bag.");
        }
    };

    YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
}

/////// SkuSelection Class /////
function SkuSelection(line_id, color_id, size_id, qty, item_id) {
    this.line_id             = line_id;
    this.color_id            = color_id;
    this.size_id             = size_id;
    this.qty                 = qty;
    this.color_size          = new Array();
    this.defaults            = new Array();
    this.available           = new Array();
    this.available_confirmed = new Array();
    this.enable_backorders   = true;
    this.defaults['color']   = color_id;
    this.defaults['size']    = size_id;
    this.defaults['qty']     = qty;
    this.add_another         = new Array();
    this.imageElementId      = 'thumb_img_';
    this.item_id             = item_id;
    this.swatch_pad          = 0;
    this.is_clearance        = new Array();
    this.current_sku_id      = 0;
}

SkuSelection.prototype.addAvailable = function(swatch_pad, sku_id, qty_available, is_clearance)
{
    this.available[sku_id] = qty_available;
    this.is_clearance[sku_id] = is_clearance;
}

SkuSelection.prototype.addSize = function(swatch_pad, color_id, size_id, description, price, sale_price, sku_id)
{
    if (typeof this.color_size[swatch_pad] == 'undefined')
        this.color_size[swatch_pad] = new Array();

    if (typeof this.color_size[swatch_pad][color_id] == 'undefined')
        this.color_size[swatch_pad][color_id] = new Array();

    this.color_size[swatch_pad][color_id][size_id] = new Array();
    this.color_size[swatch_pad][color_id][size_id]['description'] = description;
    this.color_size[swatch_pad][color_id][size_id]['price'] = price;
    this.color_size[swatch_pad][color_id][size_id]['sale_price'] = sale_price;
    this.color_size[swatch_pad][color_id][size_id]['sku_id'] = sku_id;
}

//modifies the combo to show only the available qty for clearance items
SkuSelection.prototype.setQtyCombo = function() 
{
    var sku_id = "";
    if(this.size_id)
        sku_id = this.color_size[this.swatch_pad][this.color_id][this.size_id]['sku_id'];
    else if(this.defaults["size"]){
        sku_id = this.color_size[this.swatch_pad][this.color_id][this.defaults["size"]]['sku_id'];
    }
    var qty = 9;
    if(sku_id != "" && this.is_clearance[sku_id]){ 
        qty = this.available[sku_id];
        this.current_sku_id = sku_id;
    }
    var qtyCmb = document.getElementById('qty_select_' + this.line_id);
    if(qtyCmb){
        while (qtyCmb.options.length > 1) qtyCmb.remove(1);
        for(var i=1; i<=qty; i++)
            addOption(qtyCmb, i, i);
    }
}

SkuSelection.prototype.setBySkuId = function(skuId) {
    var size;
    for (var g = this.color_size.length - 1; g >= 0; g--)
    {
        for (var i in this.color_size[g]) {
            size = this.color_size[g][i];
            for (var j in size) {
                if (size[j]['sku_id'] == skuId) {
                    this.selectColor(i, g);
                    this.selectSize(j);
                    return true;
                }
            }
        }
    }
    return false;
}

SkuSelection.prototype.setImageFunction = function(func) {
    this.imageFunction = func;
}

SkuSelection.prototype.selectColor = function(color_id, swatch_pad)
{
    if (swatch_pad == null) { swatch_pad = 0; }
    this.swatch_pad = swatch_pad;

    this.color_id  = color_id;
    document.getElementById('color_id_' + this.line_id).value = color_id;

    hideSwatchName(this.line_id);
    var swatch = document.getElementById('swatch_' + this.line_id);
    var swatches = YAHOO.util.Dom.getElementsByClassName('swatch', 'div', swatch);
    for (var i = 0; i < swatches.length; i++) {
        if(swatches[i].id+""=="swatch_0_001")
            swatches[i].className = 'swatch-white';
        else
            swatches[i].className = 'swatch';
    }

    // if the user is simply selecting from another swatch pad and not from
    // an "add another" line, show that selection
    if (this.line_id == 0 && swatch_pad != 0) {
        swatch = document.getElementById('swatch_' + swatch_pad + '_' + color_id);
    } else {
        swatch = document.getElementById('swatch_' + this.line_id + '_' + color_id);
    }

    if(color_id+""=="001" && swatch.color_id+""=="001")
        swatch.className = 'swatch-white selected';
    else
        swatch.className = 'swatch selected';

    var ddSize = document.getElementById('size_select_' + this.line_id);
    while (ddSize.options.length > 1) ddSize.remove(1);
    for (var size_id in this.color_size[swatch_pad][color_id]) {
        if (typeof this.color_size[swatch_pad][color_id][size_id] != 'function'
        && (typeof this.color_size[swatch_pad][color_id][size_id] != 'undefined')){
            addOption(ddSize, this.color_size[swatch_pad][color_id][size_id]['description'], size_id);
        }
    }

    for (var i=0; i < ddSize.options.length; i++) {
        if(ddSize.options[i].text == 'NS'){
            ddSize.remove(i);
        }
    };

    // remove NS
    if (ddSize.length == 1) {
        ddSize.style.display = 'none';
        this.size_id = '0001'; // NS
        if (this.defaults['size'] == '') {this.defaults['size'] = this.size_id};
    }else {
        ddSize.style.display = 'inline';
    }

    this.selectSize(this.size_id);
    this.changePrice();
    this.replaceImg();
    
    // add param to links 
    var img_link = document.getElementById('product_image_' + swatch_pad);
    var desc_link = document.getElementById('product_title_' + swatch_pad);
    if (img_link) {
        var href = img_link.parentNode.href;
        if (href) {
            href = href.replace(/\?.*/g, '');
            img_link.parentNode.href = href + '?default_color=' + color_id;
            if (desc_link) {
                var as =desc_link.getElementsByTagName('a');
                if (as.length > 0) as[0].href = href;
            }
        }
    }
}

SkuSelection.prototype.selectSize = function(size_id) {
    var ddSize = document.getElementById('size_select_' + this.line_id);
    for (var i  = 0; i < ddSize.length; i++ ) {
        if (ddSize.options[i].value == size_id) {
            ddSize.selectedIndex = i;
            return;
        }
    }
    this.size_id = null; // Size not found
}

SkuSelection.prototype.selectQty = function(qty) {
    var ddQty = document.getElementById('qty_select_' + this.line_id);
    ddQty.selectedIndex = qty;
}

SkuSelection.prototype.setSize = function(size_id) {
    this.size_id = size_id;
    this.setQtyCombo();
    this.changePrice();
}

SkuSelection.prototype.setItemId = function(item_id) {
    this.item_id = item_id;
}

SkuSelection.prototype.setQty = function(qty) {
    this.qty = qty;
}

SkuSelection.prototype.setDefaults = function() {
    this.selectColor(this.defaults['color'], this.line_id);
    this.selectSize(this.defaults['size']);
    this.setQtyCombo();
    this.selectQty(this.defaults['qty']);
}

// TODO: Fix me for all image types
SkuSelection.prototype.replaceImg = function() {
    var img = document.getElementById(this.imageElementId + this.line_id);
    if (this.imageFunction) {
        this.imageFunction(this.item_id + '_' + this.color_id);
        return;
    }
    if (!img) return;
    img.src = img.src.replace(/[0-9]+_[0-9]+.jpg/, this.item_id + '_' + this.color_id + '.jpg');
}

SkuSelection.prototype.changePrice = function() {

    if (!this.color_id || !this.size_id) return;
    var retail = document.getElementById('price');
    var sale = document.getElementById('sale_price');

    if (retail) retail.innerHTML = this.color_size[this.swatch_pad][this.color_id][this.size_id]['price'];
    if (sale) sale.innerHTML = this.color_size[this.swatch_pad][this.color_id][this.size_id]['sale_price'];
}


SkuSelection.prototype.addAnotherSku = function(sku_id, qty) {
    if (typeof this.add_another[sku_id] == "undefined") this.add_another[sku_id] = 0;
    qty = parseInt(qty);
    this.add_another[sku_id] += qty;
}

SkuSelection.prototype.addAnotherPost = function() {
    var post = '';
    for (var i = 0; i < this.add_another.length; i++) {
        var x = this.add_another[i];
        if (this.add_another[x] == 0) continue;
        post = post + '&sa[' + x + ']=' + this.add_another[x];
    };
    return post;
}

SkuSelection.prototype.clearAddAnother = function() {
    this.add_another = new Array();

    aaDiv = document.getElementById('add-another-' + this.line_id);
    if (typeof aaDiv == 'undefined' || !aaDiv) return;
    aaDiv.innerHTML = '';
}

SkuSelection.prototype.editAddAnother = function(sku_id, qty) {
    if (!this.setBySkuId(sku_id)) return;
    this.selectQty(qty);
    this.add_another[sku_id] = 0;

    aaDiv = document.getElementById('add-another-item-' + sku_id);
    if (aaDiv) aaDiv.parentNode.removeChild(aaDiv);
}

SkuSelection.prototype.addAnother = function() {
    if (!this.checkSizeQty()) return;

    var skuId = this.color_size[this.swatch_pad][this.color_id][this.size_id]['sku_id'];

    var existing = document.getElementById('add-another-qty-' + skuId);
    if (existing) {
        qty = parseInt(this.qty);
        var new_qty = qty + parseInt(existing.textContent);
        existing.innerHTML = new_qty;
        this.addAnotherSku(skuId, qty);
        return;
    }

    var aaDiv = document.getElementById('add-another-' + this.line_id);
    if (!aaDiv) return;

    var outerThis = this;
    var callback = {
        success: function(o) {
            var txt = aaDiv.innerHTML;
            if (typeof txt == 'undefined') txt = '';
            aaDiv.innerHTML = txt + o.responseText;

            outerThis.addAnotherSku(skuId, outerThis.qty);
        },
        failure: function(o) {
            alert('Error adding another');
        }
    };

    postData = 's=' + skuId + '&q=' + this.qty;
    YAHOO.util.Connect.asyncRequest('POST', '/shopping_bag/ajaxaddanother', callback, postData);
}

SkuSelection.prototype.addAnotherDirect = function() {
    if (!this.checkSizeQty()) return;

    var skuId = this.color_size[this.line_id][this.color_id][this.size_id]['sku_id'];

    if (!skuId) return;
    var sURL = '/shopping_bag/addskuid?sku[' + skuId + ']=' + this.qty;
    window.location =  sURL;
}

SkuSelection.prototype.checkSizeQty = function() {
    if ((!this.size_id && this.countProps(this.color_size[this.swatch_pad][this.color_id]) > 1) || !this.qty) {
        var errTxt = "Please select the following:\r\n";
        errTxt += !this.size_id ? " - Size\r\n" : "";
        errTxt += !this.qty ?  " - Quantity\r\n" : "";
        alert(errTxt);
        return false;
    }

    // if a size is required it's caught above.  consequently, if we make it here and there is no size, use the default size
    if ( !this.size_id ) {
        this.size_id = this.defaults['size'];
    }

    return true;
}

// returns false if the user doesn't want to backorder the item.
SkuSelection.prototype.checkAvailable = function() {
    var sku_id = this.color_size[this.swatch_pad][this.color_id][this.size_id]['sku_id'];
    if ( typeof this.available[sku_id] != 'undefined'
    && ( (this.available[sku_id] <= 0) || (this.available[sku_id] - this.qty < 0) ) 
    && !this.is_clearance[sku_id])
    {
        if (typeof this.available_confirmed[sku_id] == 'undefined'){
            this.confirmBackorder(sku_id);
            return false;
        };
    }
    return true;
}

// the confirmation box
SkuSelection.prototype.confirmBackorder = function(sku_id) {

        confirm_bo = new YAHOO.widget.Panel("confirmbo", {
            width:"286px",
            fixedcenter: true,
            constraintoviewport: true,
            underlay:"shadow",
            close:false,
            visible:false,
            draggable:false,
            modal : true
        });

        confirm_bo.render(document.body);
        ss = this;
        yes_action = function(){
            ss.available_confirmed[sku_id] = 1;
            confirm_bo.hide();
            confirm_bo = null;
            ss.addToBag();
        }

        body = '<img src="/images/itemBackorder.jpg" alt="" usemap="#backordermap" border="0"/>'
             + '<map name="backordermap" id="backordermap">'
             + '<area shape="rect" coords="11,96,39,114" href="#" alt="" onclick="yes_action();" />'
             + '<area shape="rect" coords="10,114,73,132" href="#" alt="" onclick="confirm_bo.hide()" />'
             + '<area shape="rect" coords="266,3,282,19" href="#" alt="" onclick="confirm_bo.hide()"/>'
             + '</map>';


        confirm_bo.setBody(body);
        confirm_bo.render(document.body);

        var panel = document.getElementById('confirmbo');
        panel.style.marginLeft = ((YAHOO.util.Dom.getViewportWidth() / 2) - (170 / 2)) + 'px';

        confirm_bo.show();

        var underlay = document.getElementById('confirmbo_mask');
        if(underlay)
            YAHOO.util.Event.addListener(underlay, "click", function(){confirm_bo.hide();});

}

SkuSelection.prototype.addToBag = function() {
    if (!this.checkSizeQty()) return;
    if (this.enable_backorders && !this.checkAvailable()) return;

    var postData = 'i=' + this.item_id + '&c=' + this.color_id + '&s=' + this.size_id + '&q=' + this.qty;
    postData += this.addAnotherPost();

    var sUrl = "/shopping_bag/ajaxadd";
    
    outerThis = this;
    var callback = {
        success:function(o) {
            if (typeof weAreInCart != "undefined" && weAreInCart == true) {
                window.location.reload();
                return;
            }
            if (o.responseText == undefined) return;
            if (typeof wait != 'undefined') wait.hide();

            //check if item was added or there was an availability change
            var add_success = o.responseText.match(/<SPLIT>/i);

            if(add_success){

                responses = o.responseText.split('<SPLIT>');
                open_header_cart(responses[0]);
                document.getElementById('shopping_bag_counter').innerHTML = responses[1];
                outerThis.clearAddAnother();
                updateRecent();
            }
            else{
                //we've requested more than the available qty
                var availableQty = o.responseText.match(/<span style="display: none;">(.*)<\/span>/i);
                var sku_id = skuSelect.color_size[skuSelect.swatch_pad][skuSelect.color_id][skuSelect.size_id]['sku_id'];
                skuSelect.available[sku_id] = availableQty[1];
                skuSelect.setQtyCombo();
                skuSelect.selectQty(availableQty[1]);
                setTimeout(skuSelect.qtyChangeMsg, 1);
            }
        },
        failure:function(o) {
            if (o.responseText == undefined) return;
            open_header_cart("There was an error while adding the item to your bag.");
        }
    };

    return YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
}

SkuSelection.prototype.qtyChangeMsg = function() {
    confirm_bo = new YAHOO.widget.Panel("confirmbo", {
        width:"286px",
        fixedcenter: true,
        constraintoviewport: true,
        underlay:"shadow",
        close:false,
        visible:false,
        draggable:false,
        modal : true
    });

    confirm_bo.render(document.body);
    ss = this;
    yes_action = function(){
        ss.available_confirmed[sku_id] = 1;
        confirm_bo.hide();
        confirm_bo = null;
        ss.addToBag();
    }
    body = '<img src="/images/qty_exceeds.jpg" alt="" usemap="#backordermap" border="0"/>'
             + '<map name="backordermap" id="backordermap">'
             + '<area shape="rect" coords="266,3,282,19" href="#" alt="" onclick="confirm_bo.hide()"/>'
             + '</map>';
    confirm_bo.setBody(body);
    confirm_bo.render(document.body);

    var panel = document.getElementById('confirmbo');
    panel.style.marginLeft = ((YAHOO.util.Dom.getViewportWidth() / 2) - (170 / 2)) + 'px';

    confirm_bo.show();

    var underlay = document.getElementById('confirmbo_mask');
    if(underlay)
        YAHOO.util.Event.addListener(underlay, "click", function(){confirm_bo.hide();});
}

SkuSelection.prototype.printPopup = function() {
    var sUrl = "/detail/print";
    var params = '/' + this.item_id + '/' + this.color_id;
    if(this.size_id && this.qty)
        params += '/' + this.size_id + '/' + this.qty
    popup(sUrl+params, 'print', 970, 761, true);
}

SkuSelection.prototype.countProps = function(obj) {
    var i = 0;
    if ( typeof obj == "object" ) {
        for ( prop in obj ) {
            if ( typeof obj[prop] != 'undefined' && typeof obj[prop] != 'function') {
                i++;
            }
        }
    }
    return i;
}

SkuSelection.prototype.showSendDetails = function() {
    var callback = {
        success: function(o) {
            send_details = new YAHOO.widget.Panel("send_details", {
                width:"514px",
                x: (document.documentElement.clientWidth - 514)/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();

            var underlay = document.getElementById('send_details_mask');
            if (underlay) YAHOO.util.Event.addListener(underlay, "click", function(){show_selects();send_details.hide();});
            return false;
        },
        failure: function (o) {}
    };

    YAHOO.util.Connect.asyncRequest(
        'POST',
        '/detail/sendDetailsToFriend/',
        callback,
        'item=' + this.item_id + '&color=' + this.color_id
    );
}
