﻿String.prototype.boolean = function () {
    return "true" == this.toLowerCase();
};

String.prototype.BeginsWith = function(pattern) {
    return this.indexOf(pattern) === 0;
};

String.prototype.EndsWith = function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
};

function confirmCallBackFn(arg) {
    radalert("<strong>radconfirm</strong> returned the following result: <h3 style='color: #ff0000;'>" + arg + "</h3>", null, null, "Result");
}

function promptCallBackFn(arg) {
    radalert("After 7.5 million years, <strong>Deep Thought</strong> answers:<h3 style='color: #ff0000;'>" + arg + "</h3>", null, null, "Deep Thought");
}

function OpenAlert() {
    radalert('<h4>Welcome to <strong>RadWindow</strong>!</h4>', 330, 100, 'RadAlert custom title');
    return false;
}
function OpenConfirm() {
    radconfirm('<h3 style=\'color: #333399;\'>Are you sure?</h3>', confirmCallBackFn, 330, 100, null, 'RadConfirm custom title');
    return false;
}
function OpenPrompt() {
    radprompt('<span style=\'color: #333399;\'>What is the answer of Life, Universe and Everything?</span>', promptCallBackFn, 330, 160, null, 'The Question', '42');
    return false;
}

function GetDefaultWindowArguments() {
    var windowArgs = new Object();
    windowArgs.Url = null;
    windowArgs.Width = 400;
    windowArgs.Height = 300;
    windowArgs.Title = null;
    windowArgs.ShowTitle = true;
    windowArgs.IsModal = false;
    windowArgs.Status = null;
    windowArgs.ShowStatus = true;
    windowArgs.Behaviors = null;
    windowArgs.OnClose = null;
    windowArgs.OnBeforeClose = null;
    windowArgs.OnPageLoad = null;
    windowArgs.OnShow = null;
    return windowArgs;
}

function IsNullOrEmpty(obj)
{
    return !(typeof(obj) !== 'undefined' && obj != null);
}

function GetRadWindow() {
    var oWindow = null;
    if (window.radWindow) oWindow = window.radWindow;
    else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
    return oWindow;
}

function GetMainWindow() {
    return window.top;
}

function GetRadWindowByName(name) {
    return GetMainWindow().GetRadWindowManager().GetWindowByName(name);
}

// Get Default.aspx leftPane window
function GetLeftPaneWindow() {
    var mainWindow = GetMainWindow();

    if (mainWindow && mainWindow.Accessdata && mainWindow.Accessdata.Pane && mainWindow.Accessdata.Pane.Splitter && mainWindow.Accessdata.Pane.Splitter.ClientID && mainWindow.Accessdata.Pane.LeftPane && mainWindow.Accessdata.Pane.LeftPane.ClientID) {
        var splitter = mainWindow.$find(mainWindow.Accessdata.Pane.Splitter.ClientID);
        if (splitter) {
            var pane = splitter.GetPaneById(mainWindow.Accessdata.Pane.LeftPane.ClientID);
            if (pane) {
                var iframe = pane.GetExtContentElement();
                if (iframe) {
                    var contentWindow = iframe.contentWindow;
                    return contentWindow;
                }
            }
        }
    }

    return null;
}

// Get Default.aspx leftPane window
function GetRightPaneWindow() {
    var mainWindow = GetMainWindow();

    if (mainWindow && mainWindow.Accessdata && mainWindow.Accessdata.Pane && mainWindow.Accessdata.Pane.Splitter && mainWindow.Accessdata.Pane.Splitter.ClientID && mainWindow.Accessdata.Pane.RightPane && mainWindow.Accessdata.Pane.RightPane.ClientID) {
        var splitter = mainWindow.$find(mainWindow.Accessdata.Pane.Splitter.ClientID);
        if (splitter) {
            var pane = splitter.GetPaneById(mainWindow.Accessdata.Pane.RightPane.ClientID);
            if (pane) {
                var iframe = pane.GetExtContentElement();
                if (iframe) {
                    var contentWindow = iframe.contentWindow;
                    return contentWindow;
                }
            }
        }
    }

    return null;
}
var Accessdata = new Object();
Accessdata.String = new Object();
Accessdata.String.IsEmpty = function (str) {
    return (str + '').match(/[\w\d]/) == null;
}

Accessdata.Path = new Object();
Accessdata.Path.GetUrlDirectory = function (URL) {
    var result = unescape(URL.substring(0, (URL.lastIndexOf("/")) + 1))
    return result;
}

Accessdata.OpenWindow = function (url, target, properties) {
    try {
        window.open(url, target, properties);
    } catch (ex) { }
}
// Contains the Default.aspx Pane
Accessdata.Pane = new Object();

// Contains the Default.aspx Splitter2
Accessdata.Pane.Splitter = new Object();
Accessdata.Pane.Splitter.ClientID = null;

// Contains the Default.aspx leftPane
Accessdata.Pane.LeftPane = new Object();
Accessdata.Pane.LeftPane.ClientID = null;

// Contains the Default.aspx rightPane
Accessdata.Pane.RightPane = new Object();
Accessdata.Pane.RightPane.ClientID = null;

// Contains helper functions for converting object to JSON object
Accessdata.JSON = new Object();

Accessdata.JSON.Replacer = function (key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}
Accessdata.JSON.Stringify = function (arg, replacer) {
    return JSON.stringify(arg, replacer);
}
Accessdata.JSON.StringifyWithReplacer = function (arg) {
    return JSON.stringify(arg, Accessdata.JSON.Replacer);
}

Accessdata.Telerik = new Object();

Accessdata.Telerik.RadDateTimePicker = new Object();
Accessdata.Telerik.RadDateTimePicker.SetDefaultToDateTimePart = function (sender, args) {
    var oldDate = args.get_oldDate();
    var newValue = args.get_newValue();
    var dateFormat = sender.get_dateFormat();
    var date = args.get_newDate();

    if (!oldDate && (newValue.indexOf(sender.get_dateFormatInfo().TimeSeparator) < 0 || (date &&
            date.getHours() == 0 &&
            date.getMinutes() == 0 &&
            date.getSeconds() == 0))) {
        date.setHours(23);
        date.setMinutes(59);
        sender.set_value(date.format(dateFormat));
    }
}

Accessdata.Telerik.ToolTip = new Object();
Accessdata.Telerik.ToolTip.Show = function (element, value) {
    var tooltipManager = $find('RadToolTipManager1');

    //If the user hovers the element before the page has loaded, there is no manager created
    if (!tooltipManager) return;

    //Find the tooltip for this element if it has been created 
    var tooltip = tooltipManager.getToolTipByElement(element);

    //Create a tooltip if no tooltip exists for such element 
    if (!tooltip) {
        tooltip = tooltipManager.createToolTip(element);

        if (!value)
            value = "";

        if (value == "")
            value = element.getAttribute("title");
        if (value == "")
                value = element.getAttribute("alt");

        tooltip.set_text(value);
    }

    //Let the tooltip's own show mechanism take over from here - execute the onmouseover just once
    element.onmouseover = null;

    //show the tooltip
    tooltip.show();
}

//Accessdata.Telerik.RadGrid = new Object();
//Accessdata.Telerik.RadGrid.Edit = new Object();

//Accessdata.Telerik.RadGrid.Edit.OnKeyPress = function(sender, args) {
//    if (args.get_keyCode() != 13)
//        return;

//    var el = Telerik.Web.UI.Grid.GetCurrentElement(args.get_domEvent());

//    //handles InPlace edit mode
//    if ($(el).parents("tr").attr("id") && $(el).parents("tr").attr("id") != "") {
//        sender.get_masterTableView().updateItem($(el).parents("tr")[0]);
//    } else {
//        //handles EditForms edit mode           
//        var editFrom = $(el).parents("tr:has(div)");
//        if (editFrom.length > 0 && editFrom.prev("tr").attr("id") != "") {
//            sender.get_masterTableView().updateItem(editFrom.prev("tr")[0]);
//        }
//    }
//}

Accessdata.Telerik.RadComboBox = new Object();
Accessdata.Telerik.RadComboBox.RequestItems = function (sender, eventArgs) {   
    sender.requestItems(sender.get_text(), false); 
}
Accessdata.Telerik.RadComboBox.RequestItemsOnce = function (sender, eventArgs) {
    if (sender.RequestItemsOnce)
        return;
    sender.RequestItemsOnce = true;
    //    sender.requestItems(sender.get_text(), false);
    Accessdata.Telerik.AjaxRequestWithTarget(sender._uniqueId, 'test');
}

Accessdata.Telerik.RadGridExportRequestDisableAjax = false;
Accessdata.Telerik.OnRadGridExport = function (sender, args) {
    var enableExport = false;
    if (args && args.get_eventTarget) {
        if (
           args.get_eventTarget().indexOf("ExportToExcelButton") >= 0
        || args.get_eventTarget().indexOf("ExportToWordButton") >= 0
        || args.get_eventTarget().indexOf("ExportToPdfButton") >= 0
        || args.get_eventTarget().indexOf("ExportToCsvButton") >= 0
        || args.get_eventTarget().indexOf("ExportToExcel") >= 0
        || args.get_eventTarget().indexOf("ExportToWord") >= 0
        || args.get_eventTarget().indexOf("ExportToPdf") >= 0
        || args.get_eventTarget().indexOf("ExportToCsv") >= 0
        ) {
            enableExport = true;
        }
    }
    if (Accessdata.Telerik.RadGridExportRequestDisableAjax) {
        enableExport = true;
        Accessdata.Telerik.RadGridExportRequestDisableAjax = false;
    }
    if (enableExport) {
        if (args && args.set_enableAjax) {
            //alert('args.set_enableAjax(false)');
            args.set_enableAjax(false);
        }
    }
}

Accessdata.Telerik.OnRequestStart = function (sender, args) {
    var enableExport = (args && args.get_eventTarget && args.get_eventTarget().indexOf("Export") >= 0) || Accessdata.Telerik.RadGridExportRequestDisableAjax;
    //alert('enableExport: ' + enableExport);
    if (enableExport) {
        Accessdata.Telerik.OnRadGridExport(sender, args);
    }
//    if (args && args.get_enableAjax && args && args.get_enableAjax() == true) {
//        args.EventTargetElement.disabled = true;
//    }
}
Accessdata.Telerik.OnRequestEnd = function (sender, args) {
//    args.EventTargetElement.disabled = false;
}

Accessdata.Telerik.Window = new Object();
Accessdata.Telerik.Window.DefaultWindowArguments = GetDefaultWindowArguments();
Accessdata.Telerik.Window.WindowBehaviors = ['None', 'Resize', 'Minimize', 'Close', 'Pin', 'Maximize', 'Move', 'Reload', 'Default'];

Accessdata.Telerik.Window.SetTitle = function (value) {

    var wnd = GetRadWindow();
    if (wnd)
        wnd.set_title(value);
}

Accessdata.Telerik.Window.EditCompetitor = new Object();
Accessdata.Telerik.Window.EditCompetitor.OnBeforeClose = function (sender, eventArgs) {
    eventArgs.set_cancel(!sender.IsCloseAllowed);
    if(sender.GetContentFrame().contentWindow.OnBeforeClose)
        sender.GetContentFrame().contentWindow.OnBeforeClose();
}
Accessdata.Telerik.Window.EditCompetitor.OnClose = function (sender, eventArgs) {
    if(sender.GetContentFrame().contentWindow.OnClose)
        sender.GetContentFrame().contentWindow.OnClose();
}

Accessdata.Telerik.Window.OnClientCommand = function (sender, eventArgs) {
}
Accessdata.Telerik.Window.OnClientResizeEnd = function (sender, eventArgs) {
}
Accessdata.Telerik.Window.OnClientResizeStart = function (sender, eventArgs) {
}
Accessdata.Telerik.Window.OnClientDragStart = function (sender, eventArgs) {
}
Accessdata.Telerik.Window.OnClientDragEnd = function (sender, eventArgs) {
}
Accessdata.Telerik.Window.OnClientPageLoad = function (sender, eventArgs) {
        if (sender.DefaultSettings) {
            if (sender.DefaultSettings.Title)
                sender.set_title(sender.DefaultSettings.Title);
            if (sender.DefaultSettings.Status)
                sender.set_status((new Date).toLocaleTimeString() + ': ' + sender.DefaultSettings.Status);
//            if (sender.DefaultSettings.IsModal)
//                sender.set_modal(sender.DefaultSettings.IsModal);
//            if(sender.DefaultSettings.Width && sender.DefaultSettings.Height)
//                sender.setSize(sender.DefaultSettings.Width, sender.DefaultSettings.Height);
        }
//    var originalUrl = Accessdata.Path.GetUrlDirectory(sender.get_navigateUrl());

//    if (originalUrl.EndsWith("/") == false)
//        originalUrl = originalUrl + "/";

//    //Change RadWindow icon to the favicon.ico icon of the opened site
//    var icon = $telerik.getElementByClassName(sender.get_popupElement(), "windowicon", "A");
//    if (icon) {
//        icon.style.background = "url(" + originalUrl + "favicon.ico) no-repeat 0 0";
//        //oWin._titleIconElement.style.background = "transparent url('" + iconUrl + "') no-repeat scroll 0px 0px";
//    }
}
Accessdata.Telerik.Window.OnClientActivate = function (sender, eventArgs) {
}
Accessdata.Telerik.Window.OnClientBeforeClose = function (sender, eventArgs) {
}
Accessdata.Telerik.Window.OnClientClose = function (sender, eventArgs) {
}
Accessdata.Telerik.Window.OnClientShow = function (sender, eventArgs) {
}

Accessdata.Telerik.Window.Confirm = function (title, question, callbackFunction, width, height) {
    if (!title)
        title = 'Bekräfta';
    if (!question)
        question = 'Är du säker?';
    if (!width)
        width = 330;
    if (!height)
        height = 100;
    if (!callbackFunction)
        callbackFunction = null;

    radconfirm('<h4>' + question + '</h4>', callbackFunction, width, height, null, title);
    return false;
}

Accessdata.Telerik.RadAjaxManager = new Object();
Accessdata.Telerik.RadAjaxManager.ClientID = null;
Accessdata.Telerik.RadAjaxManager.GetCurrent = function () {
    return $find(Accessdata.Telerik.RadAjaxManager.ClientID);
}

Accessdata.Telerik.AjaxRequest = function (callbackArgument) {
    if(Accessdata.Telerik.RadAjaxManager.ClientID)
        $find(Accessdata.Telerik.RadAjaxManager.ClientID).ajaxRequest(callbackArgument);
}

Accessdata.Telerik.AjaxRequestWithTarget = function (target, argument) {
    if (Accessdata.Telerik.RadAjaxManager.ClientID)
        $find(Accessdata.Telerik.RadAjaxManager.ClientID).ajaxRequestWithTarget(target, argument);
}

Accessdata.Telerik.Window.RadConfirmCallback = function (result, confirmArguments) {
    if (result) {
        if (confirmArguments) {
            if (confirmArguments.Target) {
                Accessdata.Telerik.AjaxRequestWithTarget(confirmArguments.Target, confirmArguments.Argument);
            }
            else {
                Accessdata.Telerik.AjaxRequest(confirmArguments.Argument);
            }
        }
    } else {
        if (confirmArguments && jQuery.isFunction(confirmArguments.OnAbortCallback)) {
            confirmArguments.OnAbortCallback();
        }
    }
}

Accessdata.Telerik.Window.RadConfirm = function (title, question, target, argument, onAbortCallback, width, height) {
    if (!title)
        title = 'Bekräfta';
    if (!question)
        question = 'Är du säker?';
    if (!width)
        width = 330;
    if (!height)
        height = 100;
    if (!target)
        target = null;
    if (!argument)
        argument = null;
    if (!onAbortCallback)
        onAbortCallback = null;

    var confirmArguments = new Object();
    confirmArguments.Target = target;
    confirmArguments.Argument = argument;
    confirmArguments.OnAbortCallback = onAbortCallback;

    function callBackFunction(result) {
        Accessdata.Telerik.Window.RadConfirmCallback(result, confirmArguments);
    }

    radconfirm('<h4>' + question + '</h4>', callBackFunction, width, height, null, title);
    return false;
}

Accessdata.Telerik.Window.SetBehaviors = function (window, behaviors) {
    var windowBehaviors = 0;
    for (var behavior in behaviors) {
        if (Accessdata.String.IsEmpty(behaviors[behavior]) == false) {
            if ($.inArray(behaviors[behavior], Accessdata.Telerik.Window.WindowBehaviors) > 0) {
                windowBehaviors += eval('Telerik.Web.UI.WindowBehaviors.' + behaviors[behavior]);
            }
        }
    }
    window.set_behaviors(windowBehaviors);
}

Accessdata.Telerik.Window.RemoveDefaultOnClose = function (window) {
    if (window) {
        window.remove_close(window.OnClose);
    }
}

Accessdata.Telerik.OpenWindow = function (windowArgs, wnd) {
    var defaultWindowArgs = GetDefaultWindowArguments();

    for (var index in defaultWindowArgs) {
        if (typeof windowArgs[index] == 'undefined')
            windowArgs[index] = defaultWindowArgs[index];
    }

    if (!wnd)
        wnd = GetMainWindow().radopen(windowArgs.Url, windowArgs.WindowName);
    else {
        // Clear old content
        wnd.GetContentFrame().contentWindow.document.write('<html><title></title><body></body></html>');
        wnd.SetUrl(windowArgs.Url);
    }

    wnd.hide();
    wnd.DefaultSettings = windowArgs;

    wnd.setSize(windowArgs.Width, windowArgs.Height);
    wnd.set_modal(windowArgs.IsModal);
    wnd.set_visibleTitlebar(windowArgs.ShowTitle);
    wnd.set_visibleStatusbar(windowArgs.ShowStatus);

    if (windowArgs.IconUrl) {
        wnd.set_iconUrl(windowArgs.IconUrl);
        wnd._titleIconElement.style.background = "transparent url('" + windowArgs.IconUrl + "') no-repeat scroll 0px 0px";
    }

    if (windowArgs.OnClose) {
        wnd.OnClose = windowArgs.OnClose;
        wnd.add_close(wnd.OnClose);
    }

    if (windowArgs.OnBeforeClose)
        wnd.add_beforeClose(windowArgs.OnBeforeClose);

    if (windowArgs.OnPageLoad)
        wnd.add_pageLoad(windowArgs.OnPageLoad);

    if (windowArgs.OnShow)
        wnd.add_show(windowArgs.OnShow);

    if (windowArgs.Title)
        wnd.set_title(windowArgs.Title);
    if (windowArgs.Status)
        wnd.set_status(windowArgs.Status);

    if (windowArgs.Behaviors)
        Accessdata.Telerik.Window.SetBehaviors(wnd, windowArgs.Behaviors);

    setTimeout(function () {
        wnd.setActive(true); wnd.show(); wnd.center();
    }, 100);

    return false;
}

Accessdata.Telerik.RedirectWindow = function (windowArgs) {
    return Accessdata.Telerik.OpenWindow(windowArgs, GetMainWindow().GetRadWindowManager().GetActiveWindow());
}

Accessdata.Load = function (targetId, url) {
    //    $('#' + targetId).load(url, function () {
    //    });
    //$(targetId).get(0)
    //$('#' + targetId).get(0).innerHTML = '<iframe id="' + targetId.toString() + 'Iframe" src="' + url + '" frameborder="0" style="width: 100%; height: 100%; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial;"></iframe>';

//    $.ajax({
//        type: "GET",
//        url: url,
//        dataType: "html",
//        error: function () {
//            $('#' + targetId).get(0).innerHTML = 'Ett fel uppstod när sidan laddades';
//        },
//        success: function (data) {
//            $('#' + targetId).get(0).innerHTML = '<iframe id="' + targetId.toString() + 'Iframe" src="" width="100%" height="100%" frameborder="0" style="width: 100%; height: 100%; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial;">' + $(data).html() + '</iframe>';
//        }
//    });
}

Accessdata.Telerik.TreeView = new Object();
Accessdata.Telerik.TreeView.OnClientNodeClicking = function (sender, eventArgs) {
//    var treeNode = eventArgs.get_node();
//    var text = treeNode.get_text();
//    var value = treeNode.get_value();
//    var attributes = treeNode.get_attributes();
//    var uniqueId = attributes.getAttribute("NodeId");
//    var targetId = attributes.getAttribute("TargetId");

//    if(uniqueId)
//    switch (uniqueId) {
//        case "Profile":
//            if (targetId && value) {
//                Accessdata.Load(targetId, value);
//            }
//            break;
//        case "Profile.Equipment":
//            if (targetId && value) {
//                Accessdata.Load(targetId, value);
//            }
//            break;
//    }
    //eventArgs.set_cancel(true);
}
Accessdata.Telerik.TreeView.OnClientNodeClicked = function (sender, eventArgs) {

}

Accessdata.Telerik.ComboBox = new Object();
Accessdata.Telerik.ComboBox.Clear = function (sender, eventArgs) {
    if (sender) {
        try {
            //sender.clearSelection();
            //sender.set_text("");
            //sender.set_value("");
        } catch (ex) { }
    }
}

Accessdata.jQuery = new Object();
Accessdata.jQuery.ResizeToParent = function (content, $parent) {
    try {
        //var output = '';
        var height = $parent.height(); // 
        //output = output + '\nparent height: ' + height;
        height = $('div#statusbar').position().top - $parent.position().top - 1;

        //output = output + '\nafter statusbar height: ' + height;
        $parent.children('div').each(function (index) {
            if (this != content) {
                height = height - $(this).height() - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom'));
                //output = output + '\nafter internal control(' + (this != content) + ',' + $parent.children()[index].id + '): ' + height + ' -(' + ($(this).height() - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom'))) + ')';
            }
        });
        //output = output + '\ncalculated height: ' + height;

        //alert(output);
        $(content).css('height', height);
    }
    catch (ex) {
        alert('Exception: ' + ex);
    }
}

Accessdata.ResizeObjects = function () {
    $('.AccessdatajQueryAutoHeight').each(function (index) {
        Accessdata.jQuery.ResizeToParent(this, $(this).parent());
    });
}
Accessdata.ResizeWindow = function () {
    window.resizeBy(-1, -1);
    setTimeout("window.resizeBy(1, 1);", 500);
}
Accessdata.ResizeWindowTo = function (width, height) {
    if (width && height) {
        if (window.outerWidth) {
            window.outerWidth = width;
            window.outerHeight = height;
        }
        else if (window.resizeTo) {
            window.resizeTo(width, height);
        }
        else {
            //alert("Not supported.");	
        }
    }
}

Accessdata.Window = new Object();
Accessdata.Window.ClientWidth = function() {
    return Accessdata.Window._filterResults(
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
Accessdata.Window.ClientHeight = function() {
    return Accessdata.Window._filterResults(
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
Accessdata.Window._filterResults = function(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

Accessdata.Window.AddOnLoad = function(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

Accessdata.Window.Print = function () {
    window.print();
}

Accessdata.Initialize = function () {
    $(window).resize(function () {
        Accessdata.ResizeObjects();
    });
    Accessdata.ResizeObjects();
    if (Telerik && Telerik.Web && Telerik.Web.UI && Telerik.Web.UI.RadWindow && Telerik.Web.UI.RadWindow.prototype)
        Telerik.Web.UI.RadWindow.prototype.IsCloseAllowed = true;
}



$(document).ready(function () {
    Accessdata.Initialize();
});

