var tbTypes;
var txtPTXml, txtProductTypeXml;
var infoZone;
var chkFlag;
var ptRow;
var attributesDoc = null, valuesDoc = null;

$(document).ready(function() {
    tbTypes = $("#tbTypes");
    infoZone = $("#infoZone");
    txtPTXml = $("#ctl04_txtPTXml");
    chkFlag = $("#ctl04_chkFlag");
    txtProductTypeXml = $("#ctl04_txtProductTypeXml");
    ptRow = $("#ptRow");

    init();
    $("#tTypes").treeTable({
        initialState: "expanded"
    });
});

function init() {
    if ($(chkFlag).attr("checked") == true) {
        processTypes();
        $(infoZone).show();
    }
    else {
        $(tbTypes).empty();
        $(infoZone).hide();
    }
}

function processTypes() {
    var doc = $($(txtPTXml).val());
    var typeList = $(doc).find("indexes>types>type");

    if (typeList.length == 0) {
        $(ptRow).hide();
        return;
    }

    $.each(typeList, function() {
        var typeId = $(this).find("typeId").text();
        var typeName = $(this).find("typeName").text();
        var typeRowId = "t-" + typeId;
        var typeRow = $("<tr id=\"" + typeRowId + "\"><td><strong>" + typeName + "</strong><\/td><td><\/td><\/tr>");

        var typeSelector = createTypeSelector(typeId, typeName);
        var selectedTypeId = fillTypeSelector(typeName, typeSelector);

        $(tbTypes).append(typeRow);
        $("td", typeRow).eq(1).append(typeSelector);

        var attributeList = $(this).find("attributes>attribute");
        processAttributes(selectedTypeId, typeId, attributeList, typeRowId);
    });

    $(ptRow).show();
}

function processAttributes(selectedTypeId, mappedTypeId, attributeList, typeRowId) {
    $.each(attributeList, function() {
        var attributeId = $(this).find("attributeId").text();
        var attributeName = $(this).find("attributeName").text();
        var attributeRowId = typeRowId + "-" + attributeId;
        var attributeRow = $("<tr id=\"" + attributeRowId + "\" class=\"child-of-" + typeRowId + "\"><td><u>" + attributeName + "</u><\/td><td><\/td><\/tr>");

        var attributeSelector = createAttributeSelector(attributeId, attributeName, mappedTypeId);
        var selectedAttributeId = fillAttributeSelector(selectedTypeId, attributeName, attributeSelector);

        $(tbTypes).append(attributeRow);
        $("td", attributeRow).eq(1).append(attributeSelector);

        var valueList = $(this).find("values>value");
        processValues(selectedAttributeId, attributeId, valueList, attributeRowId);
    });
}

function processValues(selectedAttributeId, mappedAttributeId, valueList, attributeRowId) {
    $.each(valueList, function() {
        var valueId = $(this).find("valueId").text();
        var valueStr = $(this).find("valueStr").text();

        var usageMode = $(this).find("usageMode").text();
        var useAttributeImage = $(this).find("useAttributeImage").text();
        var image = $(this).find("image").text();

        var valueRowId = attributeRowId + "-" + valueId;
        //var valueRow = $("<tr id=\""++"\" class=\"child-of-"++"\"><td>"++"<\/td><td><\/td><\/tr>", valueRowId, attributeRowId, valueStr, selectedAttributeId, valueId));
        var valueRow = $("<tr id=\"" + valueRowId + "\" class=\"child-of-" + attributeRowId + "\"><td>" + valueStr + "<\/td><td><\/td><\/tr>");

        var valueSelector = createValueSelector(valueId, valueStr, mappedAttributeId, usageMode, useAttributeImage, image);
        fillValueSelector(selectedAttributeId, valueStr, valueSelector);

        $(tbTypes).append(valueRow);
        $("td", valueRow).eq(1).append(valueSelector);
    });
}

function createTypeSelector(mappedTypeId, mappedTypeName) {
    var selector = $("<select t=\"type\" mappedTypeId=\"" + mappedTypeId + "\" mappedTypeName=\"" + mappedTypeName + "\"><\/select>");
    $(selector).append($("<option value=\"0\">新增<\/option>"));
    $(selector).bind("change", function() { typeChanged($(this)); });
    return selector;
}

function createAttributeSelector(mappedAttributeId, mappedAttributeName, mappedTypeId) {
    var selector = $("<select t=\"attribute\" mappedAttributeId=\"" + mappedAttributeId + "\" mappedTypeId=\"" + mappedTypeId + "\" mappedAttributeName=\"" + mappedAttributeName + "\"><\/select>");
    $(selector).append($("<option value=\"0\">新增<\/option>"));
    $(selector).bind("change", function() { attributeChanged($(this)); });
    return selector;
}

function createValueSelector(mappedValueId, mappedValueStr, mappedAttributeId, usageMode, useAttributeImage, image) {
    var selector = $("<select t=\"value\" mappedValueId=\"" + mappedValueId + "\" mappedAttributeId=\"" + mappedAttributeId + "\" mappedValueStr=\"" + mappedValueStr + "\"><\/select>");
    $(selector).append($("<option value=\"0\">新增<\/option>"));
    return selector;
}

function fillTypeSelector(mappedTypeName, selector) {
    var types = $($(txtProductTypeXml).val()).find("item");
    var selectedTypeId = "0";
    var loweredTypeName = mappedTypeName.toLowerCase();

    if (types.length > 0) {
        $(selector).append($("<option value=\"\" disabled>--------------<\/option>"));
    }

    $.each(types, function() {
        var ctrlOption;
        if (selectedTypeId == 0 && $(this).attr("typeName").toLowerCase() == loweredTypeName) {
            selectedTypeId = $(this).attr("typeId");
            ctrlOption = $("<option value=\"" + selectedTypeId + "\" selected>" + $(this).attr("typeName") + "<\/option>");
        }
        else {
            ctrlOption = $("<option value=\"" + $(this).attr("typeId") + "\">" + $(this).attr("typeName") + "<\/option>");
        }
        $(selector).append(ctrlOption);
    });

    return selectedTypeId;
}

function fillAttributeSelector(selectedTypeId, mappedAttributeName, selector) {
    var selectedAttributeId = "0";
    var loweredAttributeName = mappedAttributeName.toLowerCase();

    if (attributesDoc == null || $(attributesDoc).find("item[typeId='" + selectedTypeId + "']").length == 0) {
        getAttributes(selectedTypeId);
    }

    var attributes = $(attributesDoc).find("item[typeId='" + selectedTypeId + "']");
    if (attributes.length > 0) {
        $(selector).append($("<option value=\"\" disabled>--------------<\/option>"));
    }

    $.each(attributes, function() {
        var ctrlOption;
        if (selectedAttributeId == 0 && $(this).attr("attributeName").toLowerCase() == loweredAttributeName) {
            $(selector).attr("selectAttributeName", $(this).attr("attributeName"));
            selectedAttributeId = $(this).attr("attributeId");
            ctrlOption = $("<option value=\"" + selectedAttributeId + "\" selected>" + $(this).attr("attributeName") + "<\/option>");
        }
        else {
            ctrlOption = $("<option value=\"" + $(this).attr("attributeId") + "\">" + $(this).attr("attributeName") + "<\/option>");
        }
        $(selector).append(ctrlOption);
    });

    return selectedAttributeId;
}

function fillValueSelector(selectedAttributeId, valueStr, selector) {
    var selectedValueId = "0";
    var loweredValueStr = valueStr.toLowerCase();

    if (valuesDoc == null || $(valuesDoc).find("item[attributeId='" + selectedAttributeId + "']").length == 0) {
        getValues(selectedAttributeId);
    }

    var values = $(valuesDoc).find("item[attributeId='" + selectedAttributeId + "']");
    if (values.length > 0) {
        $(selector).append($("<option value=\"\" disabled>--------------<\/option>"));
    }

    $.each(values, function() {
        var ctrlOption;
        if (selectedValueId == 0 && $(this).attr("valueStr").toLowerCase() == loweredValueStr) {
            selectedValueId = $(this).attr("valueStr");
            ctrlOption = $("<option value=\"" + selectedValueId + "\" selected>" + $(this).attr("valueStr") + "<\/option>");
        }
        else {
            ctrlOption = $("<option value=\"" + $(this).attr("valueStr") + "\">" + $(this).attr("valueStr") + "<\/option>");
        }
        $(selector).append(ctrlOption);
    });

    return selectedValueId;
}

function getAttributes(typeId) {
    var postUrl = "ImportFromHishop.aspx?isCallback=true&action=getAttributes&timestamp=";
    postUrl += new Date().getTime() + "&typeId=" + typeId;

    $.ajax({
        url: postUrl,
        type: 'GET', dataType: 'xml', timeout: 10000,
        async: false,
        success: function(resultData) {
            if (attributesDoc == null)
                attributesDoc = resultData;
            else {
                var root = $(attributesDoc).find("attributes");
                $.each($(resultData).find("item"), function() {
                    $(root).append($(this));
                });
            }
        }
    });
}

function getValues(attributeId) {
    var postUrl = "ImportFromHishop.aspx?isCallback=true&action=getValues&timestamp=";
    postUrl += new Date().getTime() + "&attributeId=" + attributeId;

    $.ajax({
        url: postUrl,
        type: 'GET', dataType: 'xml', timeout: 10000,
        async: false,
        success: function(resultData) {
            if (valuesDoc == null)
                valuesDoc = resultData;
            else {
                var root = $(valuesDoc).find("values");
                $.each($(resultData).find("item"), function() {
                    $(root).append($(this));
                });
            }
        }
    });
}

function typeChanged(selector) {
    var selectedTypeId = $(selector).val();
    var mappedTypeId = $(selector).attr("mappedTypeId");
    var attributeSelectors = $("select[t='attribute'][mappedTypeId='" + mappedTypeId + "']", tbTypes);

    $.each(attributeSelectors, function() {
        var mappedAttributeName = $(this).attr("mappedAttributeName");
        var newSelector = createAttributeSelector($(this).attr("mappedAttributeId"), mappedAttributeName, $(this).attr("mappedTypeId"));
        var selectedAttributeId = "0";

        if (selectedTypeId != "0") {
            selectedAttributeId = fillAttributeSelector(selectedTypeId, mappedAttributeName, newSelector);
        }

        var mappedAttributeId = $(this).attr("mappedAttributeId");
        resetValueSelectors(selectedAttributeId, mappedAttributeId);

        $(this).parent().append(newSelector);
        $(this).remove();
    });
}

function attributeChanged(selector) {
    var selectedAttributeId = $(selector).val();
    var mappedAttributeId = $(selector).attr("mappedAttributeId");
    $(selector).attr("selectAttributeName", $(selector).text());
    //alert($(selector).find("option:selected").text());
    resetValueSelectors(selectedAttributeId, mappedAttributeId);
}

function resetValueSelectors(selectedAttributeId, mappedAttributeId) {
    var valuesSelectors = $("select[t='value'][mappedAttributeId='" + mappedAttributeId + "']", tbTypes);
    $.each(valuesSelectors, function() {
        var mappedValueStr = $(this).attr("mappedValueStr");

        var usageMode = $(this).find("usageMode").text();
        var useAttributeImage = $(this).find("useAttributeImage").text();
        var image = $(this).find("image").text();

        var newValueSelector = createValueSelector($(this).attr("mappedValueStr"), mappedValueStr, $(this).attr("mappedAttributeId"), usageMode, useAttributeImage, image);
        if (selectedAttributeId != "0") {
            fillValueSelector(selectedAttributeId, mappedValueStr, newValueSelector);
        }
        
        $(this).parent().append(newValueSelector);
        $(this).remove();
    });
}

function doImport() {
    if ($("#ctl04_dropImportVersions").val().length == 0) {
        alert("请选择一个导入插件！");
        return false;
    }

    if ($("#ctl04_dropFiles").val().length == 0) {
        alert("请选择要导入的数据包文件！");
        return false;
    }

    if ($("#ctl04_dropCategories").val().length == 0) {
        alert("请选择要导入的店铺分类！");
        return false;
    }

    if ($(tbTypes).children().length > 0) {
        loadDataTypes();
    }

    return true;
}

function loadDataTypes() {
    var dataXml = "<xml><types>";
    var typeSelectors = $("select[t='type']", tbTypes);

    $.each(typeSelectors, function() {
        var mappedTypeId = $(this).attr("mappedTypeId");
        var mappedTypeName = $(this).attr("mappedTypeName");
        var selectedTypeId = $(this).val();

        dataXml += "<type mappedTypeId=\"" + mappedTypeId + "\" mappedTypeName=\"" + mappedTypeName + "\" selectedTypeId=\"" + selectedTypeId + "\">";
        dataXml += "<attributes>";

        var attributeSelectors = $("select[t='attribute'][mappedTypeId='" + mappedTypeId + "']", tbTypes);
        $.each(attributeSelectors, function() {
            var mappedAttributeId = $(this).attr("mappedAttributeId");
            var mappedAttributeName = $(this).attr("mappedAttributeName");
            var selectAttributeName = $(this).attr("selectAttributeName");
            var selectedAttributeId = $(this).val();

            dataXml += "<attribute mappedAttributeId=\"" + mappedAttributeId + "\" mappedAttributeName=\"" + mappedAttributeName + "\" selectAttributeName=\"" + selectAttributeName + "\" selectedAttributeId=\"" + selectedAttributeId + "\">";
            dataXml += "<values>";

            var valueSelectors = $("select[t='value'][mappedAttributeId='" + mappedAttributeId + "']", tbTypes);
            $.each(valueSelectors, function() {
                var mappedValueId = $(this).attr("mappedValueStr");
                var mappedValueStr = $(this).attr("mappedValueStr");
                var selectedValueId = $(this).val();

                dataXml += "<value mappedValueId=\"" + mappedValueId + "\" mappedValueStr=\"" + mappedValueStr + "\" selectedValueId=\"" + selectedValueId + "\" \/>";
            });

            dataXml += "<\/values>";
            dataXml += "<\/attribute>";
        });

        dataXml += "<\/attributes>";
        dataXml += "<\/type>";
    });

    dataXml += "<\/types><\/xml>";
    $("#ctl04_txtMappedTypes").val(dataXml);
    //alert(dataXml);
    //return false;
}