$(document).ready(function() {
    // удаление позиции
    $("#assettypefields .delete").live("click", function (el) {
        if (!confirm(CommonResources.SureDeleteElement)) return false;
        $.post(this.href, { "json": "json" },
            function () {
                if ($(el.target).closest("ul").find("li").length == 1) // удаляем пустые контейнеры "li"
                {
                    $(el.target).closest("ul").closest("li").prev("li.temp_li").remove();
                    $(el.target).closest("ul").closest("li").remove();
                } else
                    $(el.target).closest(".assettypefield").remove();
            });
        return false;
    });
    // удаление группы
    $("#assettypefields .blockdelete").live("click", function (el) {
        if (!confirm(AssetResources.ConfirmDeleteGroupFields)) return false;

        var ids = [];

        $(this).closest("li").find("li").each(function () {
            ids.push($(this).data("id"));
        });

        var holder = $(this).closest("li");

        $.post(base + "assettype.ivp/delete/" + $("#id").val(), { "ids": ids, "json": "json" },
            function () {
                holder.next("li").remove();
                holder.remove();
            });
        return false;
    });
    //редактирование элемента
    $("#assettypefields .edit").live("click", function () {
        $(".edited").removeClass("edited");
        $(this).closest(".assettypefield").addClass("edited");

        $("#dialog").dialog("open").load(this.href, function () {
            $("#dialog").dialog("option", "title", FormatString(AssetResources.EditAttribute));

            $("#saveassettypefield").validate({ ignore: '' });
            $(".save").click(editElement);
            $(".return").click(cancelEditing);
            $("#saveassettypefield #name").focus().select();
            $('#fieldtypeid').change(fieldTypeChange);
        });
        return false;
    });

});

function li(text, c, s, id) {   
     return FormatString('<li class="{%}" {%} {%}>{%}</li>', new Array(c, (s ? "style:" + s : ""), (id ? 'id="' + id + '"': ""), text));
}
function ul(text, c, s) { return FormatString('<ul class="{%}" {%} >{%}</ul>', new Array(c, (s ? "style:" + s : ""), text)); }
function div(text, c, s) { return FormatString('<div class="{%}" {%} >{%}</div>', new Array(c, (s ? "style:" + s : ""), text)); }
function link(label, href, title, c, s) { return FormatString('<a class="{%}" href="{%}" title="{%}" {%}>{%}</a>', new Array(c, href, title, (s ? "style:" + s : ""), label)); }
function img(src, title, c, s, width, height) { 
    return FormatString('<img class="{%}" src="{%}" title="{%}" alt="{%}" {%} {%} {%} />', 
        new Array(c, src, title, title, (s ? "style:" + s : ""), (width ? "width:" + width : ""), (height ? "height:" + height : "")));
}

function template(type, s, id) {    
    var value = li(ul(blockElement(type, s, id) + _clear, "assettypegroup"), "newelement");
    return value;
}
function blockElement(type, s, id) {    
    if (s === undefined)        
        return li(_clear + _el_actions(id), "assettypefield edited " + type, "", "li" + id);
    else
        return li(s + _clear + _el_actions(id), "assettypefield edited " + type, "", "li" + id);
}

function _el_actions(id) {
    return '<div class="element_actions"><a class="delete" href="'+deleteUrl(id)+'"> <img src="img/delete.gif"/></a>' +
            '<img class="de" src="img/cursor_drag_arrow.png" />' +
            '<a class="edit" href="' + editUrl(id) + '"><img src="img/edit.gif"/></a>' +
        '</div>';
}
var _group_actions = '<div class="groupactions"> \
                        <a class="blockdelete" href="#"><img src="img/delete.gif"/></a> \
                        <img class="bde" src="img/cursor_drag_arrow.png"/> \
                      </div>';

var _clear = '<div class="clear"></div>';

var _string = '<label class="desc">' + CommonResources.NewElement + '</label>' +
    '<input class="text small" disabled type="text" />';
var _text = '<label class="desc">' + CommonResources.NewElement + '</label>' +
    '<textarea class="text small" disabled type="text" />';
var _file = '<label class="desc">' + CommonResources.NewElement + '</label>' +
    '<input class="text small" disabled type="file" />';
var _select = '<label class="desc">' + CommonResources.NewElement + '</label>' +
    '<select class="text small" disabled type="text"></select>';
var _bool = '<label class="desc"><input disabled="true" type="checkbox" />' + CommonResources.NewElement + '</label>';
var _break = '<span class="grey">empty space</span><br/>';
var _customhtml = '<div class="additionals"></div>';
var _sortableinit = { handle: ".de", connectWith: ".assettypegroup, .newul", tolerance: "pointer", placeholder: "ui-state-highlight", stop: stopHandler, start: startHandler, over: overHandler};

function startHandler(event, ui) {
     $(".ui-state-highlight").height( ui.item.height() ).width( ui.item.width() );
    
    $(".temp_li").hide();
    $(this).closest("li").prev().show();
    $(this).closest("li").next().show();
}
function stopHandler(event, ui) {
    if (!$(this).find("li").length) $(this).closest("li").remove();
    
    if (ui.item.closest("ul").attr("id") == "assettypefields") {
        ui.item[0].outerHTML = '<li><ul class="assettypegroup">' + ui.item[0].outerHTML + '</ul>' + _clear + '</li>';
        $("#li" + ui.item.attr("id")).closest("ul").sortable( _sortableinit  );
    }else if ( ui.item.closest("ul").hasClass("newul") ) {
        ui.item.closest("ul").removeClass("newul").addClass("assettypegroup").sortable("destroy").sortable( _sortableinit );
        ui.item.closest("ul").closest("li").append(_group_actions).removeClass("temp_li");
    }

    ui.item.closest("ul").find(".clear").remove(); ui.item.closest("ul").append(_clear);
    $(".temp_li").remove();
    
    saveAssetsOrder();

    var templi = li(ul(_clear, "newul"), "temp_li");
        $("#assettypefields>li").after( templi ); $("#assettypefields>li:first").before( templi );
    $(".newul").sortable();
    
}
function receiveHandler(event, ui) {
    return true;
}
function overHandler(event, ui) { //при перетаскивании через видимый элемент подстветить возможность поместить поле между строк
    $(".temp_li").hide();
    $(this).closest("li").prev().show();
    $(this).closest("li").next().show();
    
    return true;
}

function initDesigner() {

    // перемещение по строкам:
    $("#assettypefields").sortable({ stop: function(event, ui) { saveAssetsOrder(); }, axis: "y", handle: ".bde", placeholder: "ui-state-highlight"});
    // перемещение внутри и между строк:
    $(".assettypegroup").sortable(_sortableinit);

    
    $("#fieldtypes li").on("click", function() {
        var _li = $(this).closest("li");
        if (_li.hasClass("break"))
            $("#assettypefields").append(template("Break", _break));
        else if (_li.hasClass("bool"))
            $("#assettypefields").append(template("Bool", _bool));
        else if (_li.hasClass("customhtml"))
            $("#assettypefields").append(template("CustomHtml", _customhtml));
        else if (_li.hasClass("select"))
            $("#assettypefields").append(template("Select", _select));
        else if (_li.hasClass("text"))
            $("#assettypefields").append(template("Text", _text));
        else if (_li.hasClass("file"))
            $("#assettypefields").append(template("File", _file));
        else
            $("#assettypefields").append(template("String", _string));

        $("#assettypefields>li").last().find("ul.assettypegroup").sortable(_sortableinit);

        $("#dialog").dialog("open").load(base + "assettypefield.ivp/ajaxcreate/" + $("#id").val(), { fieldtypeid: $(this).data("typeid") }, function () {
            $("#dialog").dialog("option", "title", FormatString(AssetResources.NewAttribute));
            $("#saveassettypefield").validate({ ignore: '' });
            $(".save").click(createElement);
            $(".return").click(cancelCreating);
            $("#saveassettypefield #name").val("HtmlElement").focus().select();

            $("#addfield").hide();
            $("#dialog").dialog('option', 'position', 'center');
        });
    });

    var templi = li(ul(_clear, "newul"), "temp_li");
    $("#assettypefields>li:first").before(templi);
    $("#assettypefields>li").after(templi);
    $(".newul").sortable();

    // свойства модального окна
    $("#dialog").dialog({
        autoOpen: false,
        width: 580,
        modal: true,
        position: "center",
        close: function() {
            $("li.newelement").remove();
            $("li.edited").removeClass("edited");
        }});
}

function createElement() {
    if (!$("#saveassettypefield").valid())
        return;
    
    var templi = li(ul(_clear, "newul"), "temp_li edited");
        $("#assettypefields>li").last().after( templi );
    $(".newul").sortable();
    
    applyChanges(true);
    
    return false;
}

function applyChanges( create ) {
    var name = $("#saveassettypefield #name").val();

    var additionals;
    if ( $("#saveassettypefield #parameters").length )
        additionals = $("#saveassettypefield #parameters")[0].value;    
    
    var blockstyle;
    if ( $("#saveassettypefield #blockstyle").length )
        blockstyle = $("#saveassettypefield #blockstyle")[0].value;    
    
    var inputstyle;
    if ( $("#saveassettypefield #inputstyle").length )
        inputstyle = $("#saveassettypefield #inputstyle")[0].value;    
      
    
    var labelstyle;
    if ( $("#saveassettypefield #labelstyle").length )
        labelstyle = $("#saveassettypefield #labelstyle")[0].value;    
      
    $.post(base + "assettypefield.ivp/save", $("#saveassettypefield").serialize(), function(data) {
        var id = $.parseJSON(data).Id;
        var typeid = $.parseJSON(data).FieldTypeId;
        var el = $("#assettypefields li.edited").last();

        //var _li = $("#fieldtypes").find("li[data-typeid=" + typeid + "]");
        //if (_li.hasClass("break"))
        //    el[0].outerHTML = blockElement("Break", _break, id);
        //else if (_li.hasClass("bool"))
        //    el[0].outerHTML = blockElement("Bool", _bool, id);
        //else if (_li.hasClass("customhtml"))
        //    el[0].outerHTML = blockElement("CustomHtml", _customhtml, id);
        //else if (_li.hasClass("select"))
        //    el[0].outerHTML = blockElement("Select", _select, id);
        //else if (_li.hasClass("text"))
        //    el[0].outerHTML = blockElement("Text", _text, id);
        //else if (_li.hasClass("file"))
        //    el[0].outerHTML = blockElement("File", _file, id);
        //else
        //    el[0].outerHTML = blockElement("String", _string, id);

        //el = $("#assettypefields li.edited").last();

        //if (create) {
        //    el.closest("ul").sortable( _sortableinit );
        //    el.closest(".newelement").append( _group_actions).removeClass("newelement");
        //    el.closest("ul").append();
        //    saveAssetsOrder();
        //}

        //if (el.hasClass("CustomHtml"))
        //     el.find(".additionals").html(additionals);
        //if ( !el.hasClass("Break") ) {
        //    el.attr("style", blockstyle);
        //    el.find("input,select,textarea").attr("style", inputstyle);
        //    el.find("label").attr("style", labelstyle);
        //}
            
        //el.removeClass("edited");
        
        //if (el.hasClass("Bool"))
        //    el.find(".desc").html('<input disabled="true" type="checkbox" />'+name);
        //else
        //    el.find(".desc").html(name);
        
        $("#dialog").dialog("close");
        
        loadDesigner();
    });    
}

function cancelCreating() {
    $("#assettypefields>li").last().remove();
    $("#dialog").dialog("close");
    
    return false;
}

function editElement() {
    if (!$("#saveassettypefield").valid()) return false;

    applyChanges();
    return false;
}

function cancelEditing() {
    $(".edited").removeClass("edited");
    $("#dialog").dialog("close");    
    return false;
}

function saveAssetsOrder() {
    var ids = [];
    var i = 0;
    $("#assettypefields").children("li").each(function() {
        if ($(this).find(".assettypefield").length > 0) {
            ids[i] = [];
        
            $(this).find(".assettypefield").each(function() {
                ids[i].push($(this).data("id"));
            });
            
            i++;
        }
    });

    $.getJSON(base + 'assettypefield.ivp/saveorder', { ids: JSON.stringify(ids), timestamp: new Date().toString() });
}

function editUrl(id) {
    return FormatString("{%}assettypefield.ivp/ajaxview/{%}", new Array(base, id) );
}

function deleteUrl(id) {
    return FormatString("{%}assettypefield.ivp/delete?id={%}", new Array(base, id) );
}

function setDefaultBlockStyle(type) {
    var cssstring;
    switch (type) {
    case "Date":        
        cssstring = "width:150px;height:38px;background-color: transparent;font-size:12px;";
        break;
    default:
        cssstring = "width:300px;height:38px;background-color: transparent;font-size:12px;";
    }
    
    
    $("#blockstyle").text(cssstring);
    
    return false;
}

function setDefaultLabelStyle(type) {
    var cssstring;
    
    switch (type) {
    case "Date":        
        cssstring = "width:150px;height:14px;background-color: transparent;font-size:12px;";
        break;
    default:
        cssstring = "width:300px;height:14px;background-color: transparent;font-size:12px;";
    }
    
    $("#labelstyle").text(cssstring);
    
    return false;
}

function setDefaultInputStyle(type) {
    var cssstring;
    
    switch (type) {
    case "Date":        
        cssstring = "width:150px;height:15px;font-size:12px;";
        break;
    default:
        cssstring = "width:300px;height:15px;font-size:12px;";
    }
    
    
    $("#inputstyle").text(cssstring);
    
    return false;
}

function showStyleSettings(el) {
    el.next().slideToggle();
    el.hide();
    
    return false;
}

function hideStyleSettings(el) {
    el.parent().prev().show();
    el.parent().slideToggle();
    
    return false;
}

function notShowStyleSettings(el) {
    el.closest('.error').prev().show(); 
    el.closest('.error').remove(); 
    return false;
}

function allowEditStyleSettings(el) {
    el.closest('.error').prev().remove(); 
    el.closest('.error').next().show(); 
    el.closest('.error').remove();

    $.cookies.set("htmleditor", true);
    return false;
}

function showAddField() {
    $("#addfield").slideToggle();

    $("body").on("click.addfield", function(e) {
        if ( $(e.target).hasClass("showaddfield") ) return;
            
        $("#addfield").hide();
        $("body").off("click.addfield");
    });
    
    return false;
}

function resetSettings() {
    if (!confirm(AssetResources.ConfirmResetSettings)) return false;

    $.post(base+"assettype.ivp/resetsettings/"+$("#id").val(), { "json": "json" }, function () {
        loadDesigner();
    });
    
    return false;
}

function fieldTypeChange() {
    if (this.value == 8) { // пустой интервал
        $('#cvfield').hide();
        $("#dialog").find("#name").closest(".field").hide();
        $("#dialog").find("#name").val($("#dialog").find("#name").val() ? $("#dialog").find("#name").val() : "HtmlElement");
        $("#shortname").closest(".field").hide();
        $("#hint").closest(".field").hide();
        $("#units").closest(".field").hide();
        $("#isrequired").closest(".field").hide();
        $("#isrequired").attr("checked", false);
    }
    else if (this.value == 9) { // custom html
        $("#cvfield label").html("HTML");
        $('#cvfield').show();
        $("#dialog").find("#name").closest(".field").hide();
        $("#dialog").find("#name").val($("#dialog").find("#name").val() ? $("#dialog").find("#name").val() : "HtmlElement");
        $("#shortname").closest(".field").hide();
        $("#units").closest(".field").hide();
        $("#isrequired").closest(".field").hide();
        $("#isrequired").attr("checked", false);
    } else {
        $("#dialog").find("#name").closest(".field").show();
        $("#shortname").closest(".field").show();
        $("#hint").closest(".field").show();
        $("#units").closest(".field").show();
        $("#isrequired").closest(".field").show();

        if (this.value == 5) {
            $("#cvfield label").html(AssetResources.DropDownValues);
            $('#cvfield').show();
        }
        else
            $('#cvfield').hide();
    }


}

