function addOption(select_elem, label, value) {
    var opt = new Option(label, value);
    try {
        select_elem.add(opt, null); // standards compliant
    } catch(ex) {
        select_elem.add(opt); // IE only
    }
}

function showBackImage(id, link, item_id){
    var child = YAHOO.util.Dom.getElementsBy(function(el){return true;}, 'img', 'product_image'+id);
    var src = child[0].src;

    var color_id = global_color_id[id];
    var color_description = getColorDescription(color_id, document.getElementById('color_combo' +  id));

    if (link.innerHTML.indexOf('Back') >= 0 ) {
        var medium_img = document.getElementById('hidden_bmedium_' + item_id + '_' + color_id).value;
        var large_img = document.getElementById('hidden_blarge_' + item_id + '_' + color_id).value;

        var el = document.getElementById('swatch_' + color_id + '_' + id);

        if (medium_img == '' || large_img == '') { return; }
        else {
            link.innerHTML = 'Front';
        };
    } else {
        var medium_img = document.getElementById('hidden_medium_' + item_id + '_' + color_id).value;
        var large_img = document.getElementById('hidden_large_' + item_id + '_' + color_id).value;

        var el = document.getElementById('swatch_' + color_id + '_' + id);

        if (medium_img == '' || large_img == '') { return; }
        else {
            link.innerHTML = 'Back';
        };
    }

    selectColor(el, item_id, color_id, color_description, medium_img, large_img, id, true);
}

function selectColor(selected_el, item_id, color_id, color_description, medium_img, large_img, id, ignore_back_link) {
    ignore_back_link = ignore_back_link || false;
     var sUrl = '/detail/updateAddtlImages';
         var postData = "item=" + item_id + "&color=" + color_id + "&function_name=change_image&id=" + id;
         var callback = {
             success: function(o) {
                 document.getElementById('addtl_images_container'+id).innerHTML = o.responseText;
             }
         };
         YAHOO.util.Connect.asyncRequest('Post', sUrl, callback, postData);

    var swatches = document.getElementById("swatches"+id).childNodes;
    for (i in swatches) {
        if (swatches[i].firstChild) {
            swatches[i].firstChild.className = "";
        }
    }
    if(selected_el) { selected_el.firstChild.className = "selected"; };

    var combo = document.getElementById("color_combo"+id);
    combo.value = color_id;

    color_id_value[id] = color_id;

    var size = document.getElementById("size_select"+id);
    var old_size = size.value;

    while (size.length > 1) size.remove(1);

    var new_ids = Array();
    var new_options = Array();

    for (var size_id in color_size[id][color_id]) {
        if (color_size[id][color_id][size_id]['description']) {
            new_ids.push(size_id);
            new_options.push(color_size[id][color_id][size_id]['description']);
        }
    }

    for (var i=0; i < new_ids.length; i++) {
        addOption(size, new_options[i],new_ids[i]);
    };

    if (size.length == 2) {
        size.selectedIndex = 1;
    } else if (old_size) {
        size.value = old_size;
    } else {
        size.selectedIndex = 0;
    }

    document.getElementById('product_image'+id).firstChild.src = medium_img;
    if (document.getElementById('product_image'+id+'-big').firstChild){
        var child = YAHOO.util.Dom.getElementsBy(function(el){return true;}, 'img', 'product_image'+id+'-big');
        if(child[0]) {
            old_src = child[0].src;
            child[0].onerror = function() {this.src = old_src;};
            child[0].src = large_img;
        }
    }

    if (!ignore_back_link) {
        var has_back = document.getElementById('hidden_bmedium_' + item_id + '_' + color_id).value.length > 0;
        if (!has_back) {document.getElementById('link_back_' + id).innerHTML = '';}
        else {document.getElementById('link_back_' + id).innerHTML = 'Back';}
        //document.getElementById('simple_image'+id).src = large_img.replace(/large/, "medium");
    };
    selectSize(size.value, id);
    global_color_id[id] = color_id;
} // function

function change_image(new_image, id) {
    new_image = new_image.replace(/small/, "large");
    new_image = new_image.replace(/png$/, "jpg");
    document.getElementById('product_image'+id).firstChild.src = new_image;
    var child = YAHOO.util.Dom.getElementsBy(function(el){return true;}, 'img', 'product_image'+id+'-big');
    child[0].src = new_image;
}

function getColorDescription (color_id, combo) {
    combo = combo || document.getElementById('color_combo1');

    var options = combo.options;
    for (var i=0; i < options.length; i++) {
        if (options[i].value == combo.value) {
            return options[i].text;
        };
    };

    return null;
}

function changeColorFromCombo (combo, id, item_id) {
    var color_id = combo.value;
    var swatch_name = "swatch_" + color_id + "_" + id;

    var color_description = getColorDescription(color_id, combo);

    var medium_img = document.getElementById('hidden_medium_' + item_id + '_' + color_id).value;
    var large_img = document.getElementById('hidden_large_' + item_id + '_' + color_id).value;

    selectColor(document.getElementById("swatch_" + color_id + "_" + id),
                item_id,
                color_id,
                color_description,
                medium_img,
                large_img,
                id);
}

function selectColorFromCombo(selected_el, item_id, color_id, color_description, medium_img, large_img, id) {
    medium_img = medium_img.replace(/_\d{3}(_BACK|_FRONT)*\.jpg/, "_"+color_id+"$1.jpg");
    large_img = large_img.replace(/_\d{3}(_BACK|_FRONT)*\.jpg/, "_"+color_id+"$1.jpg");
    selectColor(document.getElementById("swatch_"+color_id+"_"+id), item_id, color_id, color_description, medium_img, large_img, id);
}

function togglePresell(item_id, color_id, size_id) {
    var div = document.getElementById('presell_msg');
    var spn = document.getElementById('presell_dt');

    if ( color_size[item_id][color_id][size_id]['presell'] != '' ) {
        spn.innerHTML = color_size[item_id][color_id][size_id]['presell'];
        div.style.display = "block";
    } else {
        div.style.display = "none";
    }
}

function selectSize(size_id, id) {
    var qty =  document.getElementById("qty_select"+id);
    var old_qty = qty.value;

    while (qty.length > 1) qty.remove(1);

    if (color_size[id][color_id_value[id]][size_id])
    {
        var max_qty = color_size[id][color_id_value[id]][size_id]['quantity'];
        if (max_qty > 9) max_qty = 9;
        for (var i=2; i<=max_qty; i++) {
            addOption(qty, ''+i, ''+i);
        }
        if (old_qty > 1) {
            qty.value = old_qty;
            if (qty.value < old_qty) {
                qty.selectedIndex = qty.length - 1;
            }
        } else {
            qty.selectedIndex = 0;
        }

        selectPrice(color_size[id][color_id_value[id]][size_id], id);
    }
    else
    {
        for (var _size_id in color_size[id][color_id_value[id]]) {
            if (color_size[id][color_id_value[id]][_size_id]['price']) {
                selectPrice(color_size[id][color_id_value[id]][_size_id], id);
            }
        }
    }

    togglePresell(id, color_id_value[id], size_id);

    var borrar = 0;
}

function selectPrice(a, id) {
    var e;
    e = document.getElementById('display_price'+id);
    if (e) e.innerHTML = a['price'];
    e = document.getElementById('display_sale_price'+id);
    if (e) e.innerHTML = a['sale_price'];
}

function selectFirstColor(id) {
    elem = document.getElementById("swatches"+id).childNodes[0];
    if (elem && elem.onclick) return elem.onclick();
    elem = document.getElementById("swatches"+id).childNodes[1];
    if (elem && elem.onclick) return elem.onclick();
    elem = document.getElementById("color_combo"+id);
    if (elem && elem.onchange) return elem.onchange();

}

function popup_sizechart() {
    var w = window.open("/popups/size.html");
    //w.document.write('');
    //<body topmargin="0" leftmargin="0">
    //
    //');
}

function swap_zooms() {
    var a = document.getElementById("zoom_image");
    var b = document.getElementById("alt_image");
    var c = a.src;
    a.src = b.src;
    b.src = c;
}

// function hideDetails(id) {
//     var a = document.getElementById("product_description"+id);
//     a.className = "hidden";
//     var b = document.getElementById("hide_show"+id);
//     b.innerHTML = '<a href="#" onclick="showDetails('+id+');return false;">Show Details</a>';
//     var c = document.getElementById("addtl_images_container"+id);
//     c.className = "hidden";
// }

// function showDetails(id) {
//     var a = document.getElementById("product_description"+id);
//     a.className = "";
//     var b = document.getElementById("hide_show"+id);
//     b.innerHTML = '<a href="#" onclick="hideDetails('+id+');return false;">Hide Details</a>';
//     var c = document.getElementById("addtl_images_container"+id);
//     c.className = "";
// }

function prepareZoom(id) {
    document.getElementById('product_image'+id+'-big').style.visibility = 'visible';
    var xy = YAHOO.util.Dom.getXY('hdr_' + id);
    YAHOO.util.Dom.setXY('product_image' + id + '-big', xy);
}

function hideZoom(id) {
    document.getElementById('product_image'+id+'-big').style.visibility = 'hidden';
}

function hideDetails(id){
    document.getElementById('qz_container'+id).style.display = 'none';
    document.getElementById('hidden_details_img'+id).style.display = '';
    document.getElementById('adttl_info'+id).style.display = 'none';
    document.getElementById('hide_details'+id).style.display = 'none';
    document.getElementById('show_details'+id).style.display = '';
}

function showDetails(id){
    showOnlyThisDetails(id);
    document.getElementById('qz_container'+id).style.display = '';
    document.getElementById('hidden_details_img'+id).style.display = 'none';
    document.getElementById('adttl_info'+id).style.display = '';
    document.getElementById('hide_details'+id).style.display = '';
    document.getElementById('show_details'+id).style.display = 'none';
}

function showOnlyThisDetails(id){
    for(var i=1;i<global_color_id.length;i++)
    {
        if( i != id )
        {
             hideDetails(i);
        }
    }
}

function removeZooms(item_id, remove, main_item, event) {
    var id = parseInt(nb_items, 10);
    var next_id = id + 1;
    var evt = event || window.event;
    var cell = evt.target || evt.srcElement;
    while(cell.tagName != 'TD')
        cell = cell.parentNode;

    var nCell = cell.nextSibling;
    while(nCell.nodeType != '1')
        nCell = nCell.nextSibling;

    var pCell = cell.previousSibling;
    while(pCell.nodeType != '1')
        pCell = pCell.previousSibling;

    var nCell_val = nCell.firstChild.nodeValue.replace(/[\n ]/g,'');
    var pCell_val = pCell.firstChild.nodeValue.replace(/[\n ]/g,'');

    cell.parentNode.removeChild(cell);

    switch(nCell_val){
        case '+':
            nCell.parentNode.removeChild(nCell);
        break;
        case '}':
            if(pCell_val == '+')
                pCell.parentNode.removeChild(pCell);
            else if(pCell_val == '{'){
                // CTO EMPTY. We keep it to insert the last product container
                document.getElementById('cto_container').innerHTML = '';
            }
        break;
    }

    MagicZoom_stopZooms();
    for(var i=1; i<=id; i++){
        document.getElementById('product_image'+i+'-big').innerHTML = '';
        var zooms = YAHOO.util.Dom.getElementsByClassName('MagicZoomPup', 'div', 'product_image'+i);
        document.getElementById('product_image'+i).removeChild(zooms[0]);
    }

    var postData1 = "item=" + item_id + "&id=" + next_id;
    var callback1 = {
        success: function(o) {
            var cto_container = document.getElementById('cto_container');
            var new_container = document.createElement("DIV");
            new_container.id = 'product_detail_container'+next_id;
            new_container.className = 'product_container';
            new_container.innerHTML = o.responseText;
            cto_container.parentNode.insertBefore(new_container, cto_container);

            //execute zooms. Prevent for double execution of Zooms
            var reg = new RegExp("Firefox");
            if(!reg.test(navigator.userAgent)){
                var script = document.getElementById("color_size_script" + next_id);
                eval(script.innerHTML);
            }
            nb_items++;
        },
        failure: function(o){
            alert('error while executing CTO');
        }
    };
    YAHOO.util.Connect.asyncRequest('POST', '/detail/ctoItem', callback1, postData1);
}

function restoreZooms(id) {
    for(i=1; i<=id; i++){
        var child = YAHOO.util.Dom.getElementsBy(function(el){return true;}, 'img', 'product_image'+i+'-big');
        img = child[0].src;
        img = img.replace(/_\d{3}\.jpg/, "_"+global_color_id[i]+".jpg");
        child[0].src = img;
    }
}

  /* Next and previous buttons */
    function setNextItem(item) {
        next_item = item;
    }

    function setPrevItem(item) {
        prev_item = item;
    }

// send item to a friend by email
function showSendDetails (item_id, color) {
    var callback = {
        success: function(o) {
            send_details = new YAHOO.widget.Panel("send_details", {
                width:"690px",
                fixedcenter: false,
                x: (document.body.clientWidth - 690)/2,
                y: 115,
                constraintoviewport: false,
                underlay:"shadow",
                close:false,
                visible:false,
                draggable:false,
                iframe:false,
                modal:true
            });

            send_details.setBody(o.responseText);

            send_details.render(document.body);
            if (typeof quickViewPanel != 'undefined') {
                quickViewPanel.setBody('');
                hide_objects();
                quickViewPanel.hide();
            };
            send_details.show();
        },
        failure: function (o) {}
    };

    YAHOO.util.Connect.asyncRequest(
        'POST',
        '/detail/sendDetailsToFriend/' + item_id,
        callback,
        'item=' + item_id + '&color=' + color
    );
}

function sendDetails() {
    var item            = document.getElementById('item').value;
    var color           = document.getElementById('color').value;
    var from_name       = document.getElementById('from_name').value;
    var from_mail       = document.getElementById('from_mail').value;
    var to_name         = document.getElementById('to_name').value;
    var to_mail         = document.getElementById('to_mail').value;
    var message_content = document.getElementById('message').value;

    if (!from_mail || !to_mail || !from_name || !to_name){
        alert("Please fill in all the information");
        return;
    }

    var sUrl = '/detail/email';
    var postData = "item=" + item + "&color=" + color +"&from_name=" + from_name + "&from_mail=" + from_mail + "&to_name=" + to_name
                 + "&to_mail=" + to_mail + "&message_content=" + message_content;

    var callback = {
        success: function(o) {
            send_details.hide();
            alert('Your mail has been sent');
        },
        failure: function(o) {
            alert('Oops there was a problem sending the mail');
        }
    };

    YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);

}

function showPrintDetails (item_id, color) {
    var callback = {
        success: function(o) {
            print_details = new YAHOO.widget.Panel("print_details", {
                width:"480px",
                height:"579px",
                fixedcenter: false,
                x: (document.body.clientWidth - 480)/2,
                y: 115,
                constraintoviewport: false,
                underlay:"shadow",
                close:false,
                visible:false,
                draggable:false,
                iframe:true,
                modal:true
            });

            print_details.setBody(o.responseText);

            print_details.render(document.body);
            if (typeof quickViewPanel != 'undefined') {
                quickViewPanel.setBody('');
                quickViewPanel.hide();
            };
            print_details.show();
        },
        failure: function (o) {}
    };

    YAHOO.util.Connect.asyncRequest(
        'POST',
        '/detail/printItem',
        callback,
        'item=' + item_id + '&color=' + color
    );
}


function printDiv (id) {
    var a = window.open('','','width=640px,height=600px,resizable=true');
    a.document.open("text/html");
    a.document.write('<html><head><link rel="stylesheet" media="all" type="text/css" href="/css/product_detail.css" /></head><body>');
    a.document.write('<div style="width: 440px">');
    a.document.write('a');
    a.document.write('</div></body></html>');
    a.print();
}

function displayLargeImages (item_id, id) {
    var postData = "color_id=" + document.getElementById('color_' + id).value
                 + "&item_id=" + item_id;

    var callback = {
        success: function(o) {
            eval('var arr =' + o.responseText);
            largeImages = new YAHOO.widget.Dialog("large_images", {
                width:"400px",
                fixedcenter: 'contained',
                constraintoviewport: true,
                underlay:"shadow",
                close:true,
                visible:false,
                draggable:true,
                modal:true,
                effect: {effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25}
            });
            largeImages.setHeader(arr.title);
            largeImages.setBody(arr.image);
            largeImages.render(document.body);
            largeImages.show();

        },
        failure: function (o) {}
    };

    YAHOO.util.Connect.asyncRequest(
        'POST',
        '/detail/getLargeImages',
        callback,
        postData);
}

function displayTermsAndConditions (emf_domain_url)
{
    var postData = "";
    var callback = {
        success: function(o)
        {
            var content = o.responseText;

            panelTermsAndConditions = new YAHOO.widget.Panel("terms",
            {
                visible:false,
                underlay:"shadow",
        	draggable:true,
                fixedcenter:true,
                constraintoviewport: true,
                close:false,
        	modal:true,
                width: '500px',
                height: '450px',
                effect: {effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25}
            }
            );
            panelTermsAndConditions.setHeader("<H2>Service Plan Options:</H2>");
            panelTermsAndConditions.setBody('<div>'+content+'</div>');
            panelTermsAndConditions.setFooter('<a onclick="panelTermsAndConditions.destroy();return false;" href="#">[X] Close</a>');
            panelTermsAndConditions.render(document.body);
            panelTermsAndConditions.render();
            panelTermsAndConditions.show();

        },
        failure: function (o) {}
    };

    YAHOO.util.Connect.asyncRequest(
        'POST',
        '/static/whatIsThis',
        callback,
        postData);


}
