﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
/// <reference path="vtex.common.js" />
/// <reference path="vtex.jsevents.js" />
/// <reference path="vtex.skuEvents.js" />

$(document).ready(function () {
    //Para resolver bug do IE com radio
    if ($.browser.msie) {
        $("*[name*='espec_']").click(function () {
            if ($(this).is("input:radio")) {
                this.blur();
                this.focus();
            }
        });
    }

    //Preparo as especificações(Skus) disponiveis
    $("*[name*='espec_']").change(function () {

        //Declaracao de variaveis
        var selectedValue = new Array(); // valores selecionados nas opções de especificacao
        var selecionaveis = new Array(); // valores com as combinações possíveis
        var especChange = '';


        var index = 0; //indice para os vetores
        //vou pegar as combinações selecionadas nas opções de especificação
        selectedValue = getSelected();

        //Caso nao tenha nenhum selecionado
        //vou habilitar todas as opções
        //alert(selectedValue[0]["name"]);
        if (selectedValue[0]["name"] === undefined) {
            enableAllOptions();
            return;
        }
        if (myJSONSkuSpecification.specifications > 1) {
            index = 0;
            var espec = new Array(selectedValue.length);
            $.each(selectedValue, function (j, dataSel) {
                especChange = dataSel.name;
                especPos = especChange.replace("espec_", "");
                var temp = "";
                $.each(myJSONSkuSpecification.combination, function (i, data) {
                    if (data[dataSel.value]) {
                        var h = 0;
                        espec[index] = new Array(data[dataSel.value].length + 1);
                        $.each(data[dataSel.value], function (k, dataEspec) {
                            if (especPos == h)
                                h++;
                            temp = "espec_" + h;
                            if (dataEspec[temp] != 'undefined') {
                                espec[index][h] = dataEspec[temp];
                            }
                            h++;
                        });
                    }
                });
                espec[index][especPos] = getValuesOptions(especChange);
                index++;
            });


            $.each(espec, function (i, data) {
                if (i == 0) {
                    $.each(data, function (j, data1) {
                        selecionaveis[j] = data1.split(",");
                    });
                }
                else {
                    $.each(data, function (j, data1) {
                        selecionaveis[j] = data1.split(",").intersect(selecionaveis[j]);
                    });
                }

            });
            for (j = 0; j < myJSONSkuSpecification.specifications; j++) {
                //Desabilitar Todos
                var temp = "*[name='espec_" + j + "']";
                if ($(temp).is("input:radio")) {
                    $(temp).each(function () {
                        $(this).attr("disabled", "disabled");
                        $("label[for='" + $(this).attr("id") + "']").removeClass("sku-picked");
                    });
                }
                else {
                    $(temp).find('option').each(function () {
                        $(this).attr("disabled", "disabled");
                    });
                    //habilitar o primeiro
                    $(temp).find('option:first').each(function () {
                        $(this).removeAttr("disabled");
                    });
                }
            }

            enableOptions(selecionaveis);
            checkSelected(selecionaveis);
        }
        else {
            for (j = 0; j < myJSONSkuSpecification.specifications; j++) {
                //retirar a classe sku-picked
                var temp = "*[name='espec_" + j + "']";
                if ($(temp).is("input:radio")) {
                    $(temp).each(function () {
                        $("label[for='" + $(this).attr("id") + "']").removeClass("sku-picked");
                    });
                }
            }
        }
        $("label[for='" + $(this).attr("id") + "']").addClass("sku-picked");
        getSku();
    });
});

function getValuesOptions(espec) {
    espec = "*[name='" + espec + "']";
    var strValues = ""
    if ($(espec).is("input:radio")) {
        $(espec).each(function() {
            strValues += "," + $(this).val();
        });
    }
    else {
        $(espec).find('option').each(function() {
            if ($(this).val() && $(this).val() != "") {
                strValues += "," + $(this).val();
            }
        });
    }
    return strValues.substring(1);
}
function enableOptions(selecionaveis) {
    $.each(selecionaveis, function(i, data) {
        $.each(data, function(j, data1) {
            var temp = "[name='espec_" + i + "']";
            if ($(temp).is("input:radio")) {
                temp = "input" + temp + "[value='" + data1 + "']";
            }
            else {
                temp = "select" + temp + " option[value=" + data1 + "]";
            }
            $(temp).removeAttr("disabled");
        });
    });
}
function enableAllOptions() {
    for (j = 0; j < myJSONSkuSpecification.specifications; j++) {
        var temp = "*[name='espec_" + j + "']";
        if ($(temp).is("input:radio")) {
            $(temp).each(function() {
                $(this).removeAttr("disabled");
            });
        }
        else {
            $(temp).find('option').each(function() {
                $(this).removeAttr("disabled");
            });
        }
    }
}
function checkSelected() {
    for (j = 0; j < myJSONSkuSpecification.specifications; j++) {
        //verifico se após as mudanças
        //ficou um selecionado desabilitado
        var temp = "*[name='espec_" + j + "']";
        if ($(temp).is("input:radio")) {
            $(temp).each(function () {
                if ($(this).is(":checked") && $(this).is(":disabled")) {
                    $(this).removeAttr("checked");
                }
                else if ($(this).is(":checked")) {
                    $("label[for='" + $(this).attr("id") + "']").addClass("sku-picked");
                }
            });
        }
        else {
            $(temp).find('option').each(function() {
                if ($(this).is(":selected") && $(this).is(":disabled")) {
                    $(this).removeAttr("selected");
                    //para bug do IE:
                    $(temp).find('option:first').each(function() {
                        $(this).attr("selected", "selected");
                    });
                }
            });
        }
    }
}
function getSelected() {
    var strJson = "";
    var selectors = 0; //total de especificação selecionada
    var i = 0; //variavel para usar no array indicando a especificacao
    var valuesSelect = Array(); //valores da especificacao selecionada
    var m = 0;
    if ($('.sku-selector').length > 0) {
        while (true) {
            var nome = "#espec_" + i + "_opcao_0";
            if ($(nome).length > 0) {
                var j = 0;
                while (true) {
                    var nome2 = "#espec_" + i + "_opcao_" + j;
                    var valor = "";
                    if ($(nome2).length > 0) {
                        if ($(nome2).is("input:radio")) {
                            if ($(nome2).is(":checked")) {
                                valor = $(nome2).val();
                                selectors++;
                            }
                        }
                        else {
                            if ($(nome2).val() && $(nome2).val() != "") {
                                valor = $(nome2).val();
                                selectors++;
                            }
                        }
                        if (valor != "") {
                            strJson += ",{'value':'" + valor + "',";
                            strJson += "'name':'espec_" + i + "'}";
                            valuesSelect[m] = valor;
                            m++;
                        }
                    }
                    else {
                        break;
                    }
                    j++
                }
            }
            else {
                break;
            }
            i++;
        }
    }
    if (strJson == "")
        strJson = "[{}]";
    else
        strJson = "[" + strJson.substring(1) + "]";

    return eval('(' + strJson + ')'); ;
}

function getSku() {
    var selectedValue = getSelected();
    if (selectedValue.length == myJSONSkuSpecification.specifications) { //todos os itens selecionados
        var selection = "";
        $.each(selectedValue, function(i, data) {
            selection += "," + data.value;
        });
        selection = selection.substring(1);
        var idSku = null;
        $.each(myJSONSkuSpecification.skus, function(i, data) {
            if (data[selection]) {
                idSku = data[selection];
                return false;
            }
        });
        FireSkuSelectionChanged(idSku);
        //alert(idSku);
    }
}
