﻿
jQuery.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this;
}

var PortalBuilder = {
    OpenSec: function (baseuri, sec, obj) {
        var openUrl = baseuri + '?s=' + sec + '&o=' + obj; var windowName = 'sec' + sec;
        var oWin = window.open(openUrl, windowName, 'height=600, width=800, channelmode=no, directories=no, fullscreen=no, location=no, menubar=no, resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no', true); oWin.focus();
    },
    OpenSiteDetail: function (baseuri, sid) {
        var openUrl = baseuri + '?SID=' + sid; var windowName = 'sid' + sid;
        var oWin = window.open(openUrl, windowName, 'height=550, width=700, channelmode=no, directories=no, fullscreen=no, location=no, menubar=no, resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no', true); oWin.focus();
    },
    OpenTextContent: function (baseuri, tf) {
        var openUrl = baseuri + '?tf=' + tf; var windowName = 'tf' + PortalBuilder.WindowName(tf);
        var oWin = window.open(openUrl, windowName, 'height=550, width=700, channelmode=no, directories=no, fullscreen=no, location=no, menubar=no, resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no', true); oWin.focus();
    },
    OpenGallery: function (baseuri) {
        var openUrl = baseuri; var windowName = 'gallery';
        var oWin = window.open(openUrl, windowName, 'height=550, width=700, channelmode=no, directories=no, fullscreen=no, location=no, menubar=no, resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no', true); oWin.focus();
    },
    opendl: function (elementQuery, defaultPanel) {
        var toDrag = $(elementQuery);
        toDrag.draggable({
            handle: "div:first"
        });
        $(elementQuery + " > div:first").disableSelection();
        toDrag.show();
        toDrag.center();
        $("img[title='Close']", elementQuery + " > div:first").click(function () { PortalBuilder.closedl(elementQuery) });

        if (defaultPanel === undefined) { return; }
        $("input:text:visible:first", defaultPanel).focus();
    },
    closedl: function (elementQuery) {
        var toDrag = $(elementQuery);
        toDrag.hide();
        toDrag.draggable("destroy")
    },
    ConfirmDelete: function () {
        return window.confirm("Sure to delete this item?\r\nThis action can't be undone!");
    },
    WindowName: function (name) {
        return name.replace(/-/g, "");
    },
    OpenTextBoxPortalGallery: function (commandName, editor, args, galleryUrl) {
        var elem = editor.getSelectedElement();
        if (elem.tagName == "A") {
            editor.selectElement(elem);
            argument = elem;
        } else {
            var content = editor.getSelectionHtml();
            var link = editor.get_document().createElement("A");
            link.innerHTML = content;
            argument = link;
        }

        editor.showExternalDialog(galleryUrl, argument, 700, 455, function (sender, args) {

            editor.pasteHtml(args);

        }, null, 'Insert From Portal Gallery', true, Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Resize, false, true);
    },
    RegisterAccordion: function (elementId, index, saveStateElement) {
        $(function () {
            $(elementId).accordion({
                active: index,
                header: '> h2',
                clearStyle: true,
                autoHeight: false,
                fillSpace: true,
                change: function (event, ui) {
                    if (saveStateElement) {
                        var hField = window.document.getElementById(saveStateElement);
                        if (hField) {
                            hField.value = $(elementId).accordion("option", "active");
                        }
                    }
                }
            });
        });
    },
    EnableDrag: function (elementQuery, handle, saveStateElement) {
        $(function () {
            var toDrag = $(elementQuery);
            toDrag.draggable({
                handle: handle,
                stop: function (event, ui) {
                    if (saveStateElement) {
                        var hField = window.document.getElementById(saveStateElement);
                        if (hField) {
                            hField.value = ui.offset.top + '_' + ui.offset.left;
                        }
                    }
                }
            });
            $(window).scroll(function () {
                if (saveStateElement) {
                    var hField = window.document.getElementById(saveStateElement);
                    if (hField) {
                        if (hField.value.length != 0) {

                            var values = hField.value.split('_');
                            toDrag.css('top', ((values[0] * 1) + $(document).scrollTop()) + 'px');
                            toDrag.css('left', ((values[1] * 1) + $(document).scrollLeft()) + 'px');
                        } else {
                            toDrag.css('top', $(document).scrollTop() + 'px');
                            toDrag.css('left', $(document).scrollLeft() + 'px');

                        }
                    }
                }
            });
            $(document).ready(function () {
                if (saveStateElement) {
                    var hField = window.document.getElementById(saveStateElement);
                    if (hField) {
                        if (hField.value.length != 0) {

                            var values = hField.value.split('_');
                            toDrag.css('top', ((values[0] * 1) + $(document).scrollTop()) + 'px');
                            toDrag.css('left', ((values[1] * 1) + $(document).scrollLeft()) + 'px');
                        } else {
                            toDrag.css('top', $(document).scrollTop() + 'px');
                            toDrag.css('left', $(document).scrollLeft() + 'px');

                        }
                    }
                }
            }
        );
        });
    },
    //TextExchange
    currentTargets: '',
    ctxtName: '',
    TE_LoadText: function (newIndex, txtName, selcss, css, selcsslink, csslink, ctrID) {
        var hField = window.document.getElementById(newIndex + 'H');
        var targets = window.document.getElementById(newIndex + 'C');
        var theLink = window.document.getElementById(newIndex + ctrID);
        if (hField.value != '') {
            var oldLink = window.document.getElementById(hField.value);
            oldLink.parentNode.className = css;
            oldLink.className = csslink;
        }
        hField.value = newIndex + ctrID;
        theLink.parentNode.className = selcss;
        theLink.className = selcsslink;
        PortalBuilder.currentTargets = targets.value;
        PortalBuilder.ctxtName = txtName;
        SmartSoftLab.Portal.UI.Service.TextExchangeService.GetTextContent(txtName, this.OnRequestComplete);
    },
    OnRequestComplete: function (result) {
        var theTargets = PortalBuilder.currentTargets.split('|');
        for (var i = 0; i < theTargets.length; i++) {
            var theEditControl = $find(theTargets[i] + "_TB");
            if (theEditControl) {
                var item = theEditControl.get_items().getItem(0);
                if (item) {
                    var navUrl = item.get_value();
                    navUrl = navUrl.replace("$$", PortalBuilder.ctxtName);
                    item.set_navigateUrl(navUrl);
                }
            }

            var target = window.document.getElementById(theTargets[i] + "T");
            target.innerHTML = result;
        }
    },
    AppearancePartId: "",
    PropertyGridPartId: "",
    RegisterAppearancePart: function (apid) {
        this.AppearancePartId = apid;
    },
    RegisterPropertyGridPart: function (ppid) {
        PortalBuilder.PropertyGridPartId = ppid;
        if (PortalBuilder.PageRequestManager == null) { return; }
        if (PortalBuilder.EditorFullPB.length == 0) { return; }
        i = "#" + PortalBuilder.EditorFullPB.join(", #");


        $(i, '#' + PortalBuilder.PropertyGridPartId).change(function (eventObject) {
            PortalBuilder.AddControlToFullPostBack(PortalBuilder.PageRequestManager, PortalBuilder.EditorClientId, PortalBuilder.EditorServerId);
        });
    },
    HidePropertyGrid: function () {
        $('#' + PortalBuilder.EditorClientId).hide();
    },
    ShowPropertyGrid: function () {
        $('#' + PortalBuilder.EditorClientId).show();
    },
    TTB_OnClientCommandExecuting: function (editor, args) {
        if (args.get_commandName() == "ToggleScreenMode") {
            var isFullPage = editor.isFullScreen();
            if (isFullPage) {
                PortalBuilder.ShowPropertyGrid();
            } else {
                PortalBuilder.HidePropertyGrid();
            }
        }
    },
    Catalog_Drop_Zone: null,
    Catalog_Drop_Index: -1,
    Catalog_ItemId: -1,
    Catalog_CatalogId: -1,
    RegisterCatalog: function (zoneids, catalogId) {
        $(function () {
            $("div.Catalog > div").draggable({
                connectToSortable: zoneids,
                start: function (event, ui) {
                    var values = this.id.split('_');
                    PortalBuilder.Catalog_CatalogId = values[1] * 1;
                    PortalBuilder.Catalog_ItemId = values[2] * 1;
                },
                stop: function (event, ui) {
                    if (PortalBuilder.Catalog_Drop_Zone == null) { return; }
                    if (PortalBuilder.Catalog_Drop_Zone.id == "") { return; }
                    if (PortalBuilder.Catalog_Drop_Index == -1) { return; }
                    var retString = 'add:' + PortalBuilder.Catalog_CatalogId + ':' + PortalBuilder.Catalog_ItemId + ':' + PortalBuilder.Catalog_Drop_Zone.id + ':' + PortalBuilder.Catalog_Drop_Index;
                    PortalBuilder.Catalog_Drop_Zone = null;
                    PortalBuilder.Catalog_Drop_Index = -1;
                    PortalBuilder.Catalog_ItemId = -1;
                    PortalBuilder.Catalog_CatalogId = -1;
                    __doPostBack(catalogId.replace(/_/g, "$"), retString);
                },
                helper: 'clone',
                appendTo: 'body',
                opacity: 0.9,
                revert: 'invalid',
                zIndex: 10001
            });
            $("div.Catalog").disableSelection();
        });
    },
    Dragging_Zone: null,
    Dragging_Index: -1,
    RegisterZones: function (zoneids) {
        $(function () {
            $(zoneids).sortable({
                connectWith: zoneids,
                handle: "table:first > tbody > tr > td:first",
                opacity: 0.9,
                delay: 300,
                revert: true,
                start: function (event, ui) {
                    var draggingElement = ui.item.context;
                    PortalBuilder.Dragging_Zone = ui.item.context.parentElement;
                    PortalBuilder.Dragging_Index = $(PortalBuilder.Dragging_Zone).children().index($(draggingElement));
                },
                stop: function (event, ui) {
                    var droppedElement = ui.item.context;
                    var droppingZone = ui.item.context.parentElement;
                    var dropIndex = $(droppingZone).children().index($(droppedElement));
                    if (PortalBuilder.Dragging_Zone.id == droppingZone.id && dropIndex > PortalBuilder.Dragging_Index) {
                        dropIndex++;
                    }
                    PortalBuilder.Dragging_Zone = null;
                    PortalBuilder.Dragging_Index = -1;
                    __doPostBack(droppingZone.id.replace(/_/g, "$"), "Drag:" + droppedElement.id + ":" + dropIndex);
                },
                sort: function (event, ui) {
                    PortalBuilder.Catalog_Drop_Zone = ui.item.context.parentElement;
                    if (PortalBuilder.Catalog_Drop_Zone == null) { return; }
                    PortalBuilder.Catalog_Drop_Index = $(PortalBuilder.Catalog_Drop_Zone).children().index(ui.placeholder);
                }
            });
            $(".WP_Resizable", $(zoneids)).resizable(
        {
            animate: true,
            ghost: true,
            resize: function (event, ui) {
                var APS = {
                    HeightInput: null,
                    WidthInput: null,
                    HeightDropDown: null,
                    WidthDropDown: null
                }
                var select = $("input[type=text] + select", $('#' + PortalBuilder.AppearancePartId));
                var inputInTable = false;
                if (select.length == 2) {
                } else {
                    select = $("table + select", $('#' + PortalBuilder.AppearancePartId));
                    if (select.length != 2) { return; }
                    inputInTable = true;
                }
                APS.HeightDropDown = select[0];
                APS.WidthDropDown = select[1];
                APS.HeightInput = $(APS.HeightDropDown.parentNode).children()[$(APS.HeightDropDown.parentNode).children().index($(APS.HeightDropDown)) - 1];
                APS.WidthInput = $(APS.WidthDropDown.parentNode).children()[$(APS.WidthDropDown.parentNode).children().index($(APS.WidthDropDown)) - 1];
                if (inputInTable) {
                    APS.HeightInput = $('input[type=text]', APS.HeightInput)[0];
                    APS.WidthInput = $('input[type=text]', APS.WidthInput)[0];
                }
                if (APS.HeightInput == null) { return; }
                if (APS.HeightDropDown == null) { return; }
                if (APS.WidthInput == null) { return; }
                if (APS.WidthDropDown == null) { return; }
                APS.HeightInput.value = ui.size.height;
                APS.WidthInput.value = ui.size.width;
                APS.HeightDropDown.value = "1";
                APS.WidthDropDown.value = "1";
                $(ui.originalElement[0].childNodes[0]).css("height", "100%");
                $(ui.originalElement[0].childNodes[0]).css("width", "100%");
            }
        }
        );
            $("div[id^='WebPart_'] > table:first", $(zoneids)).disableSelection();
        });
    },
    PPMDel: function (sender, eventArgs) {
        var val = eventArgs.get_item().get_value();
        if (val) {
            if (val == "PDelete") {
                if (window.confirm("Sure to delete Site-Content!\r\nThis action can't be undone!")) { return; }
                eventArgs.set_cancel(true);
            }
        }
    },
    AddControlToFullPostBack: function (prm, cName, sName) {
        var clientArray = prm._postBackControlClientIDs;
        var serverArray = prm._postBackControlIDs;
        clientArray = clientArray == null ? [] : clientArray;
        serverArray = serverArray == null ? [] : serverArray;
        var fn, i = 0;
        while ((fn = clientArray[i++])) {
            if (fn === cName) {
                return;
            }
        }
        clientArray.push(cName);
        serverArray.push(sName);
        prm._postBackControlClientIDs = clientArray;
        prm._postBackControlIDs = serverArray;
    },
    EditorFullPB: [],
    EditorClientId: '',
    EditorServerId: '',
    PageRequestManager: null,
    RegisterEditor: function (ecID, esID) {
        PortalBuilder.EditorClientId = ecID;
        PortalBuilder.EditorServerId = esID;
        if (Sys.WebForms === undefined) { return; }
        if (Sys.WebForms.PageRequestManager === undefined) { return; }
        if (PortalBuilder.PageRequestManager == null) {
            PortalBuilder.PageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
        }
    },
    RegisterFullPBTrigger: function (controls) {
        PortalBuilder.EditorFullPB = controls;
    },
    AdminHelpUrl: '',
    AdminHelpPanel: '',
    RegisterAdminHelp: function (navigateUrl, helpPanel) {
        PortalBuilder.AdminHelpUrl = navigateUrl;
        PortalBuilder.AdminHelpPanel = helpPanel;
    },
    SetAdminHelpIfNeeded: function (sender, Args) {
        if (sender.isExternalContent()) { return; }
        sender.set_contentUrl(PortalBuilder.AdminHelpUrl);
    },
    OpenAdminHelp: function () {
        var pane = $find(PortalBuilder.AdminHelpPanel);
        if (pane.get_collapsed()) {
            pane.expand();
        }
    },
    SlidingTicket_Start: function (rUrl) {
        var ticketWindows = $("#PBEWindow");
        if (ticketWindows.length == 0) {
            var iframeNode = jQuery('<iframe id="PBEWindow" name="PBEWindow" style="display: none" src="' + rUrl + '"></iframe>');
            iframeNode.appendTo("body");
            //iframeNode.show();
        }
    },
    SlidingTicket_Stop: function () {
        var ticketWindows = $("#PBEWindow");
        if (ticketWindows.length == 1) {
            ticketWindows.remove("body");
        }
    },
    WebParts: {
        SeaDragon: {
            IsTimerOn: false,
            TimerInterval: 8000,
            CurrentTimeout: null,
            OldViewer: null,
            Navigator: null,
            ButtonPlay: null,
            DoPlayIfNeed: function () {
                if (PortalBuilder.WebParts.SeaDragon.IsTimerOn && PortalBuilder.WebParts.SeaDragon.CurrentTimeout == null) {
                    PortalBuilder.WebParts.SeaDragon.CurrentTimeout = window.setTimeout(function () {
                        PortalBuilder.WebParts.SeaDragon.CurrentTimeout = null;
                        PortalBuilder.WebParts.SeaDragon.Navigator().fireCommand("Page", "Next");
                    }, PortalBuilder.WebParts.SeaDragon.TimerInterval);

                }
            },
            RegisterNavigationControls: function (nav, viewer) {


                if (PortalBuilder.WebParts.SeaDragon.IsTimerOn) {
                    viewer.setDashboardEnabled(false);
                }

                PortalBuilder.WebParts.SeaDragon.Navigator = nav;

                if (PortalBuilder.WebParts.SeaDragon.OldViewer != null) {
                    if (PortalBuilder.WebParts.SeaDragon.OldViewer.isFullPage()) {
                        viewer.setFullPage(true);
                        PortalBuilder.WebParts.SeaDragon.OldViewer.setFullPage(false);
                    }
                    PortalBuilder.WebParts.SeaDragon.OldViewer.close();
                }

                PortalBuilder.WebParts.SeaDragon.OldViewer = viewer;

                PortalBuilder.WebParts.SeaDragon.ButtonPlay = PortalBuilder.WebParts.SeaDragon.MakeControl(PortalBuilder.WebParts.SeaDragon.IsTimerOn ? "Pause" : "Play", function (event) {
                    Seadragon.Utils.cancelEvent(event);

                    if (PortalBuilder.WebParts.SeaDragon.CurrentTimeout != null) {
                        window.clearTimeout(PortalBuilder.WebParts.SeaDragon.CurrentTimeout);
                    }

                    viewer.setDashboardEnabled(true);

                    if (PortalBuilder.WebParts.SeaDragon.IsTimerOn) {
                        $(PortalBuilder.WebParts.SeaDragon.ButtonPlay).text("Play");
                        PortalBuilder.WebParts.SeaDragon.IsTimerOn = false;
                    } else {
                        $(PortalBuilder.WebParts.SeaDragon.ButtonPlay).text("Pause");
                        PortalBuilder.WebParts.SeaDragon.IsTimerOn = true;
                        PortalBuilder.WebParts.SeaDragon.DoPlayIfNeed();
                    }

                });

                viewer.addControl(PortalBuilder.WebParts.SeaDragon.ButtonPlay, Seadragon.ControlAnchor.TOP_RIGHT);

                var buttonNext = PortalBuilder.WebParts.SeaDragon.MakeControl(" > ", function (event) {
                    Seadragon.Utils.cancelEvent(event);
                    PortalBuilder.WebParts.SeaDragon.Navigator().fireCommand("Page", "Next");
                });

                viewer.addControl(buttonNext, Seadragon.ControlAnchor.TOP_RIGHT);

                var buttonPrev = PortalBuilder.WebParts.SeaDragon.MakeControl(" < ", function (event) {
                    Seadragon.Utils.cancelEvent(event);
                    PortalBuilder.WebParts.SeaDragon.Navigator().fireCommand("Page", "Prev");
                });

                viewer.addControl(buttonPrev, Seadragon.ControlAnchor.TOP_RIGHT);


                //                var speedUpButton = PortalBuilder.WebParts.SeaDragon.MakeControl("<", function (event) {
                //                    Seadragon.Utils.cancelEvent(event);
                //                    PortalBuilder.WebParts.SeaDragon.TimerInterval -= 2000;
                //                });
                //                viewer.addControl(speedUpButton, Seadragon.ControlAnchor.TOP_LEFT);
                //                var speedDownButton = PortalBuilder.WebParts.SeaDragon.MakeControl(">", function (event) {
                //                    Seadragon.Utils.cancelEvent(event);
                //                    PortalBuilder.WebParts.SeaDragon.TimerInterval += 2000;
                //                });
                //                viewer.addControl(speedDownButton, Seadragon.ControlAnchor.TOP_LEFT);

            },
            MakeControl: function (text, func) {
                var control = document.createElement("a");
                var controlText = document.createTextNode(text);
                control.href = "#"; // so browser shows it as link       
                control.className = "seaNavigation";
                control.appendChild(controlText);
                Seadragon.Utils.addEvent(control, "click", func);
                return control;
            },
            SetBaseImages: function (imagePath) {
                Seadragon.Config.imagePath = imagePath;
            },
            DoInit: function (containerID, hfWidth, fhHeight, hfImageGuid, fInitCallBack) {

                var width = parseInt(document.getElementById(hfWidth).value);
                var height = parseInt(document.getElementById(fhHeight).value);
                var imageGuid = document.getElementById(hfImageGuid).value;

                var tileSource = new Seadragon.TileSource(width, height, 256, 1);

                tileSource.getTileUrl = function (level, x, y) {
                    return "Resource.ashx?level=" + level + "&x=" + x + "&y=" + y +
                   "&R=" + imageGuid;
                }

                var container = document.getElementById(containerID);
                var viewer = new Seadragon.Viewer(container);

                if (fInitCallBack === undefined) {
                    //nix
                } else {
                    fInitCallBack(viewer, container);
                }
                viewer.openTileSource(tileSource);
            }
        },
        ActiveUser: {
            TextBoxMinutes: '',
            RegisterTextBoxMinutes: function (clientID) {
                PortalBuilder.WebParts.ActiveUser.TextBoxMinutes = clientID;
            },
            HandleValueChange: function (sender, eventArgs) {
                $($get(PortalBuilder.WebParts.ActiveUser.TextBoxMinutes + '_text')).val(eventArgs.get_newValue());
            }
        },
        ShowHelp: function (url, options) {
            var oWin = window.open(url, "Help", 'height=600, width=800, channelmode=no, directories=no, fullscreen=no, location=no, menubar=no, resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no', true); oWin.focus();
        },
        CalendarAction: {
            CalendarFunctionHandle: null,
            OpenAppointment: function (calendarId, appointmentid) {
                PortalBuilder.WebParts.CalendarAction.CalendarFunctionHandle = function () {
                    var calendar = $find(calendarId);
                    if (calendar == null) { return; }
                    var appointments = calendar.get_appointments();
                    if (appointments == null) { return; }
                    var appointment = appointments.findByID(appointmentid);
                    if (appointment == null) { return; }
                    PortalBuilder.WebParts.CalendarAction.LoadAppointment(appointment);
                    Sys.Application.remove_load(PortalBuilder.WebParts.CalendarAction.CalendarFunctionHandle);
                };
                Sys.Application.add_load(PortalBuilder.WebParts.CalendarAction.CalendarFunctionHandle);
            },
            Appointment_Clicked: function (sender, eventArgs) {
                var appointment = eventArgs.get_appointment();
                if (appointment.get_allowEdit()) { return; }
                PortalBuilder.WebParts.CalendarAction.LoadAppointment(appointment);
            },
            LoadAppointment: function (appointment) {
                $("#C_AppointmentDialog").dialog("close");
                SmartSoftLab.Portal.UI.Service.CalendarAppointment.CalendarDescription(appointment.get_id(), appointment.get_start(), appointment.get_end(),
                    function (result) {
                        if (result.ErrorMessage != null) {
                            window.alert(result.ErrorMessage);
                            return;
                        }
                        var details = $("#C_AppointmentDialog_Description");
                        details.text(result.Description);
                        $("#C_AppointmentDialog").dialog({
                            modal: false,
                            title: result.Subject + " (" + result.StartTime + " - " + result.EndTime + ")",
                            width: 500,
                            height: 300
                        });
                    }
                );
            }
        }
    }
};
