﻿function ClickButton(btnId) {
    var btn = $get(btnId);
    if (btn == null) return;
    btn.click();
}

function IsPageValid() {
    //runs all validators check
    if (typeof (Page_Validators) == "undefined") return false;
    for (idx in Page_Validators) {
        var validator = Page_Validators[idx];
        ValidatorValidate(validator);
        if (!validator.isvalid) {
            return false;
        }
    }
    return true;
}

//displays the calendar popup at above the textbox
function CalendarPopupAbove(e, pickerID) {
    var datePicker = $find(pickerID);

    if (datePicker != null) {
        var textBox = datePicker.get_textBox();
        var popupElement = datePicker.get_popupContainer();

        var dimensions = datePicker.getElementDimensions(popupElement);
        var position = datePicker.getElementPosition(textBox);

        datePicker.showPopup(position.x, position.y - dimensions.height);
    }
}

//displays the time popup above the input
function TimePopupAbove(e, pickerID) {
    var timePicker = $find(pickerID);
    if (timePicker != null) {

        var textBox = timePicker.get_textBox();
        var popupElement = timePicker.get_timePopupContainer();

        var dimensions = timePicker.getElementDimensions(popupElement);
        var position = timePicker.getElementPosition(textBox);

        timePicker.showTimePopup(position.x, position.y - dimensions.height);
    }
}

//toggles the treenode on click
function OnTreeViewClientNodeClicked(sender, args) {
    var node = args.get_node();
    if (!node.get_expanded()) {
        node.set_expanded(true);
    }

}

//select node when right clicked and menu is showing
function OnTreeViewClientContextMenuShowing(sender, args) {
    var treeNode = args.get_node();
    treeNode.set_selected(true);
}


//prevents on click event if the same node is clicked twice.
function OnTreeViewClientNodeClicking(sender, args) {
    var treeNode = args.get_node();
    if (treeNode != null && treeNode.get_selected()) {
        args.set_cancel(true);
    }
}


function OnTreeViewNodeClickingPreventSelectable(sender, args) {
    var node = args.get_node();

    var tree = node.get_treeView();
    tree.trackChanges();

    var attribs = node.get_attributes();
    var type = attribs.getAttribute("IsSelectable");
    if (type == "False") {
        args.set_cancel(true);
    }

    tree.commitChanges();

    if (node.get_selected()) {
        args.set_cancel(true);
    }
}


//opens task window
function WindowManager_OpenTask(taskTitle, url, width, height, onClose) {
    var timestamp = new Date().getTime();

    var oWindow = window.radopen(url, "e3" + timestamp);
    oWindow.set_visibleStatusbar(false);
    oWindow.set_title(taskTitle);
    oWindow.set_status(taskTitle);
    oWindow.set_width(width);
    oWindow.set_height(height);
    oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Minimize + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Pin);
    if (onClose != null) {
        oWindow.add_close(onClose);
    }

    oWindow.center();
}


function WindowManager_OpenBrowserWindow(title, url, width, height, onClose, modal, windowArgument) {
    var timestamp = new Date().getTime();

    var browser = WM_GetBrowserWindow();
    var oWindow = browser.radopen(url, "e3" + timestamp);
    oWindow.set_visibleStatusbar(false);
    oWindow.set_title(title);
    oWindow.set_status(title);
    oWindow.set_width(width);
    oWindow.set_height(height);
    if (windowArgument != null) {
        oWindow.argument = windowArgument;
    }

    if (onClose != null) {
        oWindow.add_close(onClose);
    }

    if (modal != null && modal == true) {
        oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Close);
        oWindow.set_modal(true);
        oWindow.togglePin();
    }
    else {
        oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Minimize + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Pin);
    }

    window.setTimeout(function () {
        oWindow.setActive(true);
        oWindow.center();
    }, 0);
}

function WindowManager_OpenModal(title, url, width, height, onClose) {
    var timestamp = new Date().getTime();
    var oWindow = window.radopen(url, "e3" + timestamp);
    oWindow.set_visibleStatusbar(false);
    oWindow.set_title(title);
    oWindow.set_status(title);
    oWindow.set_width(width);
    oWindow.set_height(height);
    oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Close);
    oWindow.set_modal(true);
    oWindow.togglePin();
    if (onClose != null) {
        oWindow.add_close(onClose);
    }

    oWindow.center();
}

function WindowManager_OpenMovableModal(title, url, width, height, onClose) {
    var timestamp = new Date().getTime();
    var oWindow = window.radopen(url, "e3" + timestamp);
    oWindow.set_visibleStatusbar(false);
    oWindow.set_title(title);
    oWindow.set_status(title);
    oWindow.set_width(width);
    oWindow.set_height(height);
    oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Move);
    oWindow.set_modal(true);
    if (onClose != null) {
        oWindow.add_close(onClose);
    }

    oWindow.center();
}

function WM_GetRadWindow() {
    var oWindow = null;
    if (window.radWindow)
        oWindow = window.radWindow;
    else if (window.frameElement == null)
        return null;
    else if (window.frameElement.radWindow)
        oWindow = window.frameElement.radWindow;
    return oWindow;
}

function WM_GetBrowserWindow() {
    var wind = WM_GetRadWindow();
    if (wind == null) {
        return window;
    }
    var browser = wind.BrowserWindow;
    if (browser.frameElement == null) {
        return browser;
    }

    if (browser.parent && browser.parent.frameElement == null) {
        return browser.parent;
    }
    return browser;
}


function Attach(eventName, func) {
    try {
        var body = document.getElementsByTagName('body');
        if (body.attachEvent) {
            body.attachEvent(eventName, func);
        }
        else if (body.addEventListener) {
            body.addEventListener(eventName, func);
        }
    }
    catch (ex) {
        alert(ex);
    }
}


//the following code use radconfirm to mimic the blocking of the execution thread.
//The approach has the following limitations:
//1. It works only for elements that have *click* method, e.g. links and buttons
//2. It cannot be used in if(!confirm) checks
window.blockConfirm = function (text, mozEvent, oWidth, oHeight, callerObj, oTitle) {
    var ev = mozEvent ? mozEvent : window.event; //Moz support requires passing the event argument manually
    //Cancel the event
    ev.cancelBubble = true;
    ev.returnValue = false;
    if (ev.stopPropagation) ev.stopPropagation();
    if (ev.preventDefault) ev.preventDefault();

    //Determine who is the caller
    var callerObj = ev.srcElement ? ev.srcElement : ev.target;

    //Call the original radconfirm and pass it all necessary parameters
    if (callerObj) {
        //Show the confirm, then when it is closing, if returned value was true, automatically call the caller's click method again.
        var callBackFn = function (arg) {
            if (arg) {
                callerObj["onclick"] = "";
                if (callerObj.click) callerObj.click(); //Works fine every time in IE, but does not work for links in Moz
                else if (callerObj.tagName == "A") //We assume it is a link button!
                {
                    try {
                        eval(callerObj.href)
                    }
                    catch (e) { }
                }
            }
        }

        radconfirm(text, callBackFn, oWidth, oHeight, callerObj, oTitle);
    }
    return false;
}

//Gets true or false based on Task navigate url if we need to refresh the page.
//Page should be refreshed for: Delete, Move, Rename, Identification
function checkTaskForReload(url) {
    try {
        if (url == null) {
            return false;
        }

        if (typeof (url) != 'string') {
            return false;
        }
        var lowerUrl = url.toLowerCase();

        var idx = lowerUrl.indexOf('objectdelete.aspx');
        if (idx > 0) return true;

        idx = lowerUrl.indexOf('deleteobjects.aspx');
        if (idx > 0) return true;

        idx = lowerUrl.indexOf('objectrename.aspx');
        if (idx > 0) return true;

        idx = lowerUrl.indexOf('objectmove.aspx');
        if (idx > 0) return true;

        idx = lowerUrl.indexOf('identification.aspx');
        if (idx > 0) return true;

        idx = lowerUrl.indexOf('adiruserrename.aspx');
        if (idx > 0) return true;

        idx = lowerUrl.indexOf('gwuserrename.aspx');
        if (idx > 0) return true;

        idx = lowerUrl.indexOf('adirobjectundelete.aspx');
        if (idx > 0) return true;

        var idx = lowerUrl.indexOf('searchgroupmembers.aspx');
        if (idx > 0) {
            try {
                SetChangeList("");
                SetCSVSearch("");
                SetGroupSearch("1");
            } catch (err) {
            }

            return true;
        }

        return false;
    }
    catch (ex) {
        return false;
    }
}

//Enables the rad decorated button
function EnableButton(btn) {
    if (btn != null) {
        var enabledcss = 'rfdSkinnedButton';
        btn.parentNode.className = 'rfdSkinnedButton';
        btn.removeAttribute('disabled');
        btn.parentNode.removeAttribute('disabled');
    }
}

function StopPropagation(e) {
    //cancel bubbling
    e.cancelBubble = true;
    if (e.stopPropagation) {
        e.stopPropagation();
    }
}

function CloseCurrentToolTip() {
    try {
        var tt = Telerik.Web.UI.RadToolTip.getCurrent();
        if (tt == null || tt == undefined) {
            return;
        }
    }
    catch (ex) {
        return;
    }

    tt.hide();
}

function ToggleDiv(div, show) {
    if (show == true) {
        div.style["display"] = "block";
    }
    else {
        div.style["display"] = "none";
    }
}

Date.prototype.getTicks = function (date) {
    this.day = date.getDate();
    this.month = date.getMonth() + 1;
    this.year = date.getFullYear();
    this.hour = date.getHours();
    this.minute = date.getMinutes();
    this.second = date.getSeconds();
    this.ms = date.getMilliseconds();

    this.monthToDays = function (year, month) {
        var add = 0;
        var result = 0;
        if ((year % 4 == 0) && ((year % 100 != 0) || ((year % 100 == 0) && (year % 400 == 0)))) add++;

        switch (month) {
            case 0: return 0;
            case 1: result = 31; break;
            case 2: result = 59; break;
            case 3: result = 90; break;
            case 4: result = 120; break;
            case 5: result = 151; break;
            case 6: result = 181; break;
            case 7: result = 212; break;
            case 8: result = 243; break;
            case 9: result = 273; break;
            case 10: result = 304; break;
            case 11: result = 334; break;
            case 12: result = 365; break;
        }
        if (month > 1) result += add;
        return result;
    }

    this.dateToTicks = function (year, month, day) {
        var a = parseInt((year - 1) * 365);
        var b = parseInt((year - 1) / 4);
        var c = parseInt((year - 1) / 100);
        var d = parseInt((a + b) - c);
        var e = parseInt((year - 1) / 400);
        var f = parseInt(d + e);
        var monthDays = this.monthToDays(year, month - 1);
        var g = parseInt((f + monthDays) + day);
        var h = parseInt(g - 1);
        return h * 864000000000;
    }

    this.timeToTicks = function (hour, minute, second) {
        return (((hour * 3600) + minute * 60) + second) * 10000000;
    }

    return this.dateToTicks(this.year, this.month, this.day) + this.timeToTicks(this.hour, this.minute, this.second) + (this.ms * 10000);
}


//tests internet connection
function testConnection(emptyDivId, callBack, imgUrl) {
    var ticks = new Date().getTicks(new Date());
    if (imgUrl == null) {
        imgUrl = 'http://downloads.omni-ts.com/econtrol/content/images/testConn.gif?' + ticks;
    }
    $get(emptyDivId).innerHTML +=
        '<img id="internetConnectionTestImage" style="display: none;" ' +
        'src="' + imgUrl + '" ' +
        'onerror="testConnectionCallback(false);" ' +
        'onload="testConnectionCallback(true);">';

    testConnectionCallback = function (result) {
        callBack(result);
        var element = document.getElementById('internetConnectionTestImage');
        element.parentNode.removeChild(element);
    }
}

function EnsureSelectedItemVisible(listBox, args) {
    if (listBox == null) {
        return;
    }
    var item = listBox.get_selectedItem();
    if (item == null) {
        return;
    }
    item.select();
    item.ensureVisible();
}
