/////// 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';
    };

    var swatches_sale = document.getElementById('swatches_sale');
    if (swatches_sale) {
        var elements_sale = YAHOO.util.Dom.getElementsByClassName('color_name', 'div', swatches_sale);
        for (var j=0; j < elements_sale.length; j++) {
            elements_sale[j].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];
        },
        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);
}

var color_swatchpad = new Array();
function addSwatchpadRelation(color_id, swatchpad, rootNode){
    if(typeof rootNode != 'undefined'){
        if (typeof color_swatchpad[rootNode] == 'undefined')
            color_swatchpad[rootNode] = new Array();    
        color_swatchpad[rootNode][color_id] = swatchpad;
    }else{
        color_swatchpad[color_id] = swatchpad;
    }
}

/* 
 * TT15350 - we need to update the certona tagging each time a different color is selected
 * or whenever an item gets added to the bag
 * 
 * @param item_id
 * @param color_id
 * @param event - determine if we should change the event property or if it's just a color change
 */ 
function updateCertonaTags(item_id, color_id, event)
{
    resx.itemid = item_id + "_" + color_id;
    if(event != 'add') resx.rrqs   = "ColorCode="+color_id;
    if(event == 'add') resx.event = "shopping+cart";
    certonaResx.run();
}

/////// 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;
    if(qty == '0')
        this.qty             = qty + 1;
    else
        this.qty             = qty;
    this.colors              = new Array();
    this.color_size          = new Array();
    this.defaults            = new Array();
    this.available           = new Array();
    this.available_confirmed = new Array();
    this.backorderable       = new Array();
    this.qty_on_order        = new Array();
    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;
    this.addToBagSuccess     = new YAHOO.util.CustomEvent("addToBagSuccess", this);
    this.changedColorEvent   = new YAHOO.util.CustomEvent("changedColorEvent", this);
    this.changedColorEvent.subscribe(this.postSelectColor, this);
}

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

SkuSelection.prototype.colorExists = function(color_id)
{
    for(var c in this.colors)
    {
        if(c == color_id)
        {
            return true;
        }
    }

    return false;
};

SkuSelection.prototype.addColor = function(color_id, color_name)
{
    //make sure not to duplicate colors
    if(!this.colorExists(color_id))
        this.colors[color_id] = color_name;
};

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 (typeof this.color_size[this.swatch_pad][this.color_id] != 'undefined'){
        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"] != 'undefined' && this.defaults["size"] != ""){
            sku_id = this.color_size[this.swatch_pad][this.color_id][this.defaults["size"]]['sku_id'];
        }
    }
    //By default the qty displayed in the combo box will be 9
    var qty = 9;
    //check if there is not enough qty available and if backorders isn't set.
    if(sku_id != "" && this.available[sku_id] < qty && !this.backorderable[sku_id]){
        qty = this.available[sku_id];
        this.current_sku_id = sku_id;
    }

    //if it is in backorder then check that there is  qty on order to allow backorder.
    if(sku_id != "" && this.backorderable[sku_id]){
//        if(this.available[sku_id] >0){
        if(Number(this.available[sku_id]) + Number(this.qty_on_order[sku_id]) < qty){
            qty = Number(this.available[sku_id]) + Number(this.qty_on_order[sku_id]);
        }
//        }else if(this.qty_on_order[sku_id] < qty) {
//            qty = this.qty_on_order[sku_id];
//        }

        if (qty < 0) 
        {
            qty = 0;
        }
    }


    var qtyCmb = this.getQtySelect();
    if(qtyCmb){
        while (qtyCmb.options.length > 1) qtyCmb.remove(1);

        //adding this condition since there might be combo box with default value
        // and the array indexes wont match
        if(qtyCmb.options[0].text.toLowerCase() != "qty")
        {
            //remove the first element, otherwise "1" will be duplicated
            qtyCmb.remove(0);
        }

        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;
};

var swatch_current_class;
var swatch_cont_current_class;
SkuSelection.prototype.overColor = function(color_id, swatch_pad){
    var swatch;
    var swatch_container;

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

    //draw border on swatch container
    if(typeof swatch_container != 'undefined'){
        swatch_cont_current_class = swatch_container.className;
        swatch_container.className = 'swatch_container swatch_container_selected';
    }

    //draw inside border on swatch
    if(typeof swatch  != 'undefined'){
        //get current class
        swatch_current_class = swatch.className;
        
        if((color_id+""=="001" && swatch.color_id+""=="001") || (color_id+""=="071" && swatch.color_id+""=="071"))
            swatch.className = 'swatch-white selected';
        else
            swatch.className = 'swatch selected';
    }

};

SkuSelection.prototype.outColor = function(color_id, swatch_pad){
    var swatch_container;
    var swatch;

    if ( (typeof swatch_pad != 'undefined') && this.line_id != swatch_pad ) 
    {
        swatch = document.getElementById('swatch_' + swatch_pad + '_' + color_id);
        swatch_container = document.getElementById('s_container_' + swatch_pad + '_' + color_id);
    }
    else 
    {
        swatch = document.getElementById('swatch_' + this.line_id + '_' + color_id);
        swatch_container = document.getElementById('s_container_' + this.line_id + '_' + color_id);
    }

    if(typeof swatch_container != 'undefined' && (typeof swatch_cont_current_class != 'undefined'))
        swatch_container.className = swatch_cont_current_class;

    if(typeof swatch  != 'undefined' && (typeof swatch_current_class  != 'undefined'))
        swatch.className = swatch_current_class;
};

SkuSelection.prototype.setColorCombo = function(selected_color_id) {
    var colorCmb = this.getColorSelect();
    if(colorCmb)
    {
        if (colorCmb.length > 0)
        {
            //empty combo to regenerate options
            while (colorCmb.options.length > 0) colorCmb.remove(0);
        }

        //add new options to combo
        var c_index = 0;
        var skip = false;
        for(var idx=0; idx < this.color_size.length; idx++){
            for(var i in this.color_size[idx])
            {
                skip = false;
                if (!isNaN(i) && this.colors[i])
                {
                    //avoid adding elements that aren't colors
                    //alert(colorCmb.options.length);
                    for(var index_cmb = 0; index_cmb < colorCmb.options.length; index_cmb ++){
                       // alert(colorCmb.options[index_cmb].value);
                        //alert(i);
                        if(colorCmb.options[index_cmb].text == this.colors[i]) skip = true;;
                    }
                    if(!skip){
                        addOption(colorCmb, this.colors[i], i);

                        if(i == selected_color_id)
                        {
                            colorCmb.selectedIndex = c_index;
                        }
                        c_index++;
                    }
                }
            }
        }

    }


};

SkuSelection.prototype.getColorSelect = function()
{
    var color_drop = YAHOO.util.Dom.get('color_id_' + this.line_id);
    if(color_drop == null || typeof color_drop == 'undefined')
        color_drop = YAHOO.util.Dom.get('color_id_0');
    return color_drop;
};

SkuSelection.prototype.selectColorInCombo = function(color_id, swatch_pad, rootNode){

    if(color_id){
        //if the user is selecting colors from the combo-box,
        //get the right swatchpad (color_swatchpad arrays is being initialized in the template)
        if(typeof rootNode != 'undefined')
            swatch_pad = color_swatchpad[rootNode][color_id]; 
        else
            swatch_pad = color_swatchpad[color_id];    
        this.selectColor(color_id, swatch_pad,rootNode); 


    }else
        this.setDefaults();
};

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

    //color_id=document.getElementById('color_select' + this.line_id).value;
    this.color_id  = color_id;
    if(this.getColorSelect() != null){
        this.getColorSelect().value = color_id;
    }else{
        return;
    }

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

    var swatch_container;
    // if the user is simply selecting from another swatch pad and not from
    // an "add another" line, show that selection
    if (this.line_id != swatch_pad) {
        swatch = document.getElementById('swatch_' + swatch_pad + '_' + color_id);
        swatch_container = document.getElementById('s_container_' + swatch_pad + '_' + color_id);
    } else {
        swatch = document.getElementById('swatch_' + this.line_id + '_' + color_id);
        swatch_container = document.getElementById('s_container_' + this.line_id + '_' + color_id);
    }
    
    var ddColor = this.getColorSelect();
    //in case the call is from the cart (dropdown box) ignore the swatch divs
    if(swatch!=null){
        if((color_id+""=="001" && swatch.color_id+""=="001") || (color_id+""=="071" && swatch.color_id+""=="071"))
            swatch.className = 'swatch-white selected';
        else
            swatch.className = 'swatch selected';

        if(typeof swatch_container != 'undefined')
        {
            //clear swatch_container selected
            var swatch_containers = YAHOO.util.Dom.getElementsByClassName('swatch_container_selected', 'div', rootNode);

            //alert(swatch_containers.length);
            for (var i = 0; i < swatch_containers.length; i++)
            {
                swatch_containers[i].className = 'swatch_container';
            }

            //select the one
            swatch_container.className = 'swatch_container swatch_container_selected';
            swatch_current_class = swatch.className;
            swatch_cont_current_class = swatch_container.className;
        }
    } else {
        for (var j  = 0; j < ddColor.length; j++ ) {
            if (ddColor.options[j].value == color_id) {
                ddColor.selectedIndex = j;
            }
        }
    }
    //update color combo
    this.setColorCombo(color_id);

    var ddSize = this.getSizeSelect();
    while (ddSize.options.length > 1) ddSize.remove(1);
    
    for (var size_id in this.color_size[this.swatch_pad][color_id])
    {
        if (typeof this.color_size[this.swatch_pad][color_id][size_id] != 'function'
        && (typeof this.color_size[this.swatch_pad][color_id][size_id] != 'undefined'))
        {
            addOption(ddSize, this.color_size[this.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;};
        var sizetextCont = document.getElementById("sizetextContainer_" + this.line_id);
        var sizedropCont = document.getElementById("sizedropContainer_" + this.line_id);
        if(sizetextCont) sizetextCont.style.display = 'none';
        if(sizedropCont) sizedropCont.style.display = 'none';
        //if the default size is set then set the correct quantities in QtyCombo
        this.setQtyCombo();
    }else {
        ddSize.style.display = 'inline';
    }

    //get the size before changing color so we can know if the size exist in new color. If it doesn't we need to reset the qty
    var old_size = this.size_id;
    this.selectSize(this.size_id);
    if(old_size != this.size_id){
        //the size was not in the new color.
        this.selectQty(this.qty);
        this.setQty(this.qty);
    }

    this.changePrice();
    this.replaceImg();

    // add param to links
    var img_link = document.getElementById('product_image_' + this.line_id);
    var desc_link = document.getElementById('product_title_' + this.line_id);
    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;
            }
        }
    }
    
    this.changedColorEvent.fire([color_id, swatch_pad, this]);
};

// changedColorEvent callback
SkuSelection.prototype.postSelectColor = function(type, args, me ) 
{
    var color_id = args[0][0];
    var swatch_pad = args[0][1];
    args[0][2].updateCrossSells(color_id);
};

SkuSelection.prototype.hideWaitingBar = function(element) {
    if (typeof element != 'undefined') {
        var elWaiting = YAHOO.util.Dom.get(element);
        elWaiting.style.visibility = 'hidden';
    }
};

SkuSelection.prototype.showWaitingBar = function(element) {
    if (typeof element != 'undefined') {
        var elWaiting = YAHOO.util.Dom.get(element);
        elWaiting.style.visibility = 'visible';
    }
};

SkuSelection.prototype.updateCrossSells = function(color_id) {

    if (typeof this.xsell_container != 'undefined')
    {

        this.showWaitingBar('waiting');

        outer_this = this;
        var postData = 'color_id=' + color_id +'&item_id=' + this.item_id;
        var callback = {
            success: function(o) {
                var attrib = {
                    height: {to: 425}
                };
                var element = skuSelect.xsell_container;
                var hdr = YAHOO.util.Dom.get('xsells_header');
                
                if (o.responseText.match(/item_thumb/i)
                    || o.responseText.length == 0)
                {
                    var anim = new YAHOO.util.Anim(element, {opacity: {to: 0}}, 0.5);

                    anim.onComplete.subscribe(function()
                    {
                        skuSelect.xsell_container.innerHTML = o.responseText;
                        var a = new YAHOO.util.Anim(element, {opacity: {to: 1}}, 0.5);
                        a.animate();
                        
                        if (o.responseText.match(/item_thumb/)) 
                        {
                            hdr.style.visibility = 'visible';
                        }
                    });

                    anim.animate();
                }

                skuSelect.hideWaitingBar('waiting');
            },
            failure: function (o) {
                outer_this.hideWaitingBar('waiting');
            }
        };

        YAHOO.util.Connect.asyncRequest(
            'POST',
            '/detail/xsells',
            callback,
            postData);
    };
};

SkuSelection.prototype.setCrossSellsElementId = function(name) {
    var el = document.getElementById(name);
    if (el) {
        this.xsell_container = el;
    }
};

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

SkuSelection.prototype.getQtySelect = function()
{
    var qty_select = YAHOO.util.Dom.get('qty_select_' + this.line_id);
    if(qty_select == null || typeof qty_select == 'undefined')
        qty_select = YAHOO.util.Dom.get('qty_select_0');
    return qty_select;
};

SkuSelection.prototype.getSizeSelect = function()
{
    var size_select = YAHOO.util.Dom.get('size_select_' + this.line_id);
    if(size_select == null || typeof size_select == 'undefined')
        size_select = YAHOO.util.Dom.get('size_select_0');
    return size_select;
};

SkuSelection.prototype.selectQty = function(qty) 
{
    var ddQty = this.getQtySelect();
    if(qty == '' || qty < 0)
    {
        qty = 0;
    }

    //adding this condition since there might be combo box with default value
    // and the array indexes wont match
    if(ddQty != null)
    {
        if(ddQty.options[0].text.toLowerCase() != 'qty' && qty > 0)
        {
            qty--;
        }

        ddQty.selectedIndex = qty;
        this.qty = ddQty.value;
    }
};

SkuSelection.prototype.setSize = function(size_id) {
    this.size_id = size_id;
    //qty only should be reset if SIZE is selected in the combo
    if(!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(rootNode) {
    this.selectColor(this.defaults['color'], this.line_id, rootNode);
    this.setColorCombo(this.defaults['color']);
    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 == null || typeof img.src == 'undefined' ) 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, 10);
    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, 10);
        var new_qty = qty + parseInt(existing.textContent, 10);
        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(hide_alert) {
    hide_alert = hide_alert || false;
    
    if ((!this.size_id && this.countProps(this.color_size[this.swatch_pad][this.color_id]) > 1) 
        || (parseInt(this.qty, 10) <= 0)
        || this.qty == '' ) 
    {
        var errTxt = "Please select the following:\r\n";
        errTxt += !this.size_id ? " - Size\r\n" : "";
        errTxt += !this.qty ?  " - Quantity\r\n" : "";

        if (!hide_alert)
        {
            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) ))
    {
        if (typeof this.available_confirmed[sku_id] == 'undefined'){
            if(this.backorderable[sku_id]){
                getPageOverlay('backorder_panel', 'We\'re sorry','/detail/backorderConfirm','300px');
            }
            return false;
        };
    }
    return true;
};

SkuSelection.prototype.backorderConfirmed = function() {
    var sku_id = this.color_size[this.swatch_pad][this.color_id][this.size_id]['sku_id'];
    this.available_confirmed[sku_id] = 1;
    my_sfcPanel.hide();
    displayJQCartAnimation();
};

SkuSelection.prototype.backorderCancel = function() {
    my_sfcPanel.hide();
};

SkuSelection.prototype.addToBag = function() 
{
    if (!this.checkSizeQty()) return;
    var sku_id = this.color_size[this.swatch_pad][this.color_id][this.size_id]['sku_id'];
    if ((this.backorderable[sku_id]) && !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
            try
            {
                var add_success = YAHOO.lang.JSON.parse(o.responseText);
                document.getElementById('shopping_bag_counter').innerHTML = add_success.item_count;

                var merch_total = document.getElementById('merch_subtotal');
                if (merch_total) 
                {
                    merch_total.innerHTML = add_success.item_price;
                }
                
                var hdr_subtotal = document.getElementById('hdr_subtotal');
                if (hdr_subtotal) 
                {
                    hdr_subtotal.innerHTML = '$' + add_success.subtotal;
                }
                
                outerThis.clearAddAnother();
                outerThis.addToBagSuccess.fire(add_success);
            }
            catch(e)
            {
                //we've requested more than the available qty
                var availableQty = o.responseText.match(/<span style="display: none;">(.*)<\/span>/i);
                sku_id = outerThis.color_size[outerThis.swatch_pad][outerThis.color_id][outerThis.size_id]['sku_id'];

                if(outerThis.backorderable[sku_id])
                {
                    outerThis.available[sku_id] = 0;
                    outerThis.qty_on_order[sku_id] = availableQty[1];
                } else {
                    outerThis.available[sku_id] = availableQty[1];
                }
                outerThis.setQtyCombo();
                outerThis.selectQty(availableQty[1]);
                outerThis.setQty(availableQty[1]);

                setTimeout(outerThis.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', 570, 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
    );
};

