var outOfStockMessage = 'Dieses Modell ist leider ausverkauft, bitte treffen Sie eine andere Auswahl.';

// Array.indexOf for the IE:
if (!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for (var i = 0; i < this.length; i++){
            if (this[i] == obj) return i;
        }
        return -1;
    }
}

// All possible attribute qualifiers             ("color",                "size",       "sleeveLength",                  "cup",         "acticleType")
var attributeQualifiers = new Array("wbVariantAttribute1", "wbVariantAttribute2", "wbVariantAttribute3", "wbVariantAttribute4", "wbVariantAttribute5");

var allAttributes = new Array();

function onVariantChange(select, changedSelect, variantValues){
    // Parent form of the select box
    var form = jQuery(select).parents().map(function () {if (jQuery(this).is("form")) return this;});
    adjustVariants(form, select.value, changedSelect, variantValues);
//    var theSelectName = changedSelect!=null?"select."+changedSelect:"select.variants_select";
//    form.find(theSelectName).each(function () {
//        if (this.value == 0){
//            addErrorClassOnSelect(this);
//        }else{
//            removeErrorClassOnSelect(this);
//        }
//    });
}

// Method is called after a value of one of the attribute selectors has been changed
function allVariantsHandleChange(select, changedSelect, variantValues)
{
    // Parent element with class "product" of the select box
    var form = jQuery(select).parents().map(function () {if (jQuery(this).hasClass("product")) return this;});
    if (form.length > 0)
        form = jQuery(form[0]);
    adjustVariants(form, select.value, changedSelect, variantValues);
}

function isProduktMarketAvailable(formId, isVariant, isMarketAvailable) {
	if(isVariant) {
		var form = jQuery('#' + formId);

		if(!isMarketAvailable) {
	        form.find(".pk").val("");
	        form.find(".priceValue").val("");
	
	        form.find(".priceContainer .pricePrefix").html("");
	        form.find(".priceContainer .currency").html("");
	
	        form.find(".article").html("");
	        form.find(".disablebutton").show();
	        form.find(".enablebutton").hide();
	
	        addMessage(form, '.generalMessageField', outOfStockMessage);
		}
	}
}

function adjustVariants(form, newValue, currentQualifier, rows){
    // New selected value
    if(currentQualifier == attributeQualifiers[0]){  //is color qualifier
        changeColorView(form, newValue, rows);
    }

    //--- create a selection object from all variant selectboxes already selected --------------------------------------
    var aSelection = getSelection(form);

    //--- find all rows that match the current selection ---------------------------------------------------------------
    var theMatchingRows = filterMatchingRows(aSelection, rows);

    //--- if no variant exists for the current selection, shorten selection until a result exists ----------------------
    while(theMatchingRows.length == 0){
       aSelection =  resetFirstNonCurrentSelection(form, aSelection, currentQualifier);
       theMatchingRows = filterMatchingRows(aSelection, rows);
    }

    //--- extract unique values from the rows found and save them as list of possible options --------------------------
    var theOptions = createOptionLists(theMatchingRows);

    //--- update select boxes with the option lists (= restrict options to matching values)-----------------------------
    for(var aQualifier  in theOptions) {
        if(aQualifier != 'wbVariantAttribute5'){// && (isReset || aQualifier != currentQualifier)){
            var aSelect = jQuery(form).find("select." + aQualifier);
            updateSelectbox(aSelect,  theOptions[aQualifier]);
        }
    }

    //--- update view --------------------------------------------------------------------------------------------------
    var isComplete = theMatchingRows.length == 1 && isVariantFormCompleted(form);
    if (!isComplete) {
        //--- not complete - series view -------------------------------------------------------------------------------
        form.find(".pk").val("");
        form.find(".priceValue").val(rows["base"].priceValue);
        form.find(".selected").val("false");
        form.find(".wishlist").val(rows['base'].article);
        form.find(".tab").val("series");
        form.find(".replacement").hide();

        var aPriceValue = formatCurrencyValue(rows["base"].priceValue);
        if(aPriceValue == ''){
            form.find(".priceContainer .pricePrefix").html("");
            form.find(".priceContainer .currency").html("");
            form.find(".priceContainer .formattedPriceValue").html("");
        }else{
            form.find(".priceContainer .pricePrefix").html(rows["base"].pricePrefix);
            form.find(".priceContainer .currency").html(rows["base"].currency);
            form.find(".priceContainer .formattedPriceValue").html(aPriceValue);
        }
        form.find(".article").html("");
        form.find(".disablebutton").hide();
        form.find(".enablebutton").show();
        form.find(".availabilityDisplay").html("");
        form.find(".availabilityDisplay").attr("class", "availabilityDisplay");
        removeMessage(form, '.generalMessageField');
        
    }else{
        //--- complete - variant view ----------------------------------------------------------------------------------
        var aSelectedRow = theMatchingRows[0];
        form.find(".availabilityDisplay").html(aSelectedRow.availabilityText);
        form.find(".availabilityDisplay").attr("class", "availabilityDisplay " + aSelectedRow.availabilityCSS);
        if (aSelectedRow.available == "false"){
            form.find(".pk").val("");
            form.find(".priceValue").val("");

            form.find(".priceContainer .pricePrefix").html("");
            form.find(".priceContainer .currency").html("");
            //form.find(".priceContainer .formattedPriceValue").html("ausverk.");

            form.find(".article").html("");
            form.find(".disablebutton").show();
            form.find(".enablebutton").hide();

            addMessage(form, '.generalMessageField', outOfStockMessage);

        }else{
            form.find(".pk").val(aSelectedRow.pk);
            form.find(".priceValue").val(aSelectedRow.priceValue);

            form.find(".priceContainer .pricePrefix").html(rows["base"].singlePricePrefix);
            form.find(".priceContainer .currency").html(rows["base"].currency);
            form.find(".priceContainer .formattedPriceValue").html(formatCurrencyValue(aSelectedRow.priceValue));

            form.find(".article").html(aSelectedRow.article);
            form.find(".disablebutton").hide();
            form.find(".enablebutton").show();

            removeMessage(form, '.generalMessageField');

        }
        form.find(".wishlist").val(aSelectedRow.article);
        form.find(".selected").val("true");
        form.find(".tab").val("variant");

        if(aSelectedRow["replacement"] == "true"){
            form.find(".replacement").show();
        }else{
            form.find(".replacement").hide();
        }
    }
    return isComplete;
}

/**
 * Create a selection object for the variant attributes of the given form.
 * Returns an array of selection objects of the form selection.qualifier = 'qualifiername' and selection.value='value'.
 * @param form
 */
function getSelection(form){
    var aSelection = new Array();
    for(var j = 0; j < attributeQualifiers.length; j++){
        var aQualifier =  attributeQualifiers[j];
        jQuery(form).find("select." + aQualifier).each(function(){
            var aValue = jQuery(this).val();
            if(aValue != 0){
                aSelection[aSelection.length] = {"qualifier" : aQualifier , "value" : aValue};
            }
        });
    }
    return aSelection;
}

/**
 * Find a subset of rows that match a given selection.
 * Selection is provided as an object of the form selection.qualifier = 'qualifiername' and selection.value='value'.
 * Rows are objects with row['qualifiername'] = value.
 * @param selection
 * @param rows
 */
function filterMatchingRows(selection, rows){
    var theMatchingRows = new Array();
    for(var i = 0; i < rows.length; i++){
        var aRow = rows[i];
        var isOK = true;
        for(var j = 0; j <  selection.length; j++){
            var aSelection = selection[j];
            if (aRow[aSelection.qualifier] != aSelection.value){
                isOK = false;
                break;
            }
        }
        if (isOK)
            theMatchingRows[theMatchingRows.length] =  aRow;
    }
    return theMatchingRows;
}

/**
 * Collect variant attributes of a collection of rows into list of options (unsorted)
 * @param selectBox
 * @param optionList
 */
function createOptionLists(rows){
    var theOptions = new Object();
    for(var j = 0; j < attributeQualifiers.length; j++){
        var aQualifier =  attributeQualifiers[j];
        for(var k = 0; k < rows.length; k++){
            var aValue = rows[k][aQualifier];
            //only use non-empty values
            if(aValue != ""){
                //create new list if list for this qualifier does not exist
                if (typeof theOptions[aQualifier] == 'undefined'){
                    theOptions[aQualifier] = new Array();
                }
                //we create a list of unique options so we have to check if value is in list before adding it                
                if(theOptions[aQualifier].indexOf(aValue) == -1){
                    theOptions[aQualifier].push(aValue);
                }
            }
        }
    }
    return theOptions;
}

/**
 * Update option list of variant selectBoxes with list of available options (original options are discarded first)
 * @param selectBox
 * @param optionList
 */
function updateSelectbox(selectBox, optionList){
     var originalValue = jQuery(selectBox).val();
     var isInNewList = optionList.indexOf(originalValue) != -1;
     if (originalValue == '0' || !isInNewList){
         jQuery(selectBox).html("<" + "option value=\"0\">Bitte hier ausw&auml;hlen<" + "/option>");
         optionList.sort();
         for(var i = 0; i < optionList.length; i++) {
            selectBox.append("<option value=\"" + optionList[i] + "\">" + optionList[i] + "</option>");
        }
        if (isInNewList){
            selectBox.val(originalValue);
            // if we select single options automtically,
            // the user might not notice a changed select, therefore we  dont't use the next two lines
//        }else if (optionList.length == 1){  // automaticallsy select single options
//            selectBox.val(optionList[0]);
        }else{
            selectBox.val('0');
        }
     }
}
/**
 * Deselect first selected dropdown, if it is not the currently edited dropdown.
 * @param form
 * @param aSelection
 * @param currentQualifier
 */
function resetFirstNonCurrentSelection(form, aSelection, currentQualifier){
    for(var i = 0; i < aSelection.length; i++){
        if (aSelection[i].qualifier != currentQualifier){
            jQuery(form).find("select." + aSelection[i].qualifier).val('0');
            break;
        }
    }
    return getSelection(form);
}

/**
 * Return true if all variant dropdowns in the specified form are selected (value != 0)
 * @param form
 */
function isVariantFormCompleted(form){
    //compare count of all dropdowns with selected count
    var allCount = 0;
    var selectedCount = 0;
    for(var j = 0; j < attributeQualifiers.length; j++){
        var aQualifier =  attributeQualifiers[j];
        jQuery(form).find("select." + aQualifier).each(function(){
            var aValue = jQuery(this).val();
            allCount++;
            if(aValue != 0){
                selectedCount++;
            }
        });
    }
    return selectedCount == allCount;
}

function formatCurrency(value, currency){
    //don't return an empty  price
    var aValue = formatCurrencyValue(value);
    return (aValue == '')
        ? ''
        : currency + '&#160;' + aValue;
}

function formatCurrencyValue(value){
    //don't return an empty or zero value
    var number = new Number(value).toFixed(2);
    return (number == 0.00)
         ? ''
         : new String(number).replace(/\./, ',').replace(/,00/, ',-'); //german number format plus marketing format
                                                                       //(replace trailing double zeros with -)
}

function changeColorView(form, newValue, variantValues) {
    var imgSrc = "";
    var aColorName =  (newValue != '' && newValue != 0) ? newValue : "";
    var aRow = findMatchingValue(aColorName, variantValues);
    var anImage = findImage(form);
    if (aRow != null && anImage != null && aRow.img != ""){
        jQuery(anImage).attr('src', aRow.img);
        var nodeContainingImage = document.getElementById("imageViewContainer");
        if (nodeContainingImage){
            var aForm = document.getElementById("detailedPictureHiddenForm");
            if (aForm != null){
                aForm.colorName.value =  aColorName;
            }
        }
    }
    setActiveColorPixel(newValue);
    if (window.ajaxAdjustColorView){
        window.ajaxAdjustColorView(aColorName);
    }
}

function setActiveColorPixel(newValue){
    jQuery("div .productColorPicker ul li").each( function() { jQuery(this).removeClass("active") ; } );
    jQuery("div .productColorPicker ul li").each( function() { if(jQuery(this).children("a").children("img").attr("title") == newValue) jQuery(this).addClass("active") ; } );
}


function findMatchingValue(colorValue, variantValues) {
    if (colorValue != ""){
        for(i = 0; i < variantValues.length; i++){
            if (colorValue ==  variantValues[i]['wbVariantAttribute1']){
                if (variantValues[i].img != ''){
                    return variantValues[i];
                }
            }
        }
    }else{
        return variantValues['base'];
    }
    return null;
}

function findImage(form) {
    var container = jQuery(form);
    var anImage = container.find(".productImage");
    if (anImage.length > 0)
        return anImage[0];
    var aNewContainer = jQuery(container).parents().map(function () {if (jQuery(this).hasClass("product")) return this;});
//    if (aNewContainer.length == 0){
//        aNewContainer = $(container).parents().map(function () {if ($(this).hasClass("productTile")) return this;});
//    }

    if (aNewContainer.length > 0){
        anImage = aNewContainer.find(".productImage");
        if (anImage.length > 0)
            return anImage[0];
    }
    anImage = jQuery("#productIMG img")
    if (anImage.length > 0)
            return anImage[0];
    return null;
}

function isNighttime(){
    var NIGHTTIME = 18;  //hour (start of nighttime)
    var MORNINGTIME = 8; //hour (end of nighttime)

    var currentTime = new Date().getHours();
    return currentTime >= NIGHTTIME || currentTime < MORNINGTIME;
}
function changeImage(elem, src, containerClass, imageSelector, colorName)
{
    // Parent element with containerClass
    var container = jQuery(elem).parents().map(function () {if (jQuery(this).hasClass(containerClass)) return this;});
    container.find(imageSelector).attr("src", src);
    jQuery(elem).parents("ul").children("li").each(function (i) { jQuery(this).removeClass("active");});
    jQuery(elem).parent().addClass("active");
    jQuery(container).find("select[class='wbVariantAttribute1 variants_select']").children("option").each( function() { jQuery(this).removeAttr("selected"); } );
    jQuery(container).find("select[class='wbVariantAttribute1 variants_select']").children("option").each(function() { if(jQuery(this).attr("value") == (colorName))  jQuery(this).attr("selected", "selected");});
}
function getColorName(){
    return jQuery('#detailedPictureHiddenForm .colorName').val();
}

function setView(inViewName){
    if(typeof inViewName != 'undefined')
        jQuery('#detailedPictureHiddenForm .viewName').val(inViewName);
}
function setViewAndShow(inViewName){
    setView(inViewName);
    showDetailImage();
}
function showDetailImage(){
    openLayer("");
    document.getElementById('detailedPictureHiddenForm:showDetailedPicture').onclick(null);
}

function openPopup(inURL, inWidth, inHeight) {
    var theWindowName = 'Popup';
    var theWidth = inWidth ? inWidth : '608';
    var theHeight = inHeight ? inHeight : '635';

    theAttributes = 'left=50,top=50,width=' + theWidth + ',height=' + theHeight + ',status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes';
    theWindow = open(inURL, theWindowName, theAttributes);
    theWindow.focus();
}

function setColorImage(colorName, imageSrc){
    jQuery('.previews li.active').removeClass('active');
    jQuery('.previews li img[alt=' +colorName + ']').parents("li").addClass('active');
    jQuery('.previews li img.' +colorName + '').parents("li").addClass('active');
    jQuery('.main img.detail').attr('src', imageSrc).attr('alt', colorName);
}
function setMainImage(name, imageSelector){
    jQuery('.mainImage').hide();
    jQuery(imageSelector).show();

    //highlight preview thumbnail image
    jQuery('.previews li.active').removeClass('active');    
    jQuery('.previews li img[alt=' +name + ']').parents("li").addClass('active');
    jQuery('.previews li img.' +name + '').parents("li").addClass('active');
}


function sendForm(form, target) {
	//This is an emulation of the action link on the hidden form being clicked and submitted.
	document.getElementById(form+':'+target).onclick(null);
}

function toggleSubForm(show, subformSelector){
   //toggles a style class 'disabled' on the subform and disables all input and select elements
   if (show) {
       jQuery(subformSelector).removeClass("disabled");
       jQuery(subformSelector + " :input").removeAttr("readonly").removeAttr("disabled");
       jQuery(subformSelector + " :select").removeAttr("readonly").removeAttr("disabled");
   } else {
       jQuery(subformSelector).addClass("disabled");
       removeErrorMessages(subformSelector);
       jQuery(subformSelector + " :input").val("").attr("readonly", "readonly").attr("disabled", "true");
       jQuery(subformSelector + " :select").val("").attr("readonly", "readonly").attr("disabled", "true");
   }
}

function hideSubmitButton(selector){
    jQuery(selector).addClass('disabled').hide().each(function(index, element){
           jQuery(element).parent().parent().hide();
    });    
}

function printPage(){
    if (document.all){
        try{
            document.execCommand('print', false, null);
        }catch(d){
            self.print();
        }
    }else{
        self.print();
    }
}
