﻿/// <reference path="/Scripts/jquery-1.4.4-vsdoc.js" />

var inplace_commandPanel;
var inplace_editpanel;

var savedSelection;

$(document).ready(function () {

    inplace_commandPanel = $('#inplace-commandpanel'); //commandpanelt elmenti
    if (inplace_commandPanel.length > 0) {
        $('[data-inplace-field]').click(makeEditable);  //az összes szerkeszthetőnek feliratkozik a duplaclik eseményére, lehetne dblclick
        $('[data-inplace-field]').each(initField); //mindegyikez megkeresi az input mezőt és abból a belsejébe ill. a data ba másol
        $('[data-resource-value]').each(displayResourceValue);
        $('[data-resource-container]').click(editResource);
        $('[data-resource-container]').hover(
  function () {
      $("[data-resource-id=" + $(this).attr("data-resource-id") + "]").addClass("resource-editable-hover");
  },
  function () {
      $("[data-resource-id=" + $(this).attr("data-resource-id") + "]").removeClass("resource-editable-hover");
  }
);

        registerInplaceCommandPanelEvents();

        inplace_commandPanel.remove(); //commandpanelt kiszedi a dom-ból
    }
});


function makeEditable(event) {
    ///	<summary>
    /// Egy duplaklatty esemény hívja meg. 
    /// Az eseményt kirobbantó elemet szerkeszthető módba váltja.
    ///	</summary>
    event.stopPropagation();


    var ce = $(this).attr("contentEditable");
    if (ce == "true")
        return;

    stopCurrentEdit();

    inplace_editpanel = $(this);
    var inplace_form = inplace_editpanel.closest("form");

    inplace_editpanel.attr("contentEditable", "true");  //szerkeszthetőbe váltja
    inplace_editpanel.addClass("inplace-editing"); // css jelzés
    inplace_form.addClass("inplace-form"); //a befoglaló form-ot is megjelöli

    inplace_editpanel.removeClass("inplace-modified"); //hogy az eredeti kinézetben látszódjon szerkesztés közben


    //mezőszintű vagy form szintű commandpanel megjelenítése
    if (inplace_editpanel.attr("data-inplace-commandpanel") == "field") {
        //ezt akkor ha a szerkesztett mező után szeretnénk
        var inplace_input = inplace_editpanel.next('input');
        inplace_input.after(inplace_commandPanel);
    }
    else {
        //ezt akkor, ha a form aljára szeretnénk
        inplace_form.append(inplace_commandPanel);
    }

    //látszódjonak a formázó gombok, vagy sem?
    if (inplace_editpanel.attr("data-inplace-field") == "html") {
        $('#inplace-formatpanel').show();
    }
    else {
        $('#inplace-formatpanel').hide();
    }

    $('#inplace-formatpanel a', inplace_commandPanel).button();
    $('#inplace-actionpanel a', inplace_commandPanel).button();

    var t = inplace_editpanel.get(0); 
    var range = rangy.createRangyRange();

    range.selectNodeContents(t);

    var sel = rangy.getSelection();
    sel.setSingleRange(range);

}

function registerInplaceCommandPanelEvents() {

    rangy.init();

    //a gombok eseményeire feliratkozás
    $('#inplace-cancel', inplace_commandPanel).live("click",cancelCurrentEdit);
    $('#inplace-save', inplace_commandPanel).live("click",saveCurrentEdit);

    $("#inplace-bold", inplace_commandPanel).live("click", function () {
        if (isSomethingSelected()) {
            document.execCommand('bold', false, null);
        }
    });

    $('#inplace-italic', inplace_commandPanel).live("click", function () {
        if (isSomethingSelected()) {
            document.execCommand('italic', false, null);
        }
    });
    $('#inplace-underline', inplace_commandPanel).live("click",function () {
        if (isSomethingSelected()) {
            document.execCommand('underline', false, null);
        }
    });
    $('#inplace-justifyleft', inplace_commandPanel).live("click",function () {
        if (isSomethingSelected()) {
            document.execCommand('justifyleft', false, null);
        }
    });
    $('#inplace-justifycenter', inplace_commandPanel).live("click",function () {
        document.execCommand('justifycenter', false, null);
    });
    $('#inplace-justifyright', inplace_commandPanel).live("click",function () {
        if (isSomethingSelected()) {
            document.execCommand('justifyright', false, null);
        }
    });
    $('#inplace-justifyfull', inplace_commandPanel).live("click",function () {
        if (isSomethingSelected()) {
            document.execCommand('justifyfull', false, null);
        }
    });
    $('#inplace-indent', inplace_commandPanel).live("click",function () {
        document.execCommand('indent', false, null);
    });
    $('#inplace-outdent', inplace_commandPanel).live("click",function () {
        if (isSomethingSelected()) {
            document.execCommand('outdent', false, null);
        }
    });
    $('#inplace-insertunorderedlist', inplace_commandPanel).live("click",function () {
        if (isSomethingSelected()) {
            document.execCommand('insertunorderedlist', false, null);
        }
    });
    $('#inplace-insertorderedlist', inplace_commandPanel).live("click",function () {
        if (isSomethingSelected()) {
            document.execCommand('insertorderedlist', false, null);
        }
    });
    $('#inplace-removeformat', inplace_commandPanel).live("click",function () {
        //        if (isSomethingSelected()) {
        //            document.execCommand('removeformat', false, null);
        //        }
        inplace_editpanel.html(inplace_editpanel.text());
    });

    $('#inplace-createlink', inplace_commandPanel).live("click",function () {
        if (isSomethingSelected()) {
            document.execCommand('createlink');
        }
    });

    $('#inplace-uploadpicture', inplace_commandPanel.get()).hover(function () {
        if (savedSelection != null) {
            rangy.removeMarkers(savedSelection);
        }
        savedSelection = rangy.saveSelection();
    });

    new AjaxUpload('inplace-uploadpicture-file', {
        action: '/EditableResource/UploadImage?proba=6',
        name: 'image',
        data: createObjectWithCollectedProperties($("#inplace-uploadpicture-file")),
        onSubmit: function (file, extension) {
        },
        onComplete: function (file, response) {
            if (savedSelection != null && savedSelection.rangeInfos.length > 0) {
                var marker = $("#" + savedSelection.rangeInfos[0].markerId);
                marker.text("*");
                var range = rangy.createRangyRange();
                range.selectNode(marker.get(0));
                var sel = rangy.getSelection();
                sel.setSingleRange(range);
                document.execCommand('insertImage', false, response);
                var image = marker.children("img");
                marker.before(image);
                marker.remove();
            }
        }
    });
    

}


function createObjectWithCollectedProperties(startingNode) {
    //var t = startingNode.parents("[data-inplace-param]");//.attr("data-inplace-param");
    obj = new Object();
    //eval("x={controller: 'valmicsoda', masik: 'naja', controller:'megse' }");

    startingNode.parents("[data-inplace-param]").each(
    function () {
        var paramsWithValues = $(this).attr("data-inplace-param").split(",");

        for (var pair in paramsWithValues) {

            var second = paramsWithValues[pair].split(":");
            if (second.length > 1)
                obj[second[0]] = second[1];
        }


        
    }
    );

//    allstring = 'x={' + allstring + '}';
//    obj = eval(allstring);

    return obj;
//    obj = new Object();
//    prop = "name";
//    obj[prop] = "Yuri";

//    x = new Object();
//    propertyName = "nameProperty";
//    propertyValue = "John";
//    eval("x." + propertyName + "='" + propertyValue + "'");
//    alert(x.nameProperty);
}

function isSomethingSelected() {
    var isSelected = false;
    var sel = rangy.getSelection();
    if (!sel.isCollapsed) {
        var range = sel.getRangeAt(0);
        var node = $(range.startContainer);
        if (node.parents("[contentEditable=true][data-inplace-field]").length > 0) {
            isSelected = true;
        }
        return isSelected;
    }
}

function stopCurrentEdit(action) {
    ///	<summary>
    /// Ha van épp szerkesztés alatt egy mező, akkor azt a szerkesztést megszűnteti.
    /// Ellenőrzi, hogy a hozzátartozó inputmezőhöz képest eltér-e a tartalom, ha igen akkor rápakolja az inplace-modified classt
    ///	</summary>
    ///	<param name="isCancel" type="String">
    /// ha "cancel", akkor a hidden mezőből visszaállítja az eredeti értéket
    /// ha "save", akkor a szerkesztett elem tartalmát másolja a hidden mezőbe
    /// egyéb esetben csak az inplace-modified css classszal jelzi, hogy különböznek-e
    ///	</param>

    if (inplace_editpanel == null)
        return;

    //a rangy selection mentések eltüntetése
    $('span[id^="selectionBoundary"]').remove();

    var inplace_form = inplace_editpanel.closest("form");

        if (action == "save" && !inplace_form.valid())
            return;

    inplace_editpanel.attr("contentEditable", "false"); //szerkeszthetőség megszűntetése
    inplace_editpanel.removeClass("inplace-editing");
    inplace_form.removeClass("inplace-form");


    var inplace_input = inplace_editpanel.next('input');
    if (inplace_input == null)
        return;

    //input mezőbe másolás és validálás
    inplace_input.val(getCurrentEditedValue(inplace_editpanel));
    //alert(inplace_input.attr("name") + ': "' + inplace_input.val() + '"');

    if (inplace_input.valid()) {
        inplace_editpanel.removeClass("inplace-validation-error");
    } else {
        inplace_editpanel.addClass("inplace-validation-error");
    }

    if (inplace_commandPanel != null)
        inplace_commandPanel.remove();

    if (action == "cancel") {
        //undo, de kétféle módon
        if (inplace_editpanel.attr("data-inplace-commandpanel") == "field") {
            inplace_editpanel.each(undoField);
        }
        else {
            //az összeset vissza
            $('[data-inplace-field]').each(undoField);
        }
    }
    else if (action == "save") {
            inplace_form.submit();
           // $('[data-inplace-field]').each(initField); //TODO: ezt csak akkor, ha sikerült a post, de akkor acceptfield, mindegyikre
        
    }
    
    if (getCurrentEditedValue(inplace_editpanel) == inplace_editpanel.data("original")) {
        inplace_editpanel.removeClass("inplace-modified");
    }
    else {
        inplace_editpanel.addClass("inplace-modified");
    }

    //alert(inplace_input.attr("name") + ': "' + inplace_editpanel.html() + '"  original: "' + inplace_editpanel.data("original") + '"');

    if (inplace_editpanel.is(':empty')) {
        inplace_editpanel.addClass("inplace-empty");
    }
    else {
        inplace_editpanel.removeClass("inplace-empty");
    }

    inplace_editpanel = null;
}

function undoField() {
    ///<summary>
    /// A span belsejébe a data mezőből beállítja az eredetit,
    /// a span belsejét bemásolja az input fieldbe
    /// removeolja a spanről az inplace-modified classt,
    /// és szükség szerint beállítja az inplace-empty classt
    /// a végén pedig validál.
    ///</summary>
    var inplace_input = $(this).next('input');
    if (inplace_input == null)
        return;


    $(this).html($(this).data("original"));
    inplace_input.val($(this).data("original"));
    
    $(this).removeClass("inplace-modified");

    if ($(this).is(':empty')) {
        $(this).addClass("inplace-empty");
    }
    else {
        $(this).removeClass("inplace-empty");
    }

    if (inplace_input.valid()) {
        $(this).removeClass("inplace-validation-error");
    } else {
        $(this).addClass("inplace-validation-error");
    }
}

function initField() {
    ///<summary>
    /// Az input mezőből bemásolja a span belsejébe és a data mezőjébe,
    /// removeolja a spanről az inplace-modified classt,
    /// és szükség szerint beállítja az inplace-empty classt.
    /// Az első betöltéskor, illetve sikeres post után.
    ///</summary>

    var inplace_input = $(this).next('input');
    if (inplace_input == null)
        return;

    $(this).html(inplace_input.val());
    inplace_input.val($(this).html()); //a buta ie miatt, mert nagybetűsíti a html tageket
    $(this).data("original", inplace_input.val());

    $(this).removeClass("inplace-modified");

    if ($(this).is(':empty')) {
        $(this).addClass("inplace-empty");
    }
    else {
        $(this).removeClass("inplace-empty");
    }
}




function getCurrentEditedValue(editpanel) {
    ///	<summary>
    /// A data-inplace-field értékétől függően adja vissza
    /// a szerkesztett elem html vagy text tartalmát.
    ///	</summary>
    if (editpanel == null)
        return null;

    if (editpanel.attr("data-inplace-field") == "html")
        return editpanel.html();

    return editpanel.text();
}

function cancelCurrentEdit() {
    ///	<summary>
    /// Ha van épp szerkesztés alatt egy mező, akkor azt a szerkesztést megszűnteti és
    /// a hidden mezőből visszaállítja az eredeti értéket.
    ///	</summary>
    stopCurrentEdit("cancel");
}


function saveCurrentEdit() {
    ///	<summary>
    /// Ha van épp szerkesztés alatt egy mező, akkor azt a szerkesztést megszűnteti és
    /// a hidden mezőbe átmásolja a szerkesztett elem tartalmát.
    ///	</summary>
    stopCurrentEdit("save");
}



function saveResource() {

    var fieldValue = $.trim($(this).text());
    var fieldId = $(this).attr("data-resource-id");

    $.ajax({
        type: 'POST',
        url: '/EditableResource/SaveItem',
        data: { "id": fieldId, "value": fieldValue },
        success: function (result) {
            if (result != null && result.Success) {
                resourceEditingFinished();
            }
            else {
                alert(result.ErrorMessage);
            }
        },
        error: function (result) {

            alert(result.responseText);
        }
    });
}


function displayResourceValue() {
    var resourceValue = $(this).attr("data-resource-value")
    var tag = this.tagName.toLowerCase();

    if (tag == "input") {
        $(this).val(resourceValue);
    }
    else {
        $(this).text(resourceValue);
    }

    var resourceId = $(this).attr("data-resource-id");
    if (resourceId != '' && resourceId != null) {
        $(this).before("<div data-resource-container='yes' data-resource-id='" + resourceId + "'  title='" + resourceId + "'/>");
    }
}

function editResource() {

    var dataItem = $(this).next();
    var fieldValue = $.trim(dataItem.attr("data-resource-value"));
    var fieldId = $(this).attr("data-resource-id");

    $("#resource-textarea").val(fieldValue);
    $("#resource-hidden").val(fieldId);

    $("#resource-dialog").dialog(
    {
        modal: true,
        title: "editor",
        buttons: { "Save": saveResource, "Cancel": function () { $(this).dialog('close') } }
    }
    );
}

function resourceEditingFinished() {
    $("#resource-dialog").dialog('close');

    var fieldValue = $("#resource-textarea").val();
    var fieldId = $("#resource-hidden").val();

    //$("[data-resource-id=" + fieldId + "]").text(fieldValue);
    $("[data-resource-id=" + fieldId + "][data-resource-value]").each(
    function () {

        var tag = this.tagName.toLowerCase();
        $(this).attr("data-resource-value", fieldValue);
        if (tag == "input") {
            $(this).val(fieldValue);
        }
        else {
            $(this).text(fieldValue);
        }

    }
    )
}

function AjaxPostSucceeded(result) {
    if (result != null && result.Success) {
        $('[data-inplace-field]').each(initField);
    }
    else {
        alert(result.ErrorMessage);
    }
}

function AjaxPostError(result) {
    alert(result.responseText);
}


$.fn.isModified = function () 
{
    var retval = !getCurrentEditedValue(this) == this.data("original"); 
    return retval;
};
