﻿/// <reference path="jquery-1.4.1-vsdoc.js" />


$(document).ready(function () {

    // includeonce('Scripts/ixedit.js')
})

var mX = 0; var mY = 0;

$(document).ready(function () {
    $(document).bind("mousemove", function (e) { mX = e.clientX; mY = e.clientY; });
    
    var marr = [".menu", ".adminmenu"];
    for (ln in marr) {

        var lynx = $('a', marr[ln]);
        lynx.click(function (e) {
            lynx.removeClass('clicked');
            $(this).addClass('clicked');
        });
    }

    CMSPageLoad = function (url) {
        if ($(".loadingpanel").hasClass('disnone')) $(".loadingpanel").removeClass('disnone');
        $(".loadingpanel").css("height", $(document).height()).fadeIn(10);
        window.document.location = url;
    }

    window.RefreshSiteLayout = function () {

            $.get(".", function (data) {
                var dl = $("div#outer", data);
                $("#outer").html(dl.html());
            })
        }
});


$(document).ready(function () {

    showContentPane = function () {

        includeonce(url['Jquery.uj']);
        if (!prep) {
            $.post(url['Bulk'], function () {

                sleep(1000);    // TODO:Better way for include js
                showContentPaneHandler();
                prep = true;
            })
        } else {
            showContentPaneHandler();
        }
    };

    showContentPaneHandler = function () {

        includeonce(url['accordion']);
        $(".loadingpanel").css("height", $(document).height()).fadeIn(10);

        $.post(url['ContentPane'], function (_data) {

            $("#widdialog").css({
                display: "block",
                width: 'auto',
                height: 'auto',
                "-moz-box-shadow": '0 5px 10px rgba(0, 0, 0, 0.5)'
            }).html('<div class="dheader" onclick="hideWidgetList()">' +
                        '<a href="javascript:;" class="close-widget" role="button" unselectable="on" style="-moz-user-select: none;"><span class="ui-icon ui-icon-closethick" unselectable="on" style="-moz-user-select: none;"></span></a>'
                    + '</div>' + _data);
        });
    }

    var prep = false;
    showWidgetList = function () {

        showWidgetListAction();

    }

    showWidgetListAction = function () {

        $(".actions", ".navbox").remove();  // clear if has
        includeonce(url['Jquery.uj']);
        if (!prep) {
            $.post(url['Bulk'], function () {

                sleep(1000);    // TODO:Better way for include js
                showWidgetListHandler();
                prep = true;
            })
        } else {
            showWidgetListHandler();
        }
    }

    disableSortable = function () {

        $(".dropside").stab('disable');
    }

    hideLayerBlock = function () {

        $(".navbox").each(function (i, o) {
            $(".blocker", $(o).parent()).remove();
        });
    };

    showLayerBlock = function (act) {

        $(".navbox").each(function (i, o) {
            $(".blocker", $(o).parent()).remove();
            $(o).parent().prepend("<div class='blocker'></div>");
            $(".blocker", $(o).parent()).css("top", $(o).position().top)
                                    .css("left", $(o).position().left)
                                    .css("height", $(o).outerHeight())
                                    .css("width", $(o).outerWidth());
            if (!act & 1) {
                $(o).bind("mouseenter", function (obj) { $(".blocker", $(o).parent()).css("display", "none") })
                $(o).bind("mouseleave", function (obj) { $(".blocker", $(o).parent()).css("display", "block") })
                $(".blocker", $(o).parent()).bind("mouseenter", function (obj) { $(obj.currentTarget).css("display", "none") })
                $(".blocker", $(o).parent()).bind("mouseleave", function (obj) { $(obj.currentTarget).css("display", "block") })
            }
        });

    };

    paneContent = function (o) {

        var targetUri = ($(this).attr("data-href")).toString().toLowerCase();
        $.post(url['Content'], { eid: 1, targeturi: targetUri }, function (data) {

            $(".container").append("<div id='wdialog'>" + data + "</div>")

            hideContextMenu();
            showLayerBlock(1); //lock
            $(".cHead").removeClass('disnone');



            $("#wdialog").dialog({
                width: 630,
                height: 368,
                focus: function () { },
                close: function () {
                    $(this).remove();
                    $(".paneSEO").remove();
                    hideLayerBlock();   //unLock
                }
            });
            // $("#wdialog").parent().addClass("formFocus")
        })
    };

    bindContentLinks = function () {

        includeonce(url['Jquery.uj']);
        includeoncecss(url['Jquery.ui']);
        includeoncecss(url['Jquery.uic']);
        $("a", $(".container")).each(function (i, a) {
            var lnkCache = $(a).attr("href");
            $(a).attr("data-href", $(a).attr("href")); $(a).attr("href", "javascript:;")
            if (lnkCache.toLowerCase().indexOf('/cat/') > 0 ||
                lnkCache.toLowerCase().indexOf('post/') > -1
            ) {
                $(a).bind("click", paneContent)
            } else { }
        })
    };

    hideLinks = function () {
        $("a", $(".container")).each(function (i, a) {
            $(a).attr("data-href", $(a).attr("href")); $(a).attr("href", "javascript:;");

            if ($(a).attr("data-href").toLowerCase().indexOf('/cat/') > 0) $(a).attr("rel", "cat");
            if ($(a).attr("data-href").toLowerCase().indexOf('post/') > -1) $(a).attr("rel", "post");

        });
    };
    showLinks = function () {
        $("a", $(".container")).each(function (i, a) {
            $(a).attr("href", $(a).attr("data-href"));
        });
    };
    hideContextMenu = function () {
        $("#cntext").html('');
        $("#cntext").remove();
    };

    bindContextMenu = function () {


        $(".navbox").live("contextmenu", function (o) {
            o.preventDefault();
            showContextMenu(o.clientX, o.clientY,
                        $(o.currentTarget.parentNode).attr("id").replace('witem_',''),
                        ".container");
            
        });

    };

    showContextMenu = function (x, y, widgetID, contentObj) {
        $("#cntext").html('');
        $("#cntext").remove();

        $.post(url["WidgetContext"], { wid: widgetID },
                        function (data) {

                            $(contentObj).prepend("<div id='cntext'></div>")
                            $("#cntext").css("top", y);
                            $("#cntext").css("left", x > 950 ? 950 : x);
                            $("#cntext").attr("data-wid", $("#wid").val());

                            $("#cntext").append(data)

                        });

    };  // endOfFunction

    actionOptions = function (obj) {

        var tid = $(obj).parent().parent().parent().attr("id");
        if (tid != '') {
            tid = tid.replace('witem_', '');

            showWidgetOptions(tid);
        }
    };

    showWidgetOptions = function (wID,width,height) {

        if (wID > 0) {

            includeoncecss(url['Jquery.uic'])
            includeoncecss(url['Jquery.ui'])
            $.post(url['WidgetOptions'], { ID: wID }, function (_data) {

                var wholder = $("#dialog").dialog({ modal: true,
                    close: function () { $("#dialog").html(''); $("#dialog").remove();$("body").append("<div id='dialog'></div>") },
                    width: width,
                    height: height
                })
                $(wholder).prepend(_data);
            });
        };

    };

    actionRemove = function (obj) {

        var tid = $(obj).parent().parent().parent().attr("id");
        if (tid != '') {
            tid = tid.replace('witem_', '');

            if (tid > 0) { actionRemoveWidget(tid); }
        }

    };

    actionRemoveWidget = function (tid) {

        $.post(url['RemoveWidget'], { ID: tid }, function (_data) {

            $("#witem_" + tid.toString()).css({ display: "none" }).animate(1000);
            $("#witem_" + tid.toString()).remove();

            $("#cntext").html('');
            $("#cntext").remove();
        });
    };


    actionContext = function (obj) {
        var w = $(obj).parent().parent().parent();
        var ID = $(w).attr("id").toString().replace("witem_", "");

        showContextMenu(mX, mY, ID, $(".container"));

    }

    showWidgetListHandler = function () {


        $(".loadingpanel").css("height", $(document).height()).fadeIn(10);

        forceFocus();

        getWidgetPost();

    }

    forceFocus = function () {

        if ($(".dtab").css('position') != 'relative')
            $(".dtab").css({
                left: $(".dtab").position().left + "px",
                top: $(".dtab").position().top + "px"
            });

        $(".dtab").addClass("objectFocus");

    };

    getWidgetPost = function () {

        $.post(url['WidgetList'], function (_data) {

            var dobj = '<div class="actions"><a href="javascript:;" onclick="actionContext(this)" class="optionsE1"><span width="14" height="14" class="actions-view-context" ></span></a><a href="javascript:;" onclick="actionOptions(this)" class="optionsE1"><span width="14" height="14" class="actions-view-options" ></span></a><a href="javascript:;" onclick="actionRemove(this)" class="closeE1"><span width="14" height="14" class="actions-window-close" ></span></div>'

            $.each($(".navbox"), function (i, o) {
                if ($(this).parent().attr("rel"))
                    $(o).prepend(dobj);

                //$(o).bind("mouseenter", function (obj) { $(obj.currentTarget).parent().css("border", "2px dashed #666666"); })
                //$(o).bind("mouseleave", function (obj) { $(obj.currentTarget).parent().css("border", "0"); })

            });


            $("#widdialog").css({
                display: "block",
                height: 'auto',
                "-moz-box-shadow": '0 5px 10px rgba(0, 0, 0, 0.5)'
            }).html('<div class="dheader" onclick="hideWidgetList()">' +
                    '<a href="javascript:;" class="close-widget" role="button" unselectable="on" style="-moz-user-select: none;"><span class="ui-icon ui-icon-closethick" unselectable="on" style="-moz-user-select: none;"></span></a></div>' + _data);

            setupSource();

            setupAllAreas();

        });  //endOfPost

    };


    hideWidgetList = function (o) {

        $("#widdialog").css({ display: "none" }).animate(100);
        $(".loadingpanel").hide();
        $(".dtab").css({ left: "", top: "" }).removeClass("objectFocus");
        $("#widdialog").html('');
    };

});                                              //endOfDocReady

setupSource = function () {

    $("#stabSource").sortable({
        connectWith: 'ul',
        forceHelperSize: true,
        placeholder: 'ui-state-highlight',
        receive: function (o, ui) {
            var widgetName = $(ui["item"]).attr("rel");
            var widgetID = $(ui["item"]).attr("id").replace("witem_", "");
            $.post(url["RemoveWidget"], { ID: widgetID }, function (_data) {
                var widgetBaseID = _data["ID"];
                $(ui["item"]).attr("id", "item_" + widgetBaseID);
                $(ui["item"]).html(widgetName);
            })
        }
    });

};

setupAllAreas = function () {

    setupWidget("#stabmain", 1);
    setupWidget("#stabtop", 2);
    // setupWidget("#stabheader", 4); // TODO: Better stab design
    setupWidget("#stab07", 7);
    setupWidget("#stabmid", 6);
    setupWidget("#stabfooter", 3);

    $(".dropside").sortable('enable');
};


setupWidget = function (PlaceID, ColID) {

    $(PlaceID).sortable({
        connectWith: 'ul',
        forceHelperSize: true,
        receive: function (o, ui) {
            var widgetName = $(ui["item"]).html();
            var widgetID = $(ui["item"]).attr("id").replace("item_", "")


            $.post(url["AddWidget"], { widgetName: widgetName,
                baseID: widgetID,
                pageID: 1,   // 1: frontpage, main menu
                colID: ColID     // 1: first main column
            }, function (_jdata) {

                $.post(url["Widget"], { ID: _jdata["ID"] }, function (_data) {

                    $(ui["item"]).attr("id", "witem_" + _jdata["ID"])
                    $(ui["item"]).attr("rel", widgetName)
                    $(ui["item"]).html(_data)

                });
            });
        }
    }); }

loading = function (target) {

        var load = $("<div></div>").addClass("loadingpanel")
        $(target).prepend(load)
    };

removeloading = function (target) {

        $(".loadingpanel").remove();
    };

var included_files = new Array();

function includeonce(script_filename, trig) {
    if (!in_array(script_filename, included_files)) {
        
        var html_doc = document.getElementsByTagName('head').item(0);
        var js = document.createElement('script');
        js.setAttribute('language', 'javascript');
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', script_filename);
        html_doc.appendChild(js);
        included_files.push(script_filename);
    }
    window.trig = trig;
    return window.trig;
}
function includeoncecss(css_filename) {
    if (!in_array(css_filename, included_files)) {
        var html_doc = document.getElementsByTagName('head').item(0);
        //var html_doc = $("head", document).get(0);
        var cs = document.createElement('link');
        cs.setAttribute('rel', 'stylesheet');
        cs.setAttribute('type', 'text/css');
        cs.setAttribute('media', 'screen');
        cs.setAttribute('href', css_filename);
        html_doc.appendChild(cs);
        included_files.push(css_filename);
    }
    return false;
}
function in_array(needle, haystack) {
    for (var i = 0; i < haystack.length; i++) {
        if (haystack[i] == needle) {
            return true;
        }
    }
    return false;
}
function replaceAll(str, old, rep) {
    var rExp = new RegExp(old, "g");
    return (str.replace(rExp, rep));
}
function sleep(delay)
{
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}
