﻿var browser = {
    isIE: navigator.appName == "Microsoft Internet Explorer" ? true : false,
    isOpera: navigator.appName == "Opera" ? true : false,
    isFF: !document.all && document.getElementById && !this.isOpera
}

var divOverText = "Loading...";

function $(documentID) {
    if (document.all)//ie4
    {
        return document.all[documentID];
    }
    else if (document.getElementById) {//isIE6
        return document.getElementById(documentID);
    }
    else if (document.layers) {//isNS4
        return document.layers[documentID];
    }
    else if (document.getElementById && !document.all) {//isNS6
        return document.getElementById(documentID);
    }
}


function doNotAllowSelectionInDrp(index, sender) {
    if (sender.options.length <= 1)
        return;

    if (!sender.options[index].selected)
        return;

    if (index - 1 >= 0 && index - 1 < sender.options.length)
        sender.options[index - 1].selected = true;
    else if (index + 1 < sender.options.length)
        sender.options[index + 1].selected = true;
}

function addEvent(element, eventName, callback) {
    if (typeof (element) == "string")
        element = $(element);
    if (element == null)
        return;
    if (element.addEventListener)
        element.addEventListener(eventName, callback, false);
    else if (element.attachEvent)
        element.attachEvent("on" + eventName, callback);
}

function removeEvent(element, eventName, callback) {
    if (typeof (element) == "string")
        element = $(element);
    if (element == null)
        return;
    if (element.removeEventListener)
        element.removeEventListener(eventName, callback, false);
    else if (element.detachEvent)
        element.detachEvent("on" + eventName, callback);
}

function openPopup(url, target) {
    var _target = "WFSSPopup";
    if (null != target)
        _target = target;

    var settings = new popupSettings().getSettings(_target);
    window.open(url, _target,
                'status=' + settings.status +
                ',toolbar=' + settings.toolbar +
                ',menubar=' + settings.menubar +
                ',location=' + settings.location +
                ',scrollbars=' + settings.scrollbars +
                ',height=' + settings.height +
                ',width=' + settings.width +
                ',left=' + settings.left +
                ',top=' + settings.top);
}

function popupSettings() {
    this.width = 1020;
    this.height = 756;
    this.location = 0;
    this.scroolbars = 0;
    this.menubar = 0;
    this.toolbar = 0;
    this.status = 0;
    this.left = 0;
    this.top = 0;

    this.getAutoResponseSettings = function() {
        this.width = 700;
        this.height = 600;

        return this;
    }

    this.getTips = function() {
        this.width = 700; //620;
        this.height = 600; //300;

        return this;
    }

    this.getSettings = function(target) {
        switch (target.toLowerCase()) {
            case "autoresponse":
                return this.getAutoResponseSettings();
            case "tips":
                return this.getTips();
            default:
                return this;
        }
    }
}

var wndHTML = null;
var tempSender = null;
var _wTitle = '';
function openPopupWithHTML(page, sender, target, wTitle, evt, sourceTagName) {
    evt = (null == event) ? evt : event;
    if ('a' == evt.srcElement.tagName.toLowerCase())
        return;
    var _target = "WFSSPopupHTML";
    if (null != target)
        _target = target;
    if (null != wTitle)
        _wTitle = wTitle;

    var _page = "about:blank";
    if (null != page)
        _page = page;
    if (null == wndHTML || wndHTML.closed)
        wndHTML = window.open(_page, _target, 'status=no,toolbar=no,menubar=no,location=no,scrollbars=yes,height=756,width=1020,left=0,top=0');
    tempSender = sender;
    //debugger;
    setTimeout('wndHTML.document.body.innerHTML = tempSender.innerHTML;wndHTML.document.title=_wTitle;wndHTML.focus()');
}

//---------------------------------   Grid Style related -----------------------------------

var oldColor = '';
var oldSender = null;
function onGridRowMouseOver(sender, addPostBackRef, onClickCallBacks) {     //  debugger
    if (null == addPostBackRef)
        addPostBackRef = true;
    oldColor = sender.style.backgroundColor;
    sender.style.backgroundColor = '#FFFFDD';
    sender.style.cursor = 'pointer';
    sender.onclick = function() {   //debugger
        if (!addPostBackRef) {
            if (null != oldSender)
                oldSender.style.backgroundColor = '#FFFFFF';
            oldColor = sender.style.backgroundColor = '#FFEEFF';
            oldSender = sender;
            setTimeout(onClickCallBacks, 0);
            return;
        }
        var aList = sender.getElementsByTagName('a');
        for (var i = 0; i < aList.length; i++) {
            if (aList[i].href.indexOf('Select$') != -1) {
                if (aList[i].target)
                    window.open(aList[i].href, aList[i].target);
                else
                    window.location.href = aList[i].href;
                break;
            }
        }
    };
}

function onGridRowMouseOut(sender) {
    sender.style.backgroundColor = oldColor; //'#FFFFFF';
}

var repeaterItemOldColor = '';
function onRepeaterItemMouseOver(sender) {
    repeaterItemOldColor = sender.style.backgroundColor;
    sender.style.backgroundColor = '#FFFFDD';
    sender.style.cursor = 'pointer';
    sender.onclick = function() {

        var aList = sender.getElementsByTagName('a');
        for (var i = 0; i < aList.length; i++) {
            if (aList[i].id.indexOf('Select') != -1) {
                if (aList[i].target)
                    window.open(aList[i].href, aList[i].target);
                else
                    window.location.href = aList[i].href;
                break;
            }
        }
    };
}

function onRepeaterItemMouseOut(sender) {
    sender.style.backgroundColor = repeaterItemOldColor; //'#FFFFFF';
}

//---------------------------------  End Grid Style related -----------------------------------

function submitOnEnter(evt, linkButtonClientID, type) {//debugger;
    evt = (null != evt) ? evt : event;
    var keycode = '';
    if (evt.which)
        keycode = evt.which;
    else
        keycode = evt.keyCode
    if (keycode == 13) {
        if (null != type && type == "button")
            __doPostBack(linkButtonClientID, "");
        else
            window.location.href = $(linkButtonClientID).href;
    }
}

function messagesCheckSpell(ftb) {
    if (ftb.GetHtml() != '')
        ftb.NetSpell();
}

function AddBeginRequest(fn) {
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(fn);
}

function AddEndRequest(fn) {
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(fn);
}

function RemoveEndRequest(fn) {
    Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(fn);
}

function ValidateEmail(sender, asOneInstance, stringAlert) {
    if (sender.value == '')
        return true;
    var regEx = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
    if (asOneInstance) {
        if (!regEx.test(sender.value)) {
            alert(stringAlert);
            return false;
        }
    }
    else {
        var val = sender.value.replace(/ /g, '');
        var tokens = val.split(',');
        for (var i = 0; i < tokens.length; i++) {
            if (!regEx.test(tokens[i])) {
                alert(stringAlert);
                return false;
            }
        }
    }
    return true;
}

function GetBrowser() {
    if (navigator.appName == "Microsoft Internet Explorer")
        return "IE";
    return "NIE";
}

//*********************************************** treeview with checkboxes - check/uncheck feature for parent/childrens *******************************************

function initTree(treeViewClientID) {
    var treeElement = $(treeViewClientID);
    var inputList = treeElement.getElementsByTagName("input");
    for (var i = 0; i < inputList.length; i++) {
        if (inputList[i].type.toLowerCase() != "checkbox")
            continue;

        inputList[i].onclick = function() {
            var childNodesContainer = $(this.id.replace("CheckBox", "Nodes"));
            if (childNodesContainer == null)
                return;
            var childCheckBoxList = childNodesContainer.getElementsByTagName("input");
            for (var j = 0; j < childCheckBoxList.length; j++) {
                if (childCheckBoxList[j].type.toLowerCase() != "checkbox")
                    continue;
                childCheckBoxList[j].checked = this.checked;
            }
        }
    }
}

//*********************************************** SESSION TIMEOUT ********************************************

var sessionTimeout = null; //= 20 * 60 * 1000 - 25 * 1000;//milliseconds
var sessionTimeoutTracker = sessionTimeout;
var counter = 30; //seconds
var sessionIntervalID = null;
var trackSessionIntervalID = null;
var sessionTimeoutID = null;
var msg;

function StartSessionTracking() {
    sessionTimeoutTracker = sessionTimeout - (counter + 5) * 1000;
    try {
        clearInterval(trackSessionIntervalID);
    } catch (e) { }
    //window.status = "StartSessionTracking";
    updateSessionDiv();
    trackSessionIntervalID = setInterval("TrackSession()", 60 * 1000);
}
var divSessionId;
var divSessionIntervalId;
function updateSessionDiv() {
    try {
        var temp = sessionTimeoutTracker / 1000;
        $(divSessionId).innerText = "ALOT: " + temp + "s";
    }
    catch (e) { }
}
function TrackSession() {
    if (sessionTimeoutTracker <= 60 * 1000)
        return;
    sessionTimeoutTracker -= 60 * 1000;
    updateSessionDiv();
    //window.status = sessionTimeoutTracker ;
    if (sessionTimeoutTracker <= 60 * 1000) {
        setTimeout("CloseSession()", (60 - counter - 5) * 1000);
        clearInterval(trackSessionIntervalID);
    }
}

function CloseSession() {
    counter = 30; //seconds
    msg = "Your session<br /> expires in " + counter + " secs";
    SessionDiv();
    sessionIntervalID = setInterval('remind()', 1000);
}

function ClearTimeout() {
    clearTimeout(sessionTimeoutID);
    sessionTimeoutID = null;
}

function remind() {
    counter--;

    msg = "Your session<br /> expires in " + counter + " secs";
    $("sessionTextID").innerHTML = msg;
    if (counter == 0 && null != sessionIntervalID) {
        clearInterval(sessionIntervalID);
        sessionIntervalID = null;
        window.location = "../AutoLogOut.aspx";
    }
}

var sessionDiv = document.createElement('div');
var sessionIframe = document.createElement('iframe');
var sessionTxtSpan = document.createElement('span');
var sessionCancelBtn = document.createElement("input");

function setSizeOnSessionDiv() {
    var elHeight = (document.body.scrollHeight < document.body.clientHeight) ? document.body.clientHeight : document.body.scrollHeight;
    sessionDiv.style.width = document.body.clientWidth;
    sessionDiv.style.height = elHeight//clientHeight;

    sessionTxtSpan.style.top = parseInt(elHeight / 2) - 100;
    sessionTxtSpan.style.left = parseInt(document.body.clientWidth / 2) - 100;
    sessionTxtSpan.id = 'sessionTextID';

    sessionCancelBtn.style.top = parseInt(elHeight / 2);
    sessionCancelBtn.style.left = parseInt(document.body.clientWidth / 2) - 40;
    sessionCancelBtn.style.right = parseInt(document.body.clientWidth / 2) - 100;

    sessionIframe.style.width = document.body.clientWidth;
    sessionIframe.style.height = elHeight; //clientHeight;					
}

function SessionDiv(sessionDivDisplay) {
    if (null == sessionDivDisplay)
        sessionDivDisplay = 'block';
    sessionDiv.style.left = 0; //window.screenLeft;
    sessionDiv.style.top = 0; //window.screenTop;
    sessionDiv.style.display = sessionDivDisplay;
    sessionDiv.style.zIndex = 99999;
    sessionDiv.id = 'sessionDiv';
    sessionDiv.style.position = 'absolute';
    sessionDiv.style.filter = 'alpha(opacity=40)';
    sessionTxtSpan.innerHTML = msg;
    //sessionTxtSpan.style.position = 'relative';                                                

    sessionTxtSpan.style.position = 'absolute';
    sessionDiv.appendChild(sessionTxtSpan);
    sessionDiv.className = 'DivOver';
    sessionDiv.onmouseover = 'this.style.cursor = "wait"';
    //document.body.appendChild(sessionDiv);        

    sessionIframe.style.left = 0; //window.screenLeft;
    sessionIframe.style.top = 0; //window.screenTop;
    sessionIframe.style.display = sessionDivDisplay;
    sessionIframe.id = 'sessionIframe';
    sessionIframe.style.zIndex = 99999;
    sessionIframe.style.position = 'absolute';
    sessionIframe.style.filter = 'alpha(opacity=0)';
    sessionIframe.style.color = 'navy';
    sessionIframe.style.backgroundColor = 'white';
    sessionIframe.frameBorder = 0;
    sessionIframe.scrolling = 'no';
    sessionIframe.src = 'about:blank';
    sessionIframe.style.cursor = 'wait';
    sessionIframe.onmouseover = 'this.style.cursor = "wait"';
    document.body.appendChild(sessionIframe);

    document.body.appendChild(sessionDiv);

    sessionCancelBtn.type = "button";
    sessionCancelBtn.id = "btnCancel";
    sessionCancelBtn.value = "Cancel";
    sessionCancelBtn.style.fontWeight = "bold";
    sessionCancelBtn.style.backgroundColor = "white";
    sessionCancelBtn.style.position = "absolute";
    sessionCancelBtn.onclick = function() { history.go(0) };
    sessionDiv.appendChild(sessionCancelBtn);

    setSizeOnSessionDiv();
    window.onresize = setSizeOnSessionDiv;
}


function setHdnValue(value, hdnClientID) {
    $(hdnClientID).value = value;
}

function setCheckValuesValue(val, hdnClientID, sender) {
    if (sender.checked) {
        $(hdnClientID).value = $(hdnClientID).value + val + '#$423#';
    }
    else {
        $(hdnClientID).value = $(hdnClientID).value.replace(val + '#$423#', "");
    }
}

function toogleDefaultText(sender, text, evt) {
    evt = (null == evt) ? event : evt;
    if (evt.type == "focus") {
        if (sender.value == text) {
            sender.value = '';
            sender.style.color = '#000000';
        }
    }
    else if (evt.type == "blur") {
        if (sender.value == '') {
            sender.value = text;
            sender.style.color = '#888888';
        }
    }
}

function multiEditClick(sender, gridId, hdnStateId) {//debugger;
    sender.disabled = true;
    var oldMEditEnabled = !sender.checked; //($(hdnStateId).value == "true") ? true : false;        
    if (!oldMEditEnabled)
        sender.value = "Normal Edit Mode";
    else
        sender.value = "Multi Edit Mode";

    sender.disabled = false;
    $(hdnStateId).value = (!oldMEditEnabled).toString();
    setMultiEditContext(gridId, !oldMEditEnabled);
    return true;
}

function setMultiEditContext(gridId, mEditEnabled) {
    var grid = $(gridId);
    var spanList = grid.getElementsByTagName('span');
    for (var i = 0; i < spanList.length; i++) {
        if (spanList[i].id.indexOf('lblCounter') != -1)
            spanList[i].style.display = mEditEnabled ? "none" : "block";
        if (spanList[i].id.indexOf('spanCkMEdit') != -1) {
            spanList[i].style.display = mEditEnabled ? "block" : "none";
            if (!mEditEnabled) {
                var ckList = spanList[i].getElementsByTagName("input");
                ckList[0].checked = false;
            }
        }
    }
}

var dbClickTarget = null;
var dbClickCount = 0;
function isDbClick(sender) {
    window.status = dbClickCount;
    if (dbClickTarget != sender) {
        dbClickTarget = sender;
        dbClickCount = 1;
        setTimeout("dbClickCount=0;", 1000);
        return false;
    }
    if (dbClickCount == 1) {
        dbClickCount = 0;
        return true;
    }
    else {
        setTimeout("dbClickCount=0;", 1000);
        dbClickCount++;
    }
    return false;
}



function escapeHTML(str) {
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

function openCodeWindow(sender, lnkId, txtAttachedId, url, modalId) {
    var txtId = sender.id.replace(lnkId, txtAttachedId);
    var txt = $(txtId);
    var cPos = getCaretPos(txt); //(null == txt.selectionStart) ? 0 : txt.selectionStart;
    url = url + "?senderId=" + txtId + "&cPos=" + cPos;
    ModalFormShow(modalId, url);
    return false;
}

function setCode(textBoxId, cPos, encodedText) {
    var str = $(textBoxId).value.substring(0, cPos);
    var str1 = $(textBoxId).value.substring(cPos);
    str += encodedText + str1;
    $(textBoxId).value = str;
}

function ModalFormSelfClose(timeoutScript) {
    var frameList;
    if (browser.isIE)
        frameList = window.parent.document.frames;
    else
        frameList = window.parent.frames;
    var fId;
    for (var i = 0; i < frameList.length; i++) {
        fId = frameList[i].frameElement.id;
        if (fId.indexOf('_iframe') != -1)
            window.parent.ModalFormHide(fId);
    }
    if (timeoutScript)
        setTimeout("window.parent." + timeoutScript, 0);
    //window.parent.ModalFormHide(fId);
}



function getCaretPos(textarea) {
    var caretPos = 0;
    textarea.focus();
    // get selection in firefox, opera, …    
    if (typeof (textarea.selectionStart) == 'number') {
        caretPos = textarea.selectionStart
    } 
    else if (document.selection) {
        var selection_range = document.selection.createRange().duplicate();

        if (selection_range.parentElement() == textarea) { // Check that the selection is actually in our textarea
            // Create three ranges, one containing all the text before the selection,
            // one containing all the text in the selection (this already exists), and one containing all
            // the text after the selection.
            var before_range = document.body.createTextRange();
            before_range.moveToElementText(textarea); // Selects all the text
            before_range.setEndPoint("EndToStart", selection_range); // Moves the end where we need it

            var after_range = document.body.createTextRange();
            after_range.moveToElementText(textarea); // Selects all the text
            after_range.setEndPoint("StartToEnd", selection_range); // Moves the start where we need it

            var before_finished = false, selection_finished = false, after_finished = false;
            var before_text, untrimmed_before_text, selection_text, untrimmed_selection_text, after_text, untrimmed_after_text;

            // Load the text values we need to compare
            before_text = untrimmed_before_text = before_range.text;
            selection_text = untrimmed_selection_text = selection_range.text;
            after_text = untrimmed_after_text = after_range.text;

            // Check each range for trimmed newlines by shrinking the range by 1 character and seeing
            // if the text property has changed. If it has not changed then we know that IE has trimmed
            // a \r\n from the end.
            do {
                if (!before_finished) {
                    if (before_range.compareEndPoints("StartToEnd", before_range) == 0) {
                        before_finished = true;
                    } else {
                        before_range.moveEnd("character", -1)
                        if (before_range.text == before_text) {
                            untrimmed_before_text += "\r\n";
                        } else {
                            before_finished = true;
                        }
                    }
                }
                if (!selection_finished) {
                    if (selection_range.compareEndPoints("StartToEnd", selection_range) == 0) {
                        selection_finished = true;
                    } else {
                        selection_range.moveEnd("character", -1)
                        if (selection_range.text == selection_text) {
                            untrimmed_selection_text += "\r\n";
                        } else {
                            selection_finished = true;
                        }
                    }
                }
                if (!after_finished) {
                    if (after_range.compareEndPoints("StartToEnd", after_range) == 0) {
                        after_finished = true;
                    } else {
                        after_range.moveEnd("character", -1)
                        if (after_range.text == after_text) {
                            untrimmed_after_text += "\r\n";
                        } else {
                            after_finished = true;
                        }
                    }
                }

            } while ((!before_finished || !selection_finished || !after_finished));

            // Untrimmed success test to make sure our results match what is actually in the textarea
            // This can be removed once you’re confident it’s working correctly
            var untrimmed_text = untrimmed_before_text + untrimmed_selection_text + untrimmed_after_text;
            var untrimmed_successful = false;
            if (textarea.value == untrimmed_text) {
                untrimmed_successful = true;
            }
            // ** END Untrimmed success test

            caretPos = untrimmed_before_text.length;
        }
    }
    return caretPos;
}

function simulateEvent(elem, eventName) {    
    if (typeof (elem) == "string") {
        elem = $get(elem);
    }

    if (document.createEvent) {            
        var evObj = document.createEvent('MouseEvents');
        evObj.initEvent(eventName, true, false);
        elem.dispatchEvent(evObj);
    } else if (document.createEventObject) {        
        elem.fireEvent('on' + eventName);
    }
} 