function changeLanguage() {
    $("body").css("cursor", "progress");
    $.getJSON("", {
        jsonevent: editor.find("#id:first").val(),
        lang: editor.find("#lang:first").val()
    }, function (rec) {
        editor.find("#title:first").val(rec.title);
        editor.find("#event:first").val(rec.event);
        $("body").css("cursor", "auto");
        return true;
    });
    return true;
}

function clearForm(form) {
    // $(':input','#'+form)
    //  .not(':button, :submit, :reset, :hidden')
    //  .val('')
    //  .removeAttr('checked')
    //  .removeAttr('selected');    // iterate over all of the inputs for the form
    //    element that was passed in
    $(':input', form).each(function () {
        var type = this.type;
        var tag = this.tagName.toLowerCase(); // normalize case
        // it's ok to reset the value attr of text inputs,
        // password inputs, and textareas
        if (type == 'text' || type == 'password' || tag == 'textarea') {
            this.value = "";
        }
        // checkboxes and radios need to have their checked state cleared
        // but should *not* have their 'value' changed
        else if (type == 'checkbox' || type == 'radio') {
            this.checked = false;
        }
        // select elements need to have their 'selectedIndex' property set to -1
        // (this works for both single and multiple select elements)
        else if (tag == 'select') {
            this.selectedIndex = -1;
        }
    });
}

function closeEditor(fImmediate) {
    editor.dialog("close");
    return editor;
}



function saveEvent(id, close) {
    log("save", id);
    log(editor);
    // if (($("#orgcategory").val() != editor.find("#category:first").val())) {
    //     $("#editeventform").submit();
    //     closeEditor();
    //     return true;
    // }
    log("next");
    $("body").css("cursor", "progress");
    var newrecord = $("#editeventform:first").serializeArray();
    log("saving record",newrecord);
    $.ajax({
        url: "ajax",
        type: "POST",
        data: {
            jsonsave: JSON.stringify(newrecord),
            fullhtml: id > 0 ? "no" : "yes"
        },
        dataType: "json",
        success: function (response) {
            var html = response.html;
            $("#editeventform #id").val(response.id);
            if (id > 0) {
                var newe = $(html.replace(/\\n/g, '<br />').replace(/\\r/g, ''));
                if (editor.find("#fenabled:first").attr('checked')) {
                    $("body #id" + id).after(newe).remove();
                }
                else {
                    $(".adminmode #id" + id).after(newe).remove();
                    $(".normalmode #id" + id + ":first").remove().each(

                    function () {
                        closeEditor();
                        // $("body").css("cursor", "auto");
                        return true;
                    });
                }

                if (close === true) {
                    closeEditor();
                }

                $("#id" + id).addClass("eventclass");
                $("#id" + id).addClass("eventclass");
                statusMsg("Successfully Saved", "#editeventform #lang");
            }
            else {
                $("#centercontainer").empty().append(html);
                $("#centercontainer .listevent").addClass("eventclass");
            }
            liveEditing();
            $("body").css("cursor", "auto");
            return true;
        }
    });
    return false;
}

function populateEditor(data_array) {
    clearForm("#editeventform");
    $.each(data_array, function (key, value) {
        $("#editeventform #" + key).each(function () {
            var $this = $(this);
            switch (this.type) {
            case 'select-one':
            case 'select-multiple':
                $this.attr('selected', true);
                break;
            case 'password':
            case 'text':
            case 'hidden':
            case 'textarea':
                $this.val(value);
                break;
            case 'checkbox':
            case 'radio':
                $(this).attr("checked", value === 1 || value === "1" ? true : false);
            }
        });
    });
    $("#editeventform #lang").val($("#language").val());
}


function openEditor(id, fdup) {
    $("body").css("cursor", "progress");
    $.ajax({
        url: "ajax",
        data:{jsonevent: id,category:curpage()},
        type: "GET",
         dataType:"json",
        success: function (event) {
	    log("openeditor",event);
            if (fdup === true) {
                id = event.id = 0;
            }
            $("#editeventform").data("orgevent", event);
            populateEditor(event);
            editor.dialog("open");
            $("body").css("cursor", "auto");
            return true;
        }
    });
}

function enableEditButtons() {
    $(".buttons .edit").click(

    function () {
	var id=eventID($(this));
	log("edit id is",id);
        openEditor(id, false);
    });
    $(".buttons .duplicate").click(

    function () {
	var id=eventID($(this));
	log("duplicate is",id);
        duplicateEvent(id, true);
    });
    $(".buttons .delete").click(

    function () {
	var id=eventID($(this));
	log("delete is",id);
        deleteEvent(id, true);
    });
    $(".buttons .save").click(

    function () {
        saveEvent($("#editeventform #id").val());
    });
    $(".buttons .close").click(

    function () {
        closeEditor();
    });

    $('.buttons img').hover(

    function () {
        $(this).css('cursor', 'pointer');
    }, function () {
        $(this).css('cursor', 'auto');
    });

}


function editing(id, f) {
    $("#id" + id + " li")[f ? "addClass" : "removeClass"]("editinglive");
}

function checkToken() {
    // if they type in a token do various automatic stuff to other fields affected
    var element = $('token');
    var token = $("#editeventform #token").val();

    if (token.length !== 0) {

        $('#class,#startdate,#duration,#orderby').val('');
        $('#fadmin').attr('checked', true);
        $('#fenableshare').attr('checked', false);

        // set groupby depending on token
        var sg = [];
        sg["admin."] = "adminmessages";
        sg["ev:"] = "eventdefaults";
        sg["fb:"] = "facebook";
        sg["sys:"] = "system";
        sg["list:"] = "list-settings";
        sg["list-sql:"] = "lists-sql";
        sg["list-sql-admin:"] = "lists-sql-admin";
        sg["og:"] = "opengraph";
        sg["google:"] = "google";
        sg.js = "javascript";
        sg["ical:"] = "ical";
        sg.raw = "raw";
        sg.css = "css";
        sg.meta = "meta";

        for (var index in sg) {
            if (token.indexOf(index) === 0) {
                $("#groupby").val(sg[index]);
                $('#groupby').css("color", "red");
                return true;
            }
        }
        $('#groupby').val("tokenset");
        $('#groupby').css("color", "red");
    }
    return true;
}

function duplicateEvent(id, conf) {
    if (conf) {
        if (!confirmaction("Duplicate Event?")) return false;
    }
    return openEditor(id, true);
}


function deleteEvent(id, conf) {
    if (conf) {
        if (!confirmaction("Really DELETE this event?")) {
            return false;
        }
    }
    $("body").css("cursor", "progress");
    closeEditor();
    $.ajax({
        url: "ajax",
        type: "GET",
        data: {
            del: id
        },
        cache: true,
        success: function (html) {
            $("#id" + id).detach().remove();
            $("body").css("cursor", "auto");
        }
    });
    return false;
}



function enableEditing(isadmin) {

    log("enabled editing called");

    $("#body.normalmode")[isadmin ? "addClass" : "removeClass"]("liveediting");

    $(".editicons").remove();
    $(".liveediting #centercontainer .listevent,.adminmode #centercontainer .listevent").each(
    /* add edit buttons to all editable entities */

    function () {
        $(this).prepend($('<div class="editicons"/>').append($(window.editbuttons).remove()));
    });

    $(".liveediting #newevent,.adminmode #newevent").show();

    $(".liveediting #centercontainer .eventclass,.adminmode #centercontainer .listevent").hover(

    function () {
        $(this).find(".editicons:first").stop(1, 1).fadeTo(5000, 1);
        $(this).data("bs", $(this).css("border-style"));
        $(this).data("bc", $(this).css("border-color"));
        $(this).data("bw", $(this).css("border-width"));
        $(this).css("border-style", "dashed");
        $(this).css("border-color", "red");
        $(this).css("border-width", "1px");
    }, function () {
        $(this).find(".editicons:first").stop(1, 1).fadeTo(2000, 0);
        $(this).css("border-style", $(this).data("bs"));
        $(this).css("border-color", $(this).data("bc"));
        $(this).css("border-width", $(this).data("bw"));
    });

    if (!isadmin) {
        closeEditor();
        $(".normalmode #centercontainer .listevent").unbind('mouseenter mouseleave');
        setShareFade();
        // $(".normalmode .editicons").remove();
        $(".normalmode #newevent").hide();
    }

    enableEditButtons();
    animationsEnable();

}

function liveEditing() {
        enableEditing($("#centercontainer").data("fbadmin"));
}

function editorReady() {
    $("#showadvanced").change(

    function () {
        $("#advanced")[$("#showadvancedcheck").is(':checked') ? "show" : "hide"]();
    });

    $("#startdate").change(

    function () {
        $("#durationcontainer")[$("#startdate").val() ? "show" : "hide"]();
    });

    $('#startdate').datetimepicker({
        dateFormat: 'yy-mm-dd',
        timeFormat: 'h:m',
        numberOfMonths: 2,
        stepMinute: 15,
        separator: ' '
        // showOn: "button",
        // buttonImage: "common-images/smallcalendar.gif",
        // buttonImageOnly: false
    });

    $("#eventdateimg").click(function () {
        $("#startdate").click();
        alert("click");
    });

    $("#image").change(

    function () {
        $('imgpreviewimg').attr("src", $('#image').val());
    });


    $("#newevent").click(function () {
        openEditor(0, false);
    });


    $("#token").change(function () {
        checkToken();
    });
    $("#editeventform #lang").change(

    function () {
        changeLanguage();
    });

    editor = $("#editeventcontainer").dialog({
        width: "48em",
        modal: false,
        autoOpen: false,
        open: function (event, ui) {
            $("#centercontainer .embed").css("visibility", "hidden");
            $("#previousevent").button({
                icons: {
                    primary: "common-images/leftarrow.png"
                }
            });
            $("#nextevent").button({
                icons: {
                    primary: "ui-icon-close"
                }
            });
        },
        close: function (event, ui) {
            $("#centercontainer .embed").css("visibility", "visible");
        },
        buttons: [
            {
            text: "save",
            className: "editorsavebutton",
            click: function () {
                var id = $("#editeventform #id").val();
                saveEvent(id);
            }

        },
                {
            text: "close",
            click: function () {
                closeEditor();
            }
        },
                {
            text: "reset",
            click: function () {
                populateEditor($("#editeventform").data("orgevent"));
            }
        }

        ]
    });
    $("#editeventform").find('input').keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            e.preventDefault();
            saveEvent(editor.find("#editeventform #id:first").val(), true);
        }
    });

    $("#editeventform #embed").change(

    function () {
        $("#editeventform #embedpreview").empty().append($($(this).val()));;
    });

    $(".clearfield").click(function () {
        $(this).prevAll("textarea:first,input:first").val("");
    });

    $(".editselectwidget").find("select:first").change(

    function () {
        $(this).prevAll("input[type=text]").val($(this).val());
    });

    liveEditing();
}

$(document).ready(function () {
    editorReady();
    fbClientConnect();
});

