﻿//global variables
var attribSectionID = 'visualAttributes';
var attribContainerClass = 'visualContainer';
var attribIDPrefix = 'attrib';
var attribTagType = 'input';
var selectedClassName = 'select';
var inactiveClassName = 'inactive';
var hoverClassName = 'hover';
var attribState;
var attribStateIdentify;
var attribStateClassName;
var previousVariantImage;



//- vibe 20110902 add fix bug	
function Variant(ID, Inventory, Price, Image, Name, Description) {
    this.ID = ID;
    this.Inventory = Inventory;
    this.Price = Price;
    this.Image = Image;
    this.Name = Name;
    this.Description = Description;
}

//save the state of every control before hover
function SaveState() {

    attribStateIdentify = new Array();
    attribStateClassName = new Array();
    var AllInput = $("#" + attribSectionID + " " + attribTagType);
    for (var i = 0; i < AllInput.length; i++) {
        if (AllInput[i].type == "button" || AllInput[i].type == "image") {
            attribStateIdentify.push(AllInput[i].id);
            attribStateClassName.push(AllInput[i].className);
        }
    }
}

//restore the state of controls after mouse out
function RestoreState() {
    if (attribStateIdentify != null) {
        for (var i = 0; i < attribStateIdentify.length; i++) {
            document.getElementById(attribStateIdentify[i]).className = attribStateClassName[i];

        }
    }
}




//called from onmouseover event
function Hover(elem) {
    //store the current state
    SaveState();

    //get the element being hovered over as a Jquery.js element
    var pElem = $("#" + elem.id);

    //if this attribute has a swatch image, show it.
    if (pElem.attr("type") == "image") {
        showSwatchImage(elem.id);
    }

    //if the element is active, add the hover class to the element
    if (!pElem.hasClass(inactiveClassName)) {
        pElem.addClass(hoverClassName);
    }

    //show the other attributes that can be selected with the current attribute
    ShowValidCombosForHover(pElem);
}


//change medium image to swatch image 
function showSwatchImage(id) {
    var medium = $("#" + id + "SwatchM");
    var large = $("#" + id + "SwatchL");
    if (medium.length > 0) {

        previousVariantImage = $('#variantImage').attr("innerHTML");
        if (large.length > 0) {
            $('#variantImage').attr({ innerHTML: '<img style="cursor:pointer" onClick="popupimg(\'' + large.val() + '\')" src="' + medium.val() + '" />' });
        }
        else {
            $('#variantImage').attr({ innerHTML: '<img src="' + medium.val() + '" />' });
        }
    }

}

//when mouse out, restore the medium image
function RestoreSwatchImage(id) {
    var medium = $("#" + id + "SwatchM");
    if (medium.length > 0) {
        $('#variantImage').attr({ innerHTML: previousVariantImage });
    }
}

//called from onmouseout event
function Off(elem) {
    //get the element that was just 'moused out' as a as a Jquery.js element
    var pElem = $("#" + elem.id);

    //remove the hover class from the element
    pElem.removeClass(hoverClassName);

    if (!pElem.hasClass(selectedClassName)) {
        //if the element that was being hovered over was not selected, 
        //simply restore the state to what it was before the hover action
        //this logic is simpler than having to run through the select logic again
        RestoreState();
        if (pElem.attr("type") == "image") {
            RestoreSwatchImage(elem.id);
        }
    }
    else {
        //otherwise, the hover item was actually selected, so now need to show the valid items
        ShowValidCombosForSelect(GetSelectedAttributes());
    }

}

//called from onclick event
function Select(elem) {

    //get the element being hovered over as a Jquery.js element
    var pElem = $("#" + elem.id);

    var ErrorInfo = $('#errorInfo');
    ErrorInfo.hide();


    //if the element has the hover class then remove it
    if (pElem.hasClass(hoverClassName)) {
        pElem.removeClass(hoverClassName);
    }



    //remove the 'selected' class from all siblings of the currently selected element
    //the logic is that you can only select one attribute from each attributeContainer
    pElem.siblings().each(function() {
        $(this).removeClass(selectedClassName);
    });

    //add the 'selected' class to the currently selected element
    pElem.addClass(selectedClassName);

    var attribSelectName = pElem.parent().prev(".attribSelectName");
    if (attribSelectName != null) {
        attribSelectName.attr({ innerHTML: "&#160;&#160;" + GetAttributeName(pElem) });
    }

    var selectedAttributes = GetSelectedAttributes();

    var variantAttributesText = '';
    for (var i = 0; i < selectedAttributes.length; i++) {

        variantAttributesText += GetAttributeName($(selectedAttributes[i]));
        if (i < selectedAttributes.length - 1) {
            variantAttributesText += ',';
        }
    }



    if (selectedAttributes.length == NumAttributeSections) {
        ShowVariantInfo(selectedAttributes, ProductID);
    }
    showAttributesMapImage(variantAttributesText);
    ShowValidCombosForSelect(selectedAttributes);
}

// show all the valid attribute combination when mouse hover
function ShowValidCombosForHover(hoverAttribute) {
    //extract the numbered ID of the attribute being hovered over	
    var hoverAttributeID = hoverAttribute.attr("id").replace(attribIDPrefix, '');

    var validIDs = new Array();

    //get an array of ALL the combos that the hovered attribute belongs to
    //this array contains IDs of attributes that need to be 'activated'
    for (var i = 0, len = ValidCombos.length; i < len; i++) {
        var combo = ValidCombos[i].split(',');
        if (ArrayContains(combo, hoverAttributeID) != -1) {
            validIDs = validIDs.concat(combo);
        }
    }

    var siblings = hoverAttribute.siblings();
    //loop through every attribute in the Attributes container
    $("#" + attribSectionID + " " + attribTagType).each(function() {
        //extract the numbered ID of the element currently being iterated through
        var iteratedAttributeID = $(this).attr("id").replace(attribIDPrefix, '');
        if (ArrayContains(validIDs, iteratedAttributeID) == -1) {
            $(this).addClass(inactiveClassName);
        }
        else {
            $(this).removeClass(inactiveClassName);
        }

    });
}

//if the array contains the hoverAttributeID return index,
//else return -1
function ArrayContains(array, hoverAttributeID) {
    for (var i = 0, len = array.length; i < array.length; i++) {
        if (array[i] == hoverAttributeID) {
            return i;
        }
    }
    return -1;
}

//if the array contains the object hoverAttribute return index,
//else return -1
function ArrayContainsObject(array, hoverAttribute) {
    for (var i = 0, len = array.length; i < array.length; i++) {
        if (array[i].id == hoverAttribute.id) {

            return i;
        }
    }
    return -1;
}


// show all the valid attributes combination after mouse click
function ShowValidCombosForSelect(selectedAttributes) {

    if (selectedAttributes.length > 0) {
        if (selectedAttributes.length > 1) {

            //loop through every attribute in the Attributes container
            $("#" + attribSectionID + " " + attribTagType).each(function() {
                //extract the numbered ID of the element currently being iterated through
                $(this).addClass(inactiveClassName);

            });
        }
        else {
            $("#" + attribSectionID + " " + attribTagType).each(function() {
                if (ArrayContainsObject($(selectedAttributes[0]).siblings(), this) == -1) {
                    $(this).addClass(inactiveClassName);
                }
            });
        }


        //loop through all valid combos
        //	if the combo does not contain ALL of the selectedAttributes 
        //		then parse the combo and 'inactivate' the elements in that combo
        var selectedAttributeIDs = GetSelectedAttributesID();

        var validIDs = new Array();

        for (var j = 0, len = ValidCombos.length; j < len; j++) {
            var combo = ValidCombos[j].split(',');
            var flag = true;
            var selectedAttributeIDslen = selectedAttributeIDs.length;
            for (var i = 0; i < selectedAttributeIDslen; i++) {
                if (ArrayContains(combo, selectedAttributeIDs[i]) == -1) {
                    flag = false;
                }
            }

            if (flag) {
                validIDs = validIDs.concat(combo);
            }
        }

        if (validIDs.length > 0) {
            var validIDsLen = validIDs.length;
            for (var i = 0; i < validIDsLen; i++) {
                $("#" + attribIDPrefix + validIDs[i]).removeClass(inactiveClassName);
            }
        }
    }
    else {
        //this should occur when the Off method is invoked and no items are selected
        Reactivate();
    }

}

//remove the inactive class from all attribute elements
function Reactivate() {
    //loop through every attribute in the Attributes container
    $("#" + attribSectionID + " " + attribTagType).each(function() {
        //extract the numbered ID of the element currently being iterated through
        $(this).removeClass(inactiveClassName);

    });

}


//clear all the selections and displayed info
function clearSelection() {

    $("#" + attribSectionID + " " + attribTagType).each(function() {
        //extract the numbered ID of the element currently being iterated through
        $(this).removeClass(inactiveClassName);
        $(this).removeClass(selectedClassName);
    });

    var addToCartButton = $('#addToCartButton');
    //var addToWishButton = $('#addToWishButton');
    var availability = $('#availability');
    var price = $('#variantPrice');
    var variantAttributesList = $('#variantAttributes');
    $("#" + attribSectionID + " .attribSelectName").each(function() {
        $(this).attr({ innerHTML: '' });
    });
    if ($("#DDHideAddToCart").val() == 1) {
        addToCartButton.hide();
    }
    availability.hide();
    if ($("#DDHidePrice").val() == 1) {
        price.hide();
    }
    variantAttributesList.html("&nbsp;");
    $('#variantName').hide();
    $('#variantDesc').hide();
    var medium = $('#DefaultImage');
    var large = $('#DefaultLargeImage');
    if (large.length > 0) {
        $('#variantImage').attr({ innerHTML: '<img id="ProductPic" style="cursor:pointer" onClick="popupimg(\'' + large.val() + '\')" src="' + medium.val() + '" />' });
    }
    else {
        $('#variantImage').attr({ innerHTML: '<img id="ProductPic" src="' + medium.val() + '" />' });
    }


}


//get an array of the selected attribute 
function GetSelectedAttributes() {

    return $("#" + attribSectionID + " ." + selectedClassName);
}


//get an array of the selected attribute IDs
function GetSelectedAttributesID() {
    var SelectedAttributes = new Array();

    $("#" + attribSectionID + " ." + selectedClassName).each(function() {
        SelectedAttributes.push($(this).attr("id").replace(attribIDPrefix, ''));
    });
    return SelectedAttributes;
}


//get the name of attribute
function GetAttributeName(element) {
    var elementName = '';
    if (element != null) {
        if (element.hasClass('attribImage')) {
            elementName = element.attr('alt');
        }
        else if (element.hasClass('attribButton')) {
            elementName = element.attr('value');
        }
    }
    return elementName;
}


//after all the selections are made, show the variant info
function ShowVariantInfo(selectedAttributes, productID) {
    var attributeIDs = GetSelectedAttributesID();

    //generate a list of the selected attributes and display the list
    var variantAttributesList = $('#variantAttributes');
    var variantAttributesText = '';
    for (var i = 0; i < selectedAttributes.length; i++) {

        variantAttributesText += GetAttributeName($(selectedAttributes[i]));
        if (i < selectedAttributes.length - 1) {
            variantAttributesText += ',&#160;';
        }
    }
    variantAttributesList.attr({ innerHTML: variantAttributesText });
    //show variant pricing, availability and add to cart button
    if (attributeIDs != null && attributeIDs.length > 0) {
        attributeIDs = attributeIDs.sort(sortNumber);

        var addToCartButton = $('#addToCartButton');
        //var addToWishButton = $('#addToWishButton');
        var availability = $('#availability');
        var variantID = $('#VariantID');
        var price = $('#variantPrice');

        var comboIndex = ArrayContains(ValidCombos, attributeIDs.join(','));

        if (comboIndex != -1) {
            var variant = Variants[comboIndex];

            var variantImage = variant.Image;
            if (variantImage.indexOf('nopicture') == -1) {
                $('#variantImage').attr({ innerHTML: unescapeHTML(variantImage) });
                var allImageDiv = $("#variantMultiImages  div");
                for (var i = 0; i < allImageDiv.length; i++) {
                    $(allImageDiv[i]).hide();
                }
                $('#VariantsImagesDiv' + variant.ID).show();
            }

            if (variant.Inventory > 0) {
                variantID.attr({ value: variant.ID });
                addToCartButton.show();
                //addToWishButton.show();
                price.html(unescapeHTML(variant.Price));
                price.show();
                availability.attr({ innerHTML: "" });
            }
            else {
                if ($("#ShowAddToCartOnNoStock").val() > 0) {
                    variantID.attr({ value: variant.ID });
                    addToCartButton.show();
                    //addToWishButton.show();
                    price.html(unescapeHTML(variant.Price));
                    price.show();
                    availability.attr({ innerHTML: "" });
                }
                else {

                    if ($("#DDHideAddToCart").val() == 1) {
                        addToCartButton.hide();
                    }
                    //if ($("#DDHideAddToWish").val() == 1) {
                    //    addToWishButton.hide();
                    //}

                    if ($("#DDHidePrice").val() == 1) {
                        price.hide();
                    }
                    availability.attr({ innerHTML: $("#outStock").val() });
                }
            }
            ShowVariantNameAndDesc();
        }
        else {
            if ($("#DDHideAddToCart").val() == 1) {
                addToCartButton.hide();
            }
            //if ($("#DDHideAddToWish").val() == 1) {
            //    addToWishButton.hide();
            //}

            if ($("#DDHidePrice").val() == 1) {
                price.hide();
            }
            availability.attr({ innerHTML: $("#notAvail").val() });
            $('#variantName').hide();
            $('#variantDesc').hide();

            //vibe 20110902 add fix bug
            $('#InStockMessage').hide();
            $('#OutStockMessage').hide();
    
        }
        availability.show();
    }
}

//transfer the escape character to HTML tag
function unescapeHTML(str) {
    str = String(str).replace(/&gt;/g, '>').
    replace(/&lt;/g, '<').
    replace(/&quot;/g, '"').
    replace(/&amp;/g, '&');
    return str;
}

function sortNumber(a, b) {
    return a - b;
}


//ajax add to cart function for visual version 
function AddToCartAjax() {

    var ErrorInfo = $('#errorInfo');
    var availability = $('#availability');
    ErrorInfo.hide();
    var attributeIDs = GetSelectedAttributesID();
    if (attributeIDs.length < NumAttributeSections) {
        ErrorInfo.attr({ innerHTML: $('#makeSelections').val() });
        ErrorInfo.show();
        return;
    }
    if (availability.attr("innerHTML").length > 1) {

        ErrorInfo.attr({ innerHTML: availability.attr("innerHTML") });
        ErrorInfo.show();
        availability.hide();
        return;
    }

    if ($("#Quantity").val() > 0) {
        var ajaxurl = "ajaxAddToCart.aspx";
        var para = '&ProductID=' + $('#ProductID')[0].value + '&VariantID=' + $('#VariantID')[0].value + '&Quantity=' + $('#Quantity')[0].value;
        myajax(ajaxurl, para);
    }
    else {
        ErrorInfo.attr({ innerHTML: $('#enterQuantity').val() });
        ErrorInfo.show();
    }
}

//add to cart function for visual version 
function AddToCart() {
    var ErrorInfo = $('#errorInfo');
    var availability = $('#availability');
    ErrorInfo.hide();

    var attributeIDs = GetSelectedAttributesID();
    if (attributeIDs.length < NumAttributeSections) {
        ErrorInfo.attr({ innerHTML: $('#makeSelections').val() });
        ErrorInfo.show();
        return;
    }
    if (availability.attr("innerHTML").length > 1) {

        ErrorInfo.attr({ innerHTML: availability.attr("innerHTML") });
        ErrorInfo.show();
        availability.hide();
        return;
    }
    if ($("#Quantity").val() > 0) {
        document.AddToCartForm.submit();
    }
    else {
        ErrorInfo.attr({ innerHTML: $('#enterQuantity').val() });
        ErrorInfo.show();
    }
}

//ajax add to cart function for dropdown version.
function DDAddToCartAjax() {

    var ErrorInfo = $('#errorInfo');
    ErrorInfo.hide();

    var istartID = 1;
    while ($("#attributeGroup" + istartID).length > 0) {
        if ($("#attributeGroup" + istartID).val() == "parentAttr") {
            ErrorInfo.attr({ innerHTML: $('#makeSelections').val() });
            ErrorInfo.show();
            return;
        }
        istartID++;
    }

    if ($("#Quantity").val() > 0) {
        var ajaxurl = "ajaxAddToCart.aspx";
        var para = '&ProductID=' + $('#ProductID')[0].value + '&VariantID=' + $('#VariantID')[0].value + '&Quantity=' + $('#Quantity')[0].value;
        myajax(ajaxurl, para);
    }
    else {
        ErrorInfo.attr({ innerHTML: $('#enterQuantity').val() });
        ErrorInfo.show();
    }
}


//add to cart function for dropdown version.
function DDAddToCart() {
    var ErrorInfo = $('#errorInfo');
    ErrorInfo.hide();

    var istartID = 1;
    while ($("#attributeGroup" + istartID).length > 0) {
        if ($("#attributeGroup" + istartID).val() == "parentAttr") {
            ErrorInfo.attr({ innerHTML: $('#makeSelections').val() });
            ErrorInfo.show();
            return;
        }
        istartID++;
    }

    if ($("#Quantity").val() > 0) {
        document.AddToCartForm.submit();
    }
    else {
        ErrorInfo.attr({ innerHTML: $('#enterQuantity').val() });
        ErrorInfo.show();
    }
}
//add to wishlist function for dropdown version.
//function DDAddToWish() {
//    var ErrorInfo = $('#errorInfo');
//    ErrorInfo.hide();

//    var istartID = 1;
//    while ($("#attributeGroup" + istartID).length > 0) {
//        if ($("#attributeGroup" + istartID).val() == "parentAttr") {
//            ErrorInfo.attr({ innerHTML: $('#makeSelections').val() });
//            ErrorInfo.show();
//            return;
//        }
//        istartID++;
//    }

//    if ($("#Quantity").val() > 0) {
//        document.AddToWishForm.submit();
//    }
//    else {
//        ErrorInfo.attr({ innerHTML: $('#enterQuantity').val() });
//        ErrorInfo.show();
//    }
//}

function myajax(ajaxurl, para) {
    $('#miniCart').show();
    $('#miniCart').html('<div id="MiniCartLoading"><img src="images/spinner.gif" alt="Loading..." style="vertical-align:middle;" /> <strong>Adding item to cart...</strong></div>')

    $.ajax({
        url: ajaxurl,
        type: 'POST',
        dataType: 'html',
        timeout: 20000,
        data: para,
        error: function() { },
        success: function(html) {
            //the logic after success
            $('#miniCart').html(html);
            $('#numCartItems').attr({ innerHTML: $('#itemsCount').attr("innerHTML") });


        }
    });
}

function showAttributesMapImage(selectedAttributes) {
    if (selectedAttributes.length == 0)
        return;
    $('#productMultiImages').hide();
    var hiddenDrop = document.getElementById("attributesMapDD");
    if (hiddenDrop == null)
        return;

    for (var i = 0; i < hiddenDrop.options.length; i++) {
        var text = hiddenDrop.options[i].text;
        var variantID = hiddenDrop.options[i].value;

        if (selectedAttributes.toString() == text) {

            var variant = GetVariantByID(variantID);
            var variantImage = variant.Image;
            $('#variantImage').html(unescapeHTML(variantImage));
            var allImageDiv = $("#variantMultiImages  div");
            for (var i = 0; i < allImageDiv.length; i++) {
                $(allImageDiv[i]).hide();
            }
            $('#VariantsImagesDiv' + variant.ID).show();
            return;
        }
    }
    //     if($('#AutoFindImage').val() == 1)
    //     {
    //     var attributeIDs = DropDownGetSelectedAttr(NumAttributeSections+1);
    //         for (var i = 0, len = ValidCombos.length; i < ValidCombos.length; i++)
    //	    {
    //             if(ArrayIsInArray(attributeIDs, ValidCombos[i].split(",")) >0)
    //             {
    //               var variant = Variants[i];
    //               var variantImage = variant.Image;
    //               $('#variantImage').attr({innerHTML:unescapeHTML(variantImage)});
    //               var allImageDiv = $("#variantMultiImages  div");
    //	            for(var i=0;i<allImageDiv.length;i++)
    //                 {
    //                     $(allImageDiv[i]).hide(); 
    //                 }
    //                $('#VariantsImagesDiv' +variant.ID).show();
    //               return;
    //             }
    //	     }
    //        }

}


function GetVariantByID(variantID) {
    for (var i = 0; i < Variants.length; i++) {
        if (Variants[i].ID == variantID) {
            return Variants[i];
        }
    }

}

function ArrayIsInArray(arrayChild, array) {
    for (var i = 0, len = arrayChild.length; i < arrayChild.length; i++) {
        if (ArrayContains(array, arrayChild[i]) == -1) {
            return -1;
        }
    }
    return 1;
}


//called from onchange event
function DropDownChange(elem) {

    var pElem = $("#" + elem.id);
    var ErrorInfo = $('#errorInfo');
    ErrorInfo.hide();
    var nextID = elem.id.replace('attributeGroup', '');
    $('#variantName').hide();
    $('#variantDesc').hide();
    //vibe 20110902 add fix bug
    $('#InStockMessage').hide();
    $('#OutStockMessage').hide();

    if (pElem.val() == "parentAttr") {
        setFollowingDisabled(elem.id);
        //generate a list of the selected attributes and display the list
        var selectedAttributes = DropDownGetSelectedText(nextID);
        showAttributesMapImage(selectedAttributes);
        var variantAttributesList = $('#variantAttributes');
        var variantAttributesText = '';
        for (var i = 0; i < selectedAttributes.length; i++) {
            variantAttributesText += selectedAttributes[i];
            if (i < selectedAttributes.length - 1) {
                variantAttributesText += ',&#160;';
            }
        }
        variantAttributesList.html(variantAttributesText);
        $('#variantName').hide();
        $('#variantDesc').hide();

        //vibe 20110902 add fix bug
        $('#InStockMessage').hide();
        $('#OutStockMessage').hide();
    
        
        if ($("#DDHideAddToCart").val() == 1) {
            $('#addToCartButton').hide();
        }


        if ($("#DDHidePrice").val() == 1) {
            $('#variantPrice').hide();
        }
    }
    else {
        if (NumAttributeSections == nextID) {
            ShowDropDownVariantInfo();
            nextID++;
            var selectedAttributes = DropDownGetSelectedText(nextID);

            showAttributesMapImage(selectedAttributes);
            //----------------Vibe commerce add 
            var variantAttributesList = $('#variantAttributes');
            var variantAttributesText = '';
            for (var i = 0; i < selectedAttributes.length; i++) {
                variantAttributesText += selectedAttributes[i];
                if (i < selectedAttributes.length - 1) {
                    variantAttributesText += ',&#160;';
                }
            }
            variantAttributesList.html(variantAttributesText);
            //---------------Vibe commerce end

            return;
        }
        nextID++;
        if ($("#attributeGroup" + nextID).length > 0) {
            $("#attributeGroup" + nextID).attr('disabled', false);
            var selectedAttributeIDs = DropDownGetSelectedAttr(nextID);

            var validIDs = new Array();
            var selectedAttributes = DropDownGetSelectedText(nextID);
            showAttributesMapImage(selectedAttributes);
            //generate a list of the selected attributes and display the list
            var variantAttributesList = $('#variantAttributes');
            var variantAttributesText = '';
            for (var i = 0; i < selectedAttributes.length; i++) {
                variantAttributesText += selectedAttributes[i];
                if (i < selectedAttributes.length - 1) {
                    variantAttributesText += ',&#160;';
                }
            }
            variantAttributesList.html(variantAttributesText);

            for (var j = 0, len = ValidCombos.length; j < len; j++) {
                var combo = ValidCombos[j].split(',');
                var flag = true;
                var selectedAttributeIDslen = selectedAttributeIDs.length;
                for (var i = 0; i < selectedAttributeIDslen; i++) {
                    if (ArrayContains(combo, selectedAttributeIDs[i]) == -1) {
                        flag = false;
                    }
                }

                if (flag) {
                    validIDs = validIDs.concat(combo);
                }
            }
 
            var validIDsLen = validIDs.length;
            if (validIDsLen > 0) {
                document.getElementById("attributeGroup" + nextID).options.length = 1;
                var hiddenDrop = document.getElementById("attributeGroupHidden" + nextID);

                var itemCount = 0;
                
                
                 for (var i = 0; i < hiddenDrop.options.length; i++) {                
                    var id = hiddenDrop.options[i].value;
                    if (ArrayContains(validIDs, id) != -1) {
                        document.getElementById("attributeGroup" + nextID).options.add(new Option(hiddenDrop.options[i].text, hiddenDrop.options[i].value));
                        itemCount += 1;
                    }
                }
                
                //vibe 20110902 add fix bug
                if (itemCount == 0) {
                    $('#NotAvailMessage').show();
                }
                else {
                    $('#NotAvailMessage').hide(); 
                }
            }
            setFollowingDisabled("attributeGroup" + nextID);
            if (document.getElementById("attributeGroup" + nextID).options.length == 2) {
                document.getElementById("attributeGroup" + nextID).selectedIndex = 1;
                DropDownChange(document.getElementById("attributeGroup" + nextID));
            }


        }
    }
}

//get the all the values of selected options
function DropDownGetSelectedAttr(nextID) {

    var SelectedAttrIDs = new Array();
    for (var i = 1; i < nextID; i++) {
        if ($("#attributeGroup" + i).val() != "parentAttr") {
            SelectedAttrIDs.push($("#attributeGroup" + i).val());
        }
    }
    return SelectedAttrIDs;
}

//get the all the text of selected options
function DropDownGetSelectedText(nextID) {

    var SelectedAttrIDs = new Array();
    for (var i = 1; i < nextID; i++) {
        SelectedAttrIDs.push(document.getElementById("attributeGroup" + i).options[document.getElementById("attributeGroup" + i).selectedIndex].text);
    }
    return SelectedAttrIDs;
}


//diable all the following dropdown lists
function setFollowingDisabled(startID) {

    var istartID = startID.replace('attributeGroup', '');
    istartID++;
    while ($("#attributeGroup" + istartID).length > 0) {
        $("#attributeGroup" + istartID).val("parentAttr");
        $("#attributeGroup" + istartID).attr('disabled', true);
        istartID++;
    }


}

//show variant info once you change the option 
function ShowDropDownVariantInfo() {
    var attributeIDs = DropDownGetSelectedAttr(NumAttributeSections + 1);
    var selectedAttributes = DropDownGetSelectedText(NumAttributeSections + 1);
    //generate a list of the selected attributes and display the list
    var variantAttributesList = $('#variantAttributes');
    var variantAttributesText = '';
    for (var i = 0; i < selectedAttributes.length; i++) {
        variantAttributesText += selectedAttributes[i];
        if (i < selectedAttributes.length - 1) {
            variantAttributesText += ',&#160;';
        }
    }
    variantAttributesList.attr({ innerHTML: variantAttributesText });
    //show variant pricing, availability and add to cart button



    if (attributeIDs != null && attributeIDs.length > 0) {
        attributeIDs = attributeIDs.sort(sortNumber);

        var addToCartButton = $('#addToCartButton');
        //var addToWishButton = $('#addToWishButton');
        var availability = $('#availability');
        var variantID = $('#VariantID');
        var price = $('#variantPrice');

        var comboIndex = ArrayContains(ValidCombos, attributeIDs.join(','));

        if (comboIndex != -1) {
            var variant = Variants[comboIndex];

            var variantImage = variant.Image;

            $('#variantImage').attr({ innerHTML: unescapeHTML(variantImage) });
            var allImageDiv = $("#variantMultiImages  div");
            for (var i = 0; i < allImageDiv.length; i++) {
                $(allImageDiv[i]).hide();
            }
            $('#VariantsImagesDiv' + variant.ID).show();



            if (variant.Inventory > 0) {
                variantID.attr({ value: variant.ID });
                addToCartButton.show();
                //addToWishButton.show();
                price.html(unescapeHTML(variant.Price));
                price.show();
                availability.attr({ innerHTML: "" });
            }
            else {
                if ($("#ShowAddToCartOnNoStock").val() > 0) {
                    variantID.attr({ value: variant.ID });
                    addToCartButton.show();
                    //addToWishButton.show();
                    price.html(unescapeHTML(variant.Price));
                    price.show();
                    availability.attr({ innerHTML: "" });
                }
                else {
                    variantID.attr({ value: variant.ID });
                    addToCartButton.hide();
                    price.hide();
                    availability.attr({ innerHTML: $("#outStock").val() });
                }
            }
        }
        else {
            addToCartButton.hide();
            price.hide();
            availability.attr({ innerHTML: $("#notAvail").val() });
            $('#variantName').hide();
        }
        availability.show();
        ShowVariantNameAndDesc();
    }
}

//clear all the selections and displayed info
function clearDropDownSelection() {
    var allImageDiv = $("#variantMultiImages  div");
    for (var i = 0; i < allImageDiv.length; i++) {
        $(allImageDiv[i]).hide();
    }
    $('#productMultiImages').show();
    setFollowingDisabled("attributeGroup1");
    document.getElementById("attributeGroup1").options.selectedIndex = 0;
    var addToCartButton = $('#addToCartButton');
    //var addToWishButton = $('#addToWishButton');
    var availability = $('#availability');
    var price = $('#variantPrice');
    var variantAttributesList = $('#variantAttributes');
    if ($("#DDHideAddToCart").val() == 1) {
        addToCartButton.hide();
    }
    availability.hide();
    if ($("#DDHidePrice").val() == 1) {
        price.hide();
    }
    variantAttributesList.html("&nbsp;");
    $('#variantName').hide();
    $('#variantDesc').hide();

    //vibe 20110902 add fix bug
    $('#InStockMessage').hide();
    $('#OutStockMessage').hide();
    
    var medium = $('#DefaultImage');
    var large = $('#DefaultLargeImage');
    if (large.length > 0) {
        $('#variantImage').attr({ innerHTML: '<img id="ProductPic" style="cursor:pointer" onClick="popupimg(\'' + large.val() + '\')" src="' + medium.val() + '" />' });
    }
    else {
        $('#variantImage').attr({ innerHTML: '<img id="ProductPic" src="' + medium.val() + '" />' });
    }


}

//use appconfig ddoption to create the quantity dropdownlist 
function createQuantityDD(ddoption) {
    var list = ddoption.split(',');
    document.write('<select  name="Quantity" id="Quantity">');
    for (var i = 0; i < list.length; i++) {
        document.write('<option value="' + list[i] + '">' + list[i] + '</option>');
    }
    document.write("</select>");

}

//ShowVariantDesc
function ShowVariantNameAndDesc() {
    var vid = $('#VariantID').val();
    var variant;
    for (var i = 0; i < Variants.length; i++) {
        if (Variants[i].ID == vid) {
            variant = Variants[i];
            break;
        }
    }
    $('#variantName').attr({ innerHTML: variant.Name });
    if (variant.Name.length > 0) {
        $('#variantName').show();
    }
    else {
        $('#variantName').hide();
    }

    //vibe 20110902 add fix bug

    $('#InStockMessage').hide();
    $('#OutStockMessage').hide();
    
    $('#variantDesc').attr({ innerHTML: variant.Description });
    $('#variantDesc').html(variant.Description);

     if (variant.Inventory > 0) {
        $('#InStockMessage').show();
    }
    else {
        $('#OutStockMessage').show();
    }
    
    
    if (variant.Description.length > 0) {
        $('#variantDesc').show();
    }
    else {
        $('#variantDesc').hide();
    }

}


function swapImages(mediumPath, largePath) {
    document.getElementById("ProductPic").src = mediumPath;
    document.getElementById("ProductPic").onclick = function() { popupimg(largePath) };
}

/*--------------------------------new vps javascript-----------------------------------------*/
//called from onclick event
function visualSelect(elem) {


    //vibe 20110902 add fix bug

    $('#InStockMessage').hide();
    $('#OutStockMessage').hide();

    //get the element being hovered over as a Jquery.js element
    var pElem = $("#" + elem.id);

    var ErrorInfo = $('#errorInfo');
    ErrorInfo.hide();


    //if the element has the hover class then remove it
    if (pElem.hasClass(hoverClassName)) {
        pElem.removeClass(hoverClassName);
    }



    //remove the 'selected' class from all siblings of the currently selected element
    //the logic is that you can only select one attribute from each attributeContainer
    pElem.siblings().each(function() {
        $(this).removeClass(selectedClassName);
    });

    //add the 'selected' class to the currently selected element
    pElem.addClass(selectedClassName);

    var attribSelectName = pElem.parent().prev(".attribSelectName");
    if (attribSelectName != null) {
        attribSelectName.attr({ innerHTML: "&#160;&#160;" + GetAttributeName(pElem) });
    }

    var selectedAttributes = GetSelectedAttributes();

    var variantAttributesText = '';
    for (var i = 0; i < selectedAttributes.length; i++) {
        variantAttributesText += GetAttributeName($(selectedAttributes[i]));
        if (i < selectedAttributes.length - 1) {
            variantAttributesText += ',';
        }
    }



    if (selectedAttributes.length == NumAttributeSections) {
        ShowVariantInfo(selectedAttributes, ProductID);
    }
    showAttributesMapImage(variantAttributesText);
    ShowValidCombosForSelect(selectedAttributes);


    /*Vibecommerce add for new vps 2011 7 4*/
    $("#" + pElem.attr("refDropDownid")).val(pElem.attr("attribID"));
    try {
        DropDownChange(document.getElementById(pElem.attr("refDropDownid")));
    }
    catch (e) { }
    $(".attribImage").hide();
    $(".attribImage").each(function() {
        var buttonID = $(this).attr("ID");
        $("#" + $(this).attr("refdropdownid") + " option").each(function() {
            if (buttonID == "attrib" + $(this).val()
        && $("#" + $(this).attr("refdropdownid")).attr("disabled") != "disabled") {
                $("#" + buttonID).fadeIn();
            }
        });
    });
    $(".attribButton").hide();
    $(".attribButton").each(function() {
        var buttonID = $(this).attr("ID");
        $("#" + $(this).attr("refdropdownid") + " option").each(function() {

            if (buttonID == "attrib" + $(this).val()
             && $("#" + $(this).attr("refdropdownid")).attr("disabled") != "disabled") {
                $("#" + buttonID).fadeIn();
            }
        });
    });
    /*Vibecommerce add for new vps 2011 7 4 end*/
}
function dropdownSelect(elem) {
    try {
        document.getElementById('attrib' + $(elem).val()).click()
    }
    catch (e) {
        DropDownChange(elem);
        var selectedAttributes = GetSelectedAttributes();
        var variantAttributesText = '';
        for (var i = 0; i < selectedAttributes.length; i++) {

            variantAttributesText += GetAttributeName($(selectedAttributes[i]));
            if (i < selectedAttributes.length - 1) {
                variantAttributesText += ',';
            }
        }
    }
}

function ShrinkAllUpsell() {
    $(".imgupsell").animate({
        width: "30px",
        height: "30px"
    }, 500);
    $(".btnEx").attr("status", "s");
    $(".decupsell").fadeOut();
    $(".btnEx").html("+");
}

function ExtendOrShrinkUpsell(elem) {
    //ShrinkAllUpsell();
    var thisObj = $("#" + elem.id);
    var imageID = thisObj.attr("refImage");
    var imageObj = $("#" + imageID);
    var descID = thisObj.attr("refDesc");
    var descObj = $("#" + descID);

    if (thisObj.attr("status") == "s") {
        //        imageObj.animate({
        //            width: "60px",
        //            height: "60px"
        //        },500);
        imageObj.attr("class", "imgupsellClicked");
        thisObj.attr("status", "e");
        descObj.fadeIn();
        thisObj.html("-");
    }
    else {
        //        imageObj.animate({
        //            width: "30px",
        //            height: "30px"
        //        }, 500);
        imageObj.attr("class", "imgupsell");
        thisObj.attr("status", "s");
        descObj.fadeOut();
        thisObj.html("+");
    }

}
function ChangeTheVariantImage(productid, variantid) {

    var imgURL = $('#popvariantimage' + variantid).val();
    $("#imgupsell" + productid).css("background-image", "url('" + imgURL + "')");
}
function ChangeTheCurrentVariantPrice(productid, variantid) {
    var currentprice = $('#popvariantprice' + variantid).val();
    $('#CurrentVariantPrice' + productid).val(currentprice);
    var currentpricesymbol = $('#popvariantpricesymbol' + variantid).val();
    $('#CurrentVariantPriceWithSymbol' + productid).html(currentpricesymbol);
    UpdateBtnRefPriceAndVariantid(productid, variantid, currentprice);
}
function UpdateBtnRefPriceAndVariantid(productid, variantid, price) {
    $('#btnAddOrDelete' + productid).attr("refCurrentPrice", price);
    $('#btnAddOrDelete' + productid).attr("refVariantID", variantid);
}
function ChangeTheVariant(productid, variantid) {
    ChangeTheVariantImage(productid, variantid);
    ChangeTheCurrentVariantPrice(productid, variantid);
    SyncCustomizedprice();
}
function AddOrder(productid) {
    $("#btnAddOrDelete" + productid).val("Added!");
    $("#btnAddOrDelete" + productid).attr("IsAddOrder", "true");
    $("#btnAddOrDelete" + productid).attr("disabled", "disabled");
    $("#deleteSpan" + productid).css("display", "");
    $("#btnAddOrDelete" + productid).attr("class", "UpsellOrder upsellAdded");
    SyncCustomizedprice();
}
function DeleteOrder(productid) {
    $("#btnAddOrDelete" + productid).val("Add To Order");
    $("#btnAddOrDelete" + productid).attr("IsAddOrder", "false");
    $("#btnAddOrDelete" + productid).removeAttr("disabled");
    $("#deleteSpan" + productid).css("display", "none");
    $("#btnAddOrDelete" + productid).attr("class", "UpsellOrder");
    SyncCustomizedprice();
}
function SyncCustomizedprice() {
    var cprice = 0;
    for (var i = 0; i < $(".UpsellOrder").size(); ++i) {
        if ($(".UpsellOrder").eq(i).attr("IsAddOrder") == "true") {
            cprice += parseFloat($(".UpsellOrder").eq(i).attr("refCurrentPrice"));
        }
    }
    $(".customizedprice").html((cprice + parseFloat($("#mainvariantprice" + $('#VariantID').val()).val())).toString().asCurrency());
}
function SyncImformation() {
    intAddToOrderButton();
    $(".basepirce").html($("#mainvariantprice" + $('#VariantID').val()).val().asCurrency());
    $(".customizedprice").html($("#mainvariantprice" + $('#VariantID').val()).val().asCurrency());

    var isend = false;
    var index = 1;
    while (!isend && index < 10) {

        if ($("#attributeGroup" + index).length > 0) {
            try {
                $("#PopSelectionName" + index).html($("#attributeGroup" + index).find('option:selected').text());
            }
            catch (e) {
                isend = true;
            }
        }
        else {
            isend = true;
        }
        ++index;
    }
}

function intAddToOrderButton() {
    for (var i = 0; i < $(".UpsellOrder").size(); ++i) {
        if ($(".UpsellOrder").eq(i).attr("IsAddOrder") == "false") {
            $(".UpsellOrder").eq(i).removeAttr("disabled");
        }
    }
}

var inCart = 0;
function MultiAddToCartAjax() {

    inCart = 0;
    for (var i = 0; i < $(".UpsellOrder").size(); ++i) {
        if ($(".UpsellOrder").eq(i).attr("IsAddOrder") == "true") {
            UpsellAddToCartAjax($(".UpsellOrder").eq(i).attr("refProductID"), $(".UpsellOrder").eq(i).attr("refVariantID"), $('#Quantity')[0].value);
        }
    }

    MainAddToCartAjax();
}

function ToShopingcart() {

    inCart += 1;
    var inorderNum = 0;
    for (var i = 0; i < $(".UpsellOrder").size(); ++i) {
        if ($(".UpsellOrder").eq(i).attr("IsAddOrder") == "true") {
            ++inorderNum;
        }
    }
    if (inorderNum + 1 == inCart) {  //+1 is mian product
        window.location.href = "shoppingcart.aspx";
    }
}
function UpsellAddToCartAjax(productid, variantid, qty) {
    if (qty > 0) {
        $('#miniCart').show();
        $('#miniCart').html('<div id="MiniCartLoading"><img src="images/spinner.gif" alt="Loading..." style="vertical-align:middle;" /> <strong>Adding item to cart...</strong></div>')
        $("#loading" + productid).html("<img src='skins/Skin_1/images/upsellLoading.GIF'>");
        var ajaxurl = "ajaxAddToCart.aspx";
        var para = '&ProductID=' + productid + '&VariantID=' + variantid + '&Quantity=' + qty;
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'html',
            timeout: 20000,
            data: para,
            error: function() { $("#loading" + productid).html("<img style='cursor:pointer;' onclick='UpsellAddToCartAjax(" + productid + "," + variantid + "," + qty + ")' src='skins/Skin_1/images/upsellrepeat.png'><a href='shoppingcart.aspx'>Cart</a>"); },
            success: function(html) {

                $("#loading" + productid).html("<img src='skins/Skin_1/images/upselltick.png'>");
                ToShopingcart();
                //DeleteOrder(productid);
                $('#miniCart').html(html);
                $('#numCartItems').attr({ innerHTML: $('#itemsCount').attr("innerHTML") });
            }
        });

    }
}
//ajax add to cart function for dropdown version.
function MainAddToCartAjax() {
    if ($('#Quantity')[0].value > 0) {
        $('#miniCart').show();
        $('#miniCart').html('<div id="MiniCartLoading"><img src="images/spinner.gif" alt="Loading..." style="vertical-align:middle;" /> <strong>Adding item to cart...</strong></div>')
        $("#loadingMain").html("<img src='skins/Skin_1/images/upsellLoading.GIF'>");
        var ajaxurl = "ajaxAddToCart.aspx";
        var para = '&ProductID=' + $('#ProductID')[0].value + '&VariantID=' + $('#VariantID')[0].value + '&Quantity=' + $('#Quantity')[0].value;
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'html',
            timeout: 20000,
            data: para,
            error: function() { },
            success: function(html) {
                $("#loadingMain").html("<img src='skins/Skin_1/images/upselltick.png'>");
                ToShopingcart();
                //the logic after success
                $('#miniCart').html(html);
                $('#numCartItems').attr({ innerHTML: $('#itemsCount').attr("innerHTML") });
            }
        });
    }
}

String.prototype.asCurrency = function() {
    var f1 = this;
    var f2 = (Math.round((f1 - 0) * 100)) / 100;
    f2 = Math.floor(f2) == f2 ? f2 + ".00" : (Math.floor(f2 * 10) == f2 * 10) ? f2 + '0' : f2;
    f2 = String(f2);
    r = /(\d+)(\d{3})/;
    fs = String(f2);
    while (r.test(f2)) {
        f2 = f2.replace(r, '$1' + ',' + '$2');
    }
    return ('$' + f2);
}  

