﻿var debug2 = false;
var DebugElement = null;
var DebugContexts = "";
var DebugIgnoreContexts = "";

function PopUpShowing(sender, eventArgs) {
    var popUp = eventArgs.get_popUp();
    var popUpWidth = popUp.style.width.substr(0, popUp.style.width.indexOf("px"));
    var popUpHeight = popUp.style.height.substr(0, popUp.style.height.indexOf("px"));
    popUp.style.position = "fixed";
    popUp.style.left = "50%";
    popUp.style.top = "50%";
    popUp.style.marginLeft = "-" + (popUpWidth / 2).toString() + "px"; ;
    popUp.style.marginTop = "-" + (popUpHeight / 2).toString() + "px";
}

function HandleGridDoubleClickPostback(gridId, keyName) {
    var id = $find(gridId).get_masterTableView().get_selectedItems()[0].getDataKeyValue(keyName);

    __doPostBack(gridId, "rowDoubleClicked," + id);
}

function GetRadWindow() {
    var oWindow = null;
    if (window.radWindow) oWindow = window.radWindow;
    else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
    return oWindow;
}

function CloseWindow() {
    var oWnd = null;
    try { oWnd = GetRadWindow(); } catch (e) { }
    if (oWnd != null)
        oWnd.Close();
    else
        ClosePopupWindow("");
}

function CloseRadWindow(returnValue) {
    var oWnd = null;
    try { oWnd = GetRadWindow(); } catch (e) { }
    if (oWnd != null) {
        if (returnValue == null) returnValue = oWnd.cancelReturnValue;
        oWnd.returnValue = returnValue;
        oWnd.Close();

        // Exit if not supposed to refresh
        if (oWnd.refresh != true) return;

        if (oWnd.alwaysRefresh == true || (oWnd.returnValue != oWnd.cancelReturnValue)) {
            try {
                oWnd.BrowserWindow.__doPostBack(oWnd.refreshElement, oWnd.returnValue);
            }
            catch(e)
            {
            }
        }
    } else {
        ClosePopupWindow(returnValue);
    }
}

function OpenRadWindow(url, modal, width, height, name, cancelReturnValue, title, refresh, refreshElement, closeMethod, behaviors) {
    var oManager = GetRadWindowManager();
    if (oManager == null) {
        alert("No Rad manager is available");
        return;
    } 
    Wnd = oManager.open(url, name);
    Wnd.setSize(width, height);
    Wnd.set_title(title);
    Wnd.setActive(true);
    Wnd.SetModal(true);
    Wnd.set_showContentDuringLoad(true);
    Wnd.center();
    Wnd.refresh = (refresh == null) ? false : refresh;
    Wnd.cancelReturnValue = cancelReturnValue;
    Wnd.returnValue = cancelReturnValue;
    if (behaviors != null)
        Wnd.set_behaviors(behaviors);

    if (closeMethod != null && closeMethod != "")
        Wnd.add_close(closeMethod);

    if (refreshElement == null) refreshElement = "custom";
    Wnd.refreshElement = refreshElement;
    Wnd.set_iconUrl("/images/rwPickNote.png");
    Wnd._titleIconElement.style.background = "transparent url('/images/rwPickNote.png') no-repeat scroll 0px 0px";
}

function OpenRadWindowDelay(url, modal, width, height, name, cancelReturnValue, title, refresh, refreshElement, behaviors) {
    window.setTimeout("OpenRadWindow('" + url + "'," + modal + "," + width + "," + height + ",'" + name + "','" + cancelReturnValue + "','" + title + "'," + refresh + ",'" + refreshElement + "', '" + behaviors + "');", 500);
    return;
}

function ShowComboBoxList(sender, args) {
    sender.showDropDown();
}

function HideComboBoxList(sender, args) {
    sender.hideDropDown();
}

function GetParentElement(startingElement, partialName) {
    if (IsMatch(startingElement, partialName)) return startingElement;

    if (startingElement.parentNode != null)
        return GetParentElement(startingElement.parentNode, partialName);
    else
        return null;
}

function GetRelativeControl(partialName, obj) {
    var currentControl = obj;
    var parentControl = GetParentElement(currentControl, "tdRatingCell");

    // Check current control
    if (IsMatch(parentControl, partialName))
        return currentControl;

    // Check sibling controls
    for (var i = 0; i < parentControl.childNodes.length; i++) {
        var control = parentControl.childNodes[i];
        if (IsMatch(control, partialName))
            return control;
    }
    return null;
}

function IsMatch(element, partialName) {
    if (element.id == null || element.id == '')
        return false;
    if (element.id.indexOf(partialName, 0) >= 0)
        return true;
    return false;
}

function ToggleVisibility(obj, controlName) {
    var control = document.getElementById(controlName);
    if (control == null)
        return;

    if (control.style.display == "none")
        control.style.display = "";
    else
        control.style.display = "none";
}

function ToggleVisibilityWithImage(obj, controlName, expandImage, contractImage) {
    var img = obj;
    var control = document.getElementById(controlName);

    if (control == null || img == null)
        return;

    if (control.style.display == "none") {
        control.style.display = "";
        img.src = contractImage;
    }
    else {
        control.style.display = "none";
        img.src = expandImage;
    }
}

function ToggleVisibilityWithText(obj, controlName, expandText, contractText) {
    var img = obj;
    var control = document.getElementById(controlName);

    if (control == null || img == null)
        return;

    if (control.style.display == "none") {
        control.style.display = "";
        obj.innerHTML = contractText;
    }
    else {
        control.style.display = "none";
        obj.innerHTML = expandText;
    }
}

function ClosePopupWindow(retVal) {
    DisplayDebugMessage("Close Window RetVal=" + retVal, "CloseWindow");
    window.top.returnValue = retVal;
    window.top.close();
}

function RemoveNavigationMenu() {
    if (window.opener == null) {
        var Border = 30;
        var nTop = 5;
        var nLeft = 5;
        var nWidth = window.screen.width - 20;
        var nHeight = window.screen.availHeight - 50;
        var options = "titlebar=no,statusbar=yes,menu=false,scroll=yes,resizable=yes,width=" + nWidth + ",height=" + nHeight + ",left=" + nLeft + ",top=" + nTop;
        window.open(location.href, "main", options);
        window.opener = self;
        window.top.close();
    }
}

function AddLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function')
        window.onload = func;
    else {
        window.onload = function() {
            if (oldonload) oldonload();
            func();
        }
    }
}

function SetupDebugging() {
    debug2 = true;
    DebugElement = document.createElement("<TextArea Id='DebugText' tabIndex='99999' rows='20' cols='120' name='Debugtext'></TextArea>");
    document.body.insertBefore(DebugElement);
    DebugElement.value = "Debuging has been setup!";
}

function DisplayDebugMessage(message, context) {
    if (!isValidContext(context))
        return false;

    if (DebugElement != null) {
        var NewText = DebugElement.value + "\n" + context + " - " + message
        DebugElement.value = NewText
    }
    else {
        if (debug2)
            alert(context + " - " + message);
    }
}

function isValidContext(context) {
    if ((DebugContexts == "") && (DebugIgnoreContexts == ""))
        return true;

    if (context == "undefined")
        return false;

    // Determine if context should be ignored
    if (DebugIgnoreContexts != "") {
        var list = DebugIgnoreContexts.split(",");

        for (var j = 0; j < list.length; j++) {
            if (context.indexOf(list[j]) > -1)
                return false;
        }
    }

    // Determine if context should be valid
    if (DebugContexts != "") {
        var list2 = DebugContexts.split(",");
        for (var k = 0; k < list2.length; k++) {
            if (context.indexOf(list2[k]) > -1)
                return true;
        }
        return false;
    }
    return true;
}

function FormatCurrency(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return '$' + FormatCommas(s);
}

function FormatCommas(amount) {
    var delimiter = ","; // replace comma if desired
    var a = amount.split('.', 2)
    var d = a[1];
    var i = parseInt(a[0]);
    if (isNaN(i)) { return ''; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while (n.length > 3) {
        var nn = n.substr(n.length - 3);
        a.unshift(nn);
        n = n.substr(0, n.length - 3);
    }
    if (n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if (d.length < 1) { amount = n; }
    else { amount = n + '.' + d; }
    amount = minus + amount;
    return amount;
}

function Highlight(obj) {
    var object = obj ? obj : window.event.srcElement;
    if (object == null)
        return;

    try {
        object.select();
    }
    catch (e) {
    }
}

// Performs a custom postback using the 'custom' event target
function RefreshPage(eventArg, refreshElement) {
    if ((refreshElement == undefined) || (refreshElement == "undefined") || refreshElement == null) {
        refreshElement = 'custom';
    }

    DisplayDebugMessage("Event Arg = " + eventArg, "RefreshPage");
    if (__doPostBack)
        __doPostBack(refreshElement, eventArg);
    else
        location.href = location.href;
}

//    String script = String.Format("OpenChildWindow('{0}',{1},{2}, {3}, {4}, '{5}', '{6}', {7},{8},{9},'{10}');", args.Url, JSBool(args.Modal), JSBool(args.AllowResize), args.Width, args.Height, args.Name, args.CancelReturnValue, JSBool(args.ShowToolbar), JSBool(args.ShowScrollBar), JSBool(args.RefreshAfter), JSBool(args.ForceRefresh),args.RefreshElement);


function OpenChildWindow(url, modal, AllowResize, Width, Height, Name, CancelReturnValue, showToolbar, showLocationbar, showScrollBar, refresh, alwaysRefresh, refreshElement) {
    modal = (modal == null) ? false : modal;
    var nWidth = (Width == null) ? self.document.body.clientWidth * 0.85 + "px" : Width;
    var nHeight = (Height == null) ? self.document.body.clientHeight * 0.85 + "px" : Height;

    AllowResize = (AllowResize == null) ? true : AllowResize;
    var blnRefresh = (refresh == null) ? true : refresh;
    var strresizable = (AllowResize == true) ? "yes" : "no";
    var strToolbar = (showToolbar == true) ? "yes" : "no";
    var strLocationBar = (showLocationbar == true) ? "yes" : "no";
    var strScrollBar = (showScrollBar == true) ? "yes" : "no";
    var blnAlwaysRefresh = (alwaysRefresh == null) ? false : alwaysRefresh;

    if (modal == true) {
        DisplayDebugMessage("Open url " + url, "OpenChildWindow");

        var result = window.showModalDialog(url, null, "center:yes;help:no;resizable:" + strresizable + ";scroll:" + strScrollBar + ";status:no;dialogHeight:" + nHeight + "px;dialogWidth:" + nWidth + "px;");

        if ((result == undefined) || (result == "undefined") || result == null) {

            result = CancelReturnValue;

        }

        DisplayDebugMessage("Result " + result, "OpenChildWindow");

        if (blnAlwaysRefresh || ((result != CancelReturnValue) && blnRefresh))
            RefreshPage(result, refreshElement);

        return result;
    }
    else {
        //center the new window on the existing window
        var nLeft = self.screenLeft + ((self.document.body.clientWidth / 2) - (parseInt(nWidth) / 2));
        var nTop = self.screenTop + ((self.document.body.clientHeight / 2) - (parseInt(nHeight) / 2));

        var win = window.open(url, Name, "titlebar=" + strToolbar + ",statusbar=yes,location=" + strLocationBar + ",toolbar=yes,scrollbars=" + strScrollBar + ",resizable=" + strresizable + ",width=" + nWidth + ",height=" + nHeight + ",left=" + nLeft + ",top=" + nTop);

        return win;
    }
}
//Navigation jQuery
function openContextMenu(clientId, e) {
    var contextMenu = $find(clientId);
    if ((!e.relatedTarget) || (!$telerik.isDescendantOrSelf(contextMenu.get_element(), e.relatedTarget))) {
        contextMenu.show(e);
    }
    $telerik.cancelRawEvent(e);
}

function quickSearch(obj, e) {
    var Key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
    if (Key == 13) {
        window.location.href = "/BackingTracks/FreeGuitarBackingTracks.aspx?searchKey=" + obj.value;
        return false;
    }
}

//Utilize hot-keys to for Telerik's Date Picker control
function dateTimePickerNow(sender, e) {
    var unicode = e.keyCode ? e.keyCode : e.charCode
    //var keyChar = String.fromCharCode(unicode);

    switch (unicode) {
        case 84: //T
            sender.value = GetCurrentDate() + " " + GetCurrentTime();
            //Return 'false' so the pressed key isn't entered into the date picker
            return false;

        case 116: //t
            sender.value = GetCurrentDate() + " " + GetCurrentTime();
            //Return 'false' so the pressed key isn't entered into the date picker
            return false;
        default:
            return true;
    }
    //For checking unicode for the pressed key
    //alert(unicode);
}

//Utilize hot-keys to for Telerik's Date Picker control
function datePickerToday(sender, e) {
    var unicode = e.keyCode ? e.keyCode : e.charCode

    switch (unicode) {
        // Up arrow 
        case 38:
            if (sender.value) {
                var newValue = new Date(AddDays(sender.value, 1));
                sender.value = formatDate(newValue);
            }
            return false;

            // Down arrow
        case 40:
            if (sender.value) {
                var newValue = new Date(AddDays(sender.value, -1));
                sender.value = formatDate(newValue);
            }
            return false;

        case 84: //T
            sender.value = GetCurrentDate();
            //Return 'false' so the pressed key isn't entered into the date picker
            return false;

        case 116: //t
            sender.value = GetCurrentDate();
            //Return 'false' so the pressed key isn't entered into the date picker
            return false;
    }
}

//Returns the current date in M/D/Y format
function GetCurrentDate() {
    var d = new Date();
    return formatDate(d);
}

function GetCurrentTime() {
    var curDateTime = new Date();
    var curHour = curDateTime.getHours();
    var curMin = curDateTime.getMinutes();
    var curTime = ((curHour < 10) ? "0" : "") + curHour + ":" + ((curMin < 10) ? "0" : "") + curMin;
    return curTime;
}

function AddDays(date, days) {
    var myDate = new Date(date);
    return myDate.setDate(myDate.getDate() + days);
}

function formatDate(date) {
    var d = new Date(date);
    var thisYear = d.getFullYear();

    // JavaScript month starts on 0 = January
    var thisMonth = d.getMonth() + 1;
    if (thisMonth < 10)
        thisMonth = "0" + thisMonth;

    var thisDate = d.getDate();
    if (thisDate < 10)
        thisDate = "0" + thisDate;
    return thisMonth + "/" + thisDate + "/" + thisYear;
}

//Rounds NumericTextBox fields to the quarter hour
function QuarterHourRound(sender) {
    if (sender.value != "") {
        var newVal = Math.round(sender.value * 4) / 4;
        if (newVal - Math.floor(newVal) == .5)
            newVal += "0";
        else if (newVal - Math.floor(newVal) == 0)
            newVal += ".00";
        sender.value = newVal;
    }
}

// Captures the "Tab" key and sets the highlightedItem as selected before leaving the field
function RadComboKeyPress(comboBox, eventArgs) {
    var keyCode = eventArgs.get_domEvent().keyCode;
    if (keyCode == 9) {
        try {
            comboBox.get_highlightedItem().select();
        }
        catch (err) {
            return;
        }
    }
}

// Scheculer losing focus on datePicker fields in IE
function setFocus(sender) {
    var IE = /*@cc_on!@*/false;
    if (IE) {
        if (sender.focused)
            return;

        sender.focus();
        sender.select();
    }
}

/* Print contents of element */
function printContainer(containerId)
{
    var container = document.getElementById(containerId);
    var windowObject = window.open('', "Print","width=950,height=500,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
    
    windowObject.document.writeln(container.innerHTML);
    windowObject.document.close();
    windowObject.focus();
    windowObject.print();
    clientSleep(3000);
    windowObject.close();
}

/* Pause the client */
function clientSleep(miliSeconds) 
{
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); } 
    while(curDate-date < miliSeconds);
}
    
/* Adding eventListeners to the DOM via this method 
will allow you to add more than one event listener.
We don't have to hard code it on the tag. */
if (window.addEventListener) { //For Mozilla.
    window.addEventListener("load", registerNS, false);
} else if (window.attachEvent) { // For IE.
    window.attachEvent("onload", registerNS);
}

/* registerNS adds additional namespaces. It doesn't get fired until the page load event.
It reuses the ASP.NET AJAX library to register the namespace.... 
... Type.registerNamespace() ...
For more details see Type Class in Global Namespace of the ASP.NET AJAX reference.
http://ajax.asp.net/docs/ClientReference/default.aspx */
function registerNS() {
    Type.registerNamespace('Ethos.Utilities');

    Ethos.Utilities.inspect = function(obj, justValues) {
        var stringBuffer = "";
        for (i in obj) {
            if (justValues) {
                stringBuffer += obj[i] + "\n\n";
            } else {
                stringBuffer += "" + i + ":\n\t " + obj[i] + "\n\n";
            }
        }
        if (window.debugService) {
            window.debugService.trace(stringBuffer);
            window.debugService.inspect(obj.toString(), obj);
        } else {
            document.write("<pre>" + stringBuffer + "</pre>");
            document.close();
        }
    }

    Ethos.Utilities.alert = function(ex, friendlyMessage) {
        if (window.debugService) { window.debugService.trace(ex.message); }
        if (window.debugService) { window.debugService.inspect(ex.toString(), ex); }
        alert(friendlyMessage);
    }

    Ethos.Utilities.print = function(htmlToPrint) {
        var stringBuffer = "";
        stringBuffer += '<html>';
        stringBuffer += '<body onload="window.print(); window.close();">';
        stringBuffer += htmlToPrint;
        stringBuffer += '</body>';
        stringBuffer += '</html>';
        var printWindow = window.open("", "printWindow", "directories=no,location=no,menubar=no,resizable=yes,status=yes,toolbar=no,scrollbars=yes,width=300,height=50,left=100,top=50,screenX=100,screenY=50'");
        printWindow.document.write(stringBuffer);
        printWindow.document.close();
    }

    String.prototype.IsNullOrEmpty = function() {
        var regEx = /^\s*$/;
        return regEx.test(this);
    }

    String.prototype.Trim = function() {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }

    String.prototype.RemoveRedundantWhitespace = function() {
        var result = this;
        var regEx = /^(\s*)([\W\w]*)(\b\s*$)/;
        if (regEx.test(result)) { result = result.replace(regEx, '$2'); }
        var regEx = / +/g;
        result = result.replace(regEx, " ");
        if (result == " ") { result = ""; }
        return result;
    }

    Type.registerNamespace('Ethos.Utilities.Cookies');
    Ethos.Utilities.Cookies.Set = function(name, value) {
        document.cookie = name + "=" + value + ";path=/;";
    }

    Ethos.Utilities.Cookies.Get = function(name) {
        var cookies = document.cookie.split("; ");
        for (var i = 0; i < cookies.length; i++) {
            var crumb = cookies[i].split("=");
            if (name == crumb[0]) {
                return unescape(crumb[1]);
            }
        }
        return null;
    }
}

EventDelegate = function() {
    this.Callbacks = [];
    this.Attach = function(func) {
        if (typeof (func) == "function") this.Callbacks.push(func);
    }
    this.Fire = function(params) {
        for (var i = 0; i < this.Callbacks.length; i++)
            this.Callbacks[i](params);
    }
}

/* Dashboard Scripts */
function rtsTop_ClientTabSelecting(sender, args) {
    var tab = args.get_tab();
    if (tab.get_value() == "AddDashboard") {
        args.set_cancel(true);
        ShowAddDashboardWindow();
    }
}

function ShowAddDashboardWindow() {
    var wnd = window.radopen("/Dashboards/PopUp/AddDashboard.aspx", "AddDashboard");
    wnd.setSize(550, 325);
    wnd.set_modal(true);
    wnd.add_close(CloseDashboardWindow);
    wnd.Center();
}

function CloseDashboardWindow(sender, arg) {
    //window.location.reload(true);
    window.location.href = window.location.href;
}

// Returns a number formatted with commas
function formatNumber(number) {
    number += '';
    x = number.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function calculateGpm(cost, revenue) {
    if (revenue == 0)
        return 0;

    // the * 100 / 100 is for rounding to 2 decimals
    return Math.round((revenue - cost) / revenue * 100 * 100) / 100;
}

function limitToNumeric(obj, e) {
    var keyCode, Shift;
    var insideFrames = (window.top.event == null)
    var object = obj;   //window.event.srcElement;

    if (object == null) {
        return;
    }
    e = e ? e : window.event;
    keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
    Shift = e.shiftKey;
    /*if (insideFrames) {
        keyCode = window.event.keyCode;
        Shift = window.event.shiftKey;
    } else {
        keyCode = window.top.event.keyCode;
        Shift = window.top.event.shiftKey;
    }*/
    
    //window.status = "KeyCode = " + keyCode;

    var ShiftOffset = 65536;

    if (Shift) {
        keyCode += ShiftOffset;
    }

    var numeric = (((keyCode - 48 >= 0) && (keyCode - 48 <= 9)) || ((keyCode - 96 >= 0) && (keyCode - 96 <= 9)))

    var otherkeys = "[8][9][65545][13]"

    /*if (object.SettingsObj != "undefined") {
        if (parseInt(object.SettingsObj.MinValue) < 0) {
            otherkeys = otherkeys + "[189][109]"
        }
    }*/

    if (String(object.value).search("\\.") == -1) {
        otherkeys += "[190][110]"
    }

    for (var i = 33; i <= 46; i++) {
        otherkeys += "[" + i + "][" + (i + ShiftOffset) + "]"
    }

    var other = (otherkeys.search("\\[" + keyCode + "\\]") != -1)

    if (!(numeric) && !(other)) {
        if (window.event)
            e.returnValue = false;
            //window.event.returnValue = false;
        else
            e.preventDefault();
    }


}

function LimitMaxLength(tb) {
    var max = parseInt($(tb).attr('maxlength'));
        
    if (max == 0) {
        max = parseInt($(tb).attr('maxlengthtextarea'));
    }

    if ($(tb).val().length > max) {
        $(tb).val($(tb).val().substr(0, $(tb).attr('maxlength')));
    }

    $(tb).parent().find('.charsRemaining').html('You have ' + (max - $(tb).val().length) + ' characters remaining');
}

