﻿var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
var favCommentEditMode = false;
var isclicked = false;
var chatUpdateInterval = -1;
var externalScripts = {};
var onLoadFunctions = [];
var $get = $get || function(id) { return document.getElementById(id) };  // document.getElementById is actually faster (2.5x) than $get

/*
* Bootscript (consider using pageLoad instead)
*/
function loadScript() {
    //Setting the submenu correct
    //bootExpand();

    //Adding javascript validators
    if (typeof addValidators == 'function') {
        addValidators();
    }

    //Adding the fields which contains errors
    if (typeof addErrorFields == 'function') {
        addErrorFields();
    }

    for (var i = 0; i < onLoadFunctions.length; ++i)
        onLoadFunctions[i]();
            
    // Start the timer that checks for new chat messages
    //startChatUpdateTimer(10000);

    addEvent(window, 'resize', setHeight);
    setHeight();
}

/*
* Bootscript that gets called at the end of the body (vs. at page load with loadScript)
*/
function loadScriptEnd() {
    // Used for improving updatePanel behavior in IE (http://support.microsoft.com/?kbid=2000262)
    function disposeTree(sender, args) {
        var i, j, k, behaviors, length, allnodes, nodes, element,
                elements = args.get_panelsUpdating();
        for (i = elements.length - 1; i >= 0; --i) {
            element = elements[i];
            allnodes = element.getElementsByTagName('*'),
                length = allnodes.length;
            nodes = new Array(length)
            for (k = 0; k < length; ++k) {
                nodes[k] = allnodes[k];
            }
            for (j = 0, l = nodes.length; j < l; ++j) {
                var node = nodes[j];
                if (node.nodeType === 1) {
                    if (node.dispose && typeof (node.dispose) === "function") {
                        node.dispose();
                    } else if (node.control && typeof (node.control.dispose) === "function") {
                        node.control.dispose();
                    }

                    behaviors = node._behaviors;
                    if (behaviors) {
                        behaviors = Array.apply(null, behaviors);
                        for (k = behaviors.length - 1; k >= 0; --k) {
                            behaviors[k].dispose();
                        }
                    }
                }
            }
            element.innerHTML = "";
        }
    }
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(disposeTree);

    // html editor popups position fix
    if (window.Sys && Sys.Extended && Sys.Extended.UI.HTMLEditor) {
        Sys.Extended.UI.HTMLEditor.Popups.Popup.prototype.open = function (callback, top, left) {
            this._baseOpen(callback, top, Math.min(500, left));
        };
    }

    // Google analytics code
    window._gaq = window._gaq || [];
    _gaq.push(['_setAccount', 'UA-4727485-4']);
    _gaq.push(['_trackPageview']);
    (function () {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
}

/**
 * Set height of the main content area
 */
function setHeight() {
    var body = document.body,
        height = window.innerHeight || body.parentElement.clientHeight || body.clientHeight || 0,
        main = document.getElementById("main");
    if (main)
        main.style.minHeight = Math.max(0, height - 262) + "px";
    else {
        main = document.getElementById('wrap');
        if (main)
            main.style.minHeight = Math.max(0, height - 235) + "px";
    }
    //main.className = main.className.replace(/\bnoscript\b/,'');
}

/**
* Add trim function to string if undefined
*/
if (''.trim == undefined)
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };

/**
 * Add a CSS rule to an existing stylesheet
 */
function addCssRule(selector, attribute, value, styleSheetID) {
    if (!document.styleSheets.length)
        return;
    var i = styleSheetID || 0;
    if (document.styleSheets[i].addRule)
        document.styleSheets[i].addRule(selector, attribute+':'+value);
    else
        document.styleSheets[i].insertRule(selector+' {'+attribute+':'+value+'}', 0);
}

/**
 * Remove CSS rules in stylesheet that match by the top selector element 
 */
function removeCSSRulesByTopSelector(stylesheet, selector) {
    var i, rules = stylesheet.rules ? stylesheet.rules : stylesheet.cssRules, j = rules.length;
    if (stylesheet.addRule) {  // IE
        for (i = j-1; i >= 0; --i) {
            if (rules[i].selectorText.match('^' + selector))
                stylesheet.removeRule(i);
        }
    } else {  // other
        for (i = j - 1; i >= 0; --i) {
            if (rules[i].selectorText.match('^' + selector))
                stylesheet.deleteRule(i);
        }
    }
}

/**
 * document.write Alternative (for external scripts that use it)
 */
function documentWriteAlternative(divID, text) {
    var el = document.getElementById(divID);
    if (el && ('innerHTML' in el))
        el.innerHTML = text;
}

/*
* Initiate a timer that periodically updates the chat notifier div
*/
function startChatUpdateTimer(interval) {
    if (chatUpdateInterval != -1 || typeof (chatUpdatePanelButton) == 'undefined') return;
    chatUpdateInterval = setInterval(function() { chatUpdatePanelButton.click(); }, interval);
}

/*
* Stop the timer that periodically updates the chat notifier div
*/
function stopChatUpdateTimer(interval) {
    clearInterval(chatUpdateInterval);
    chatUpdateInterval = -1;
}

/*
* Go to url
*/
function goTo(url) {
    setTimeout(function () { window.location.href = url }, 0);
}

/*
* Go to url in new tab
*/
function goToNew(url) {
//    if (isFirefox()) {
//        open(url);
//        return;
//    }
//    var link = document.createElement('a');
//    link.href = url;
//    link.target = '_new';
//    link.style.display = 'none';
//    document.body.appendChild(link);
    //    link.click();
    window.open(url);
}

/**
* Test for firefox
*/
function isFirefox() {
    return /\bfirefox\b/i.test(navigator.userAgent);
}

/*
* search for a value in the array and returns the key
*/
function array_search(value, array) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == value)
            return i;
    }

    return -1;
}

/*
* search the array for the given value, gives true if so
*/
function in_array(value, array, identifier) {
    var i = 0, j = array.length;
    if (identifier == undefined) {
        for (i; i < j; ++i) {
            if (array[i] == value)
                return true;
        }
    } else {
        if (value[identifier] == undefined)
            return false;
        for (i; i < j; ++i) {
            if (array[i][identifier] == value[identifier])
                return true;
        }
    }
    return false;
}

/*
* Finds the X position of an element
*/
function findPosX(obj) {
    var curleft = 0;

    if (obj.offsetParent) {
        while (1) {
            curleft += obj.offsetLeft;
            if (!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        curleft += obj.x;
    }

    obj.style.position = "static";

    return curleft;
}

/*
* Finds the Y position of an element
*/
function findPosY(obj) {
    var curtop = 0;

    if (obj.offsetParent) {
        while (1) {
            curtop += obj.offsetTop;
            if (!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }

    return curtop;
}

/*
* Adds an eventlistener to the element
*/
function addEvent(obj, type, fn) {
    if (obj == undefined)
        return;
    if (obj.addEventListener) {
        obj.addEventListener(type, fn, false);
    } else if (obj.attachEvent) {
        obj["e" + type + fn] = fn;
        obj[type + fn] = function() { obj["e" + type + fn](window.event); }
        obj.attachEvent("on" + type, obj[type + fn]);
    } else {
        obj["on" + type] = fn;
    }
}

/*
* Removes an eventlistener from the element
*/
function removeEvent(obj, type, fn) {
    if (obj.removeEventListener)
        obj.removeEventListener(type, fn, false);
    else if (obj.detachEvent && obj[type + fn]) {
        obj.detachEvent("on" + type, obj[type + fn]);
        obj[type + fn] = null;
        obj["e" + type + fn] = null;
    }
}

/**
 * Format a page's content for printing and print
 */
function formatPrint() {
    var i, gets, ori,
        elements = [],
        classes = ['hideheader', 'main_left', 'main_right','hidefooter'];
    for (i in classes) {
        gets = getElementsByClassName(classes[i]);
        if (!gets.length) // I.e. the designer changed the CSS classes...
            return;
        elements.push(gets[0].style);
    }
    ori = [elements[0].display, elements[1].display, elements[2].cssFloat,
            elements[2].styleFloat, elements[3].display];
    elements[0].display = 'none';
    elements[1].display = 'none';
    elements[2].cssFloat = 'left';
    elements[2].styleFloat = 'left';
    elements[3].display = 'none';
    print();
    elements[0].display = ori[0];
    elements[1].display = ori[1];
    elements[2].cssFloat = ori[2];
    elements[2].styleFloat = ori[3];
    elements[3].display = ori[4];
    return false;
}

/**
 * Format a date object to string, given a style
 */
function formatDate(date, formatStyle) {
    switch (formatStyle) {
        case 'NL_date_time':
            return [date.getDate(), date.getMonth()+1, date.getFullYear()].join('-') + ', ' + date.getHours() + ':' + leadingZeros(date.getMinutes(),2);
            break;
        default:
            return date.toString();
    }
}

/**
 * Add leading zeros to a number if it has fewer than n digits
 */
function leadingZeros(number,n) {
    return new Array(Math.max(0, n-(number + '').length) + 1).join(0) + number;
}

/**
 * Hide/show menus
 * Does opposite when bizarro is true
 */
function toggleMinimalMode(bizzarro) {
    var i, gets,
        elements = [document.getElementById('minimalBar').style],
        classes = ['header_ingelogd', 'sitemap', 'footer', 'main_left', 'main_right', 'main_main'];
    for (i in classes) {
        gets = getElementsByClassName(classes[i]);
        if (!gets.length) // I.e. the designer changed the CSS classes...
            return;
        elements.push(gets[0].style);
    }
    if (!this.minimalMode != !bizzarro) {
        this.minimalMode = false;
        elements[0].display = 'none';
        elements[1].display = elements[2].display = elements[3].display = elements[4].display = elements[5].cssFloat =
            elements[5].styleFloat = '';
        elements[6].width = '991px'
    } else {
        this.minimalMode = true;
        elements[0].display = 'block';
        elements[1].display = elements[2].display = elements[3].display = elements[4].display = 'none';
        elements[5].cssFloat = 'left';
        elements[5].styleFloat = 'left';
        elements[6].width = '800px';
    }
}

/*
* get Elements by class name
*/
function getElementsByClassName(className, tag, elm) {
    var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
    tag = tag || "*";
    elm = elm || document;
    var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
    var returnElements = [];
    var current;
    var length = elements.length;
    for (var i = 0; i < length; i++) {
        current = elements[i];
        if (testClass.test(current.className)) {
            returnElements.push(current);
        }
    }
    return returnElements;
}

/*
* Aplphabets cannot be entered
*/
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

/*
* Get elements by name does not work completly in IE
*/
function getElementsByName_iefix(tag, name) {
    var elem = document.getElementsByTagName(tag);
    var arr = new Array();
    for (i = 0, iarr = 0; i < elem.length; i++) {
        att = elem[i].getAttribute("name");
        if (att == name) {
            arr[iarr] = elem[i];
            iarr++;
        }
    }
    return arr;
}

/*
* To open a popup window for email addressess page in new email page
*/
function PopUP() {
    window.open("EmailPopUp.aspx", "popup", "menubar=0,tollbar=0,statusbars=1,left=100,top=100,width=400,height=300,resizable=yes");
}

/*
* To open a popup window for email addressess page in new email page
*/
function PopUPWithReturnField(returnField) {
    window.open("EmailPopUp.aspx?returnField=" + returnField, "popup", "menubar=0,tollbar=0,statusbars=1,left=100,top=100,width=400,height=300,resizable=yes");
}

/*
*   OPEN POPUP WITH SPECIFIED INFORMATION
*/
function popUp(typePopUp) {
    window.open("popUpScreen.aspx?type=" + typePopUp, "popup", "menubar=0,tollbar=0,statusbars=1,left=100,top=100,width=400,height=300,resizable=yes");
}

/*
*   OPEN POPUP WITH SPECIFIED INFORMATION
*/
function popUpWithReturnField(typePopUp, returnField) {
    window.open("popUpScreen.aspx?type=" + typePopUp + "&returnField=" + returnField, "popup", "menubar=0,tollbar=0,statusbars=1,left=100,top=100,width=400,height=300,resizable=yes");
}

/*
* Show and Hide rating stars.
*/
function changeRating(obj, id, array) {
    var self = array.length;
    for (i = 0; i < array.length; i++) {
        if (i <= self) {
            array[i].src = array[i].src.replace("black", "gold");
        } else {
            array[i].src = array[i].src.replace("gold", "black");
        }
        if (array[i].id == obj.id) {
            self = i;
        }
    }
}

/*
*   SHOW HIDE ELEMENT BY ID
*/
function showHideElementById(elementID) {
    var elem = document.getElementById(elementID);
    if (!elem)
        return;

    if (elem.style.display == "none") {
        elem.style.display = "block";
    } else {
        elem.style.display = "none";
    }
}

function changeImage(elementID, firstImage, secondImage) {
    var elem = document.getElementById(elementID);
    if (!elem)
        return;
    var elemSrc = elem.src.toString();
    if (elemSrc.search(firstImage) != -1) {
        elem.src = elemSrc.replace(firstImage, secondImage);
    } else {
        elem.src = elemSrc.replace(secondImage, firstImage);
    }
}

/*
*   POPUP BOX ARE YOU SURE? YES NO. SUMBIT FORM.
*/
function wantToRemove(text, obj) {
    var reaction = confirm(text);

    if (reaction) {
        return true;
    }

    return false;
}

/*
*   SELECT ALL CHECKBOXES BY NAME
*/
function checkAllCheckboxesByName(name) {
    var elements = getElementsByName_iefix("input", name);

    for (i = 0; i < elements.length; i++) {
        if (elements[i].checked) {
            elements[i].checked = false;
        } else {
            elements[i].checked = true;
        }
    }
}

function showhidecells(name) {
    if (name == "zzper" & document.aspnetForm.ctl00_cphMain_ddlUsertype != null) {
        var namearray = getElementsByName_iefix("td", name);

        if (document.aspnetForm.ctl00_cphMain_ddlUsertype.selectedIndex == 0) {
            for (var i = 0; i < namearray.length; i++) {
                namearray[i].style.display = "table-cell";
            }
        } else {
            for (i = 0; i < namearray.length; i++) {
                namearray[i].style.display = "none";
            }
        }
    } else if (name == "exp" & document.aspnetForm.ctl00_cphMain_ddlTypeOfZZPer != null) {
        if (document.aspnetForm.ctl00_cphMain_ddlTypeOfZZPer.selectedIndex == 0) {
            document.getElementById("ctl00_cphMain_startyear").style.display = "none";
            document.getElementById("ctl00_cphMain_kvknumber").style.display = "none";
            document.getElementById("ctl00_cphMain_startyear2").style.display = "none";
            document.getElementById("ctl00_cphMain_kvknumber2").style.display = "none";
        } else {
            document.getElementById("ctl00_cphMain_startyear").style.display = "table-cell";
            document.getElementById("ctl00_cphMain_kvknumber").style.display = "table-cell";
            document.getElementById("ctl00_cphMain_startyear2").style.display = "table-cell";
            document.getElementById("ctl00_cphMain_kvknumber2").style.display = "table-cell";
        }
    }
}

/*
* Show/hide the icons options on the my favorites page
*/
function switchFavoritesIcons(element, show) {
    if (!favCommentEditMode)
        getElementsByClassName('favorites_icons_container', 'div', element)[0].style["display"] = show ? 'block' : 'none';
}

/*
* Confirm box for deleteing the favorite
*/
function deleteFavorite(fav_id) {
    if (confirm(resources.confirm_delete)) {
        goTo("?delete=" + fav_id)
    }
}

/*
* Edit the comment for a favorite
*/
function editFavoriteComment(element) {
    if (isclicked == false) {

        var parentDiv = element.parentNode;
        var commentBox = parentDiv.getElementsByTagName("div");

        commentBox = commentBox[0];

        commentBox.style["width"] = "250px";
        commentBox.style["height"] = "130px";
        commentBox.style["top"] = "-10px";
        parentDiv.style["left"] = "-135px";

        commentBox.innerHTML = "<textarea style='width:243px; height:100px;' rows='1' columns='2'>" + commentBox.innerHTML;
        commentBox.innerHTML += "</textarea><p align='right'><a href='javascript:;' onclick='hideFavoriteCommentBox(this)'>" + resources.save + "</a></p>";
        var textArea = commentBox.getElementsByTagName('textarea')[0];

        textArea.focus();

        favCommentEditMode = true;
        isclicked = true;
    }
}

/*
* Edit the comment for a favorite (profile)
*/
function editFavoriteCommentProfile(id, note) {
    var commentBox = document.getElementById(id);

    if (isclicked) {
        commentBox.style["display"] = "none"
        favCommentEditMode = false;
        isclicked = false;
        return;
    }

    commentBox.style["display"] = "block";

    var textArea = commentBox.getElementsByTagName('textarea')[0];

    if (typeof (favoriteNote) != 'undefined' && note == undefined)
        try {
            textArea.innerHTML = favoriteNote;
        }catch (e){
            textArea.innerHTML = '';
        }
    textArea.focus();

    favCommentEditMode = true;
    isclicked = true;
}

/*
* Hide the edit box for the comment of a favorite
*/
function hideFavoriteCommentBox(element) {
    var parentDiv = element.parentNode;
    var hiddenID = parentDiv.parentNode.parentNode.getElementsByTagName("input")[1].value;
    var commentBox = parentDiv.parentNode;
    var textArea = commentBox.getElementsByTagName('textarea')[0];

    commentBox.style["width"] = "150px";
    commentBox.style["height"] = "";
    commentBox.style["top"] = "0px";
    parentDiv.parentNode.parentNode.style["left"] = "-85px";

    updateComment(textArea, hiddenID);

    commentBox.innerHTML = textArea.value;
    favCommentEditMode = false;
    isclicked = false;
}

/*
* Hide the edit box for the comment of a favorite (profile)
*/
function hideFavoriteCommentBoxProfile(element, save, note) {
    var hiddenID = element.parentNode.parentNode.parentNode.getElementsByTagName("input")[0].value;
    var icon = element.parentNode.parentNode.parentNode.getElementsByTagName("img")[0];
    var commentBox = element.parentNode.parentNode;
    var textArea = commentBox.getElementsByTagName('textarea')[0];

    commentBox.style["display"] = "none";

    favCommentEditMode = false;
    isclicked = false;

    if (save) {
        if (note == undefined) {
            updateComment(textArea, hiddenID);
            favoriteNote = textArea.value;
        } else
            addNote(textArea.value, hiddenID);
    }
}

/*
 * Hide or show task box
 */
function toggleTaskBox(insertValue,save,id) {
    var taskBox = document.getElementById('taskBox');
    var taskTextbox = taskBox.getElementsByTagName('textarea')[0];
    var deadline = taskBox.getElementsByTagName('input')[0];
    if (taskBox.style.display != 'block'){
        taskBox.style.display = 'block';
        taskTextbox.value = insertValue || '';
        deadline.value = '';
    }else{
        taskBox.style.display = 'none';
        if (save)
            addTask(taskTextbox.value, id, deadline.value);
        taskTextbox.value = '';
    }
    return false;
}



/*
 * Hide or show task edit box
 */
function toggleTaskEdit(insertValue,save,id, dag) {
    var taskBox = document.getElementById('TaskEdit');
    var taskTextbox = taskBox.getElementsByTagName('textarea')[0];
    var deadline = taskBox.getElementsByTagName('input')[0];
    var taskID = document.getElementById('hdnid');
    if (taskBox.style.display != 'block'){
        taskBox.style.display = 'block';
        taskTextbox.value = insertValue || '';
        deadline.value = dag;
        taskID.value = id;
       
	
    }else{
        taskBox.style.display = 'none';
        if (save)
            editTask(taskTextbox.value, taskID.value, deadline.value);
        taskTextbox.value = '';
    }
    return false;
}


/*
* Show the feedback popup 
*/
function showFeedbackPopup(page, querystring, path) {
    path = path || '';
    window.open(path + "hdcall.aspx?page=" + page + "&pagecodes=" + querystring, "MyWindow", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=500,height=570");
}

/*
* Show the private chatroom popup
*/
function showPrivateChatPopup(user_id_session, user_id_normal) {
    window.open("privateChat.aspx?id1=" + user_id_session + "&id2=" + user_id_normal, "selftextwillmove", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=370,height=220");

}


/*
* for gridview selected box
*/
function SelectAllCheckboxes(spanChk) {

    // Added as ASPX uses SPAN for checkbox

    var oItem = spanChk.children;

    var theBox = (spanChk.type == "checkbox") ? spanChk : spanChk.children.item[0];

    xState = theBox.checked;

    elm = theBox.form.elements;

    for (var i = 0; i < elm.length; i++) {

        if (elm[i].type == "checkbox" && elm[i].id != theBox.id) {

            //elm[i].click();

            if (elm[i].checked != xState)

                elm[i].click();

            //elm[i].checked=xState;

        }
    }
}

/*
* Limit the display size of an image
*/
function limitImageSize(img, maxwidth, maxheight) {
    var imgwidth = img.width,
        imgheight = img.height,
        ratio = imgwidth / imgheight;
    if (imgwidth <= maxwidth) {
        if (imgheight <= maxheight)
            return;
        img.height = maxheight;
        img.width = maxheight * ratio;
    } else if (imgheight <= maxheight) {
        img.width = maxwidth;
        img.height = maxwidth / ratio;
    } else {
        if (imgwidth > imgheight) {
            img.width = maxwidth;
            img.height = maxwidth / ratio;
        } else {
            img.height = maxheight;
            img.width = maxheight * ratio;
        }
    }
}

//below functions are meant for document sharing and are mostly used in file.aspx page***************************
function openinnewwindow(param1) {
    //window.open('document.aspx?id=new');
    window.open('document.aspx?mode=' + param1 + '&id=', "Link", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=800,height=800,left=220,top=230");
}

function openinnewwindowforedit(mode, fileid) {
    //window.open('document.aspx?id=new');
    window.open('document.aspx?mode=' + mode + '&id=' + fileid, "Link", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=800,height=800,left=220,top=230");
}

function chkboxChecked(chkId) {
    var checker = document.getElementById(chkId);
    checker.checked = true;
}
function addFileUploadBox() {
    var uploadArea = document.getElementById("upload-area");

    if (!uploadArea)
        return;

    var newLine = document.createElement("br");
    uploadArea.appendChild(newLine);

    var newUploadBox = document.createElement("input");

    // Set up the new input for file uploads
    newUploadBox.type = "file";
    newUploadBox.className = 'styled_field';

    // The new box needs a name and an ID
    //if (!addFileUploadBox.lastAssignedId)
    //    addFileUploadBox.lastAssignedId = 100;

    //newUploadBox.setAttribute("id", "dynamic" + addFileUploadBox.lastAssignedId);
    //newUploadBox.setAttribute("name", "dynamic:" + addFileUploadBox.lastAssignedId);
    uploadArea.appendChild(newUploadBox);
    //addFileUploadBox.lastAssignedId++;

    //var del = document.getElementById(addFileUploadBox.lastAssignedId - 1);
}

function ChangeRowColor(row, chkId, bckcolor) {

    var checker = document.getElementById(chkId);
    if (checker.checked) {

        document.getElementById(row).style.backgroundColor = "#ffffda";
    }
    else {
        if (bckcolor % 2 == 0) {
            document.getElementById(row).style.backgroundColor = "F7F6F3";
        }
        else {
            document.getElementById(row).style.backgroundColor = "FFFFFF";
        }
    }
}

/* Delete cookies */
function deleteCookies() {
    var i, cookies = document.cookie.split('; '),
        cookieDate = new Date(),
        expires = '; expires=' + cookieDate.toGMTString()
    cookieDate.setTime(cookieDate.getTime() - 1);
    for (i = 0; i < cookies.length; ++i)
        document.cookie = cookies[i] + expires;
}

/* Hide beams (during page rendering) if cookie is set */
function hidePlusbeams() {
    var i, id, matches = document.cookie.match(/pb_[^=]+=1/g);
    this.plusbeamsCollapsed = {};
    if (!matches)
        return;
    for (i=0; i<matches.length; ++i){
        id = matches[i].match(/pb_([^=]+)=1/)[1];
        plusbeamsCollapsed[id] = true;
        addCssRule('#' + id + ' > .profile_section', 'display', 'none');
        addCssRule('#' + id + ' .beam_expand_button', 'background-image', 'url(../images/icons/bullet_toggle_plus.png)');
    }
}

/* Expand/collapse 'plusbeams' */
function plusbeamToggle(self) {
    var content, collapsed,
        cookieDate = 0,
        cookieTime = 0,
        paragraph = self.parentNode,
        section = paragraph.parentNode;
    content = paragraph.nextSibling;
    while (content.nodeType != 1)
        content = content.nextSibling;
    if (!section.id)
        return;
    if (this.plusbeamsCollapsed == undefined)
        this.plusbeamsCollapsed = {};
    collapsed = self.dir == 'rtl' || plusbeamsCollapsed[section.id];
    if (collapsed) {  // beam is collapsed, expand it
        plusbeamsCollapsed[section.id] = false;
        self.dir = 'ltr';
        self.className = self.className.replace(/ .*/,'');
        //self.style.backgroundImage = 'url(~/view/images/icons/bullet_toggle_minus.png)';
        content.style.display = 'block';
        this.alt = '-';
        cookieTime = -1;
        removeCSSRulesByTopSelector(document.styleSheets[0], '#' + section.id);
    } else {  // beam is expanded, collapse it
        self.dir = 'rtl';
        self.className += " toggle_plus";
        //self.style.backgroundImage = 'url(~/view/images/icons/bullet_toggle_plus.png)';
        content.style.display = 'none';
        this.alt = '+';
        cookieDate = 10;
        cookieValue = 1;
    }
    setCookie('pb_' + section.id, 1, cookieTime, cookieDate);
    return collapsed;
}

/* Set a cookie */
function setCookie(key, value, timeOffset, dateOffset) {
    var cookieDate = new Date();
    if (dateOffset)
        cookieDate.setDate(cookieDate.getDate() + dateOffset);
    if (timeOffset)
        cookieDate.setTime(cookieDate.getTime() +  timeOffset);
    document.cookie = key + '=' + value + ' ; expires=' + cookieDate.toGMTString();
}

/* Set the page cursor to auto or wait. (The cursor rendering will only change when the cursor is moved, or this is called from a handled mouse event!) */
function cursorWait(bool) {
    if (bool === false) {
        if (document.body.className)
            document.body.className = document.body.className.replace(/\bwait\b/, '');
    } else if (!/\bwait\b/.test(document.body.className))
        document.body.className += ' wait';
}

/* Set a textbox text, clear it on focus, reappear on blur */
function textSetFocusClear(textbox, text) {
    var element = (typeof textbox == 'object') ? textbox : document.getElementById(textbox);
    textSetFocusStyle(element, text);
    addEvent(element, 'focus', textFocusClearFactory(text));
    addEvent(element, 'blur', textBlurResetFactory(text));
}
function textSetFocusPassword(fauxPassword, password, text) {
    var element1 = (typeof fauxPassword == 'object') ? fauxPassword : document.getElementById(fauxPassword);
    var element2 = (typeof password == 'object') ? password : document.getElementById(password);
    addEvent(element2, 'focus', hideFactory(element1, element2))
    addEvent(element2, 'blur', displayFactory(element1, 'inline', element2)); ;
    addEvent(element1, 'click', hideFocusFactory(element1, element2));
}
function hideFactory(element) {
    return function() {
        element.style.display = 'none';
    }
}
function displayFactory(element1,display,element2) {
    return function() {
        if (!element2 || !element2.value)
            element1.style.display = display;
    }
}
function hideFocusFactory(element,element2) {
    return function() {
        element.style.display = 'none';
        element2.focus();
    }
}
function swapDisplayFocusFactory(element1, element2, defaultDisplay) {
    return function() {
        var temp = element1.style.display || defaultDisplay;
        element1.style.display = element2.style.display || defaultDisplay;
        element2.style.display = temp;
        if (temp != 'none')
            element2.focus();
    }
}
function textSetFocusStyle(element, text) {
    if (element.value == '' || element.value == text) {
        element.style.color = 'gray';
        element.style.fontStyle = 'italic';
        element.value = text;
    }
}
function textFocusClearFactory(text) {
    return function() {
        if (this.value == text) {
            this.value = '';
            this.style.color = '';
            this.style.fontStyle = '';
        }
    }
}
function textNormalStyle(element,text) {
    if (element.value != text) {
        element.style.color = '';
        element.style.fontStyle = '';
    }
}
function textBlurResetFactory(text) {
    return function() {
        if (this.value == '') {
            this.style.color = 'gray';
            this.style.fontStyle = 'italic';
            this.value = text;
        }
    }
}

/**
 * Truncate a value string to a character limit
 */
function valueTruncate(element, limit) {
    if (element.value.length > limit)
        element.value = element.value.slice(0, limit);
}

/**
* Show siblings with a delayed cascading effect
*/
function cascadeShowSiblings(element, display, className) {
    if (!(element = element.nextSibling) || (className && element.nodeType == 1 && element.className != className))
        return;
    display = display || 'block';
    if (element.style)
        element.style.display = display;
    setTimeout(function() { cascadeShowSiblings(element, display, className); }, 100);
}

/**
* Execute (zero parameter) functions with delays (in ms)
*/
function cascadeExecute(functions, delays) {
    var i, intermediate = 0;
    delays.splice(0, 0, 0);
    for (i = 0; i < functions.length; ++i) {
        intermediate += delays[i];
        setTimeout(functions[i], intermediate);
    }
}

/**
 * Remove an element
 */
function remove(element) {
    if (element)
        element.parentNode.removeChild(element);
}

/**
 * Make an absolutely positioned page element follow the mouse cursor (used for input file upload styling)
 */
function uploadBoxMove(event, elementID) {
    var uploadBox = document.getElementById(elementID || 'uploadBox');
    if (!uploadBox)
        return;
    uploadBox = uploadBox.style;
    uploadBox.left = ((event.layerX || event.x || event.offsetX) - 25) + 'px';
    uploadBox.top = ((event.layerY || event.y || event.offsetY) - 9) + 'px';
}

/**
 * Fake a button press
 */
function fakePress(button) {
    if (typeof (button) != 'object')
        button = document.getElementById(button);
    if (!button.style)
        return;
    button.style.paddingTop = '4px';
    button.style.paddingBottom = '2px';
    button.style.paddingLeft = '6px';
    button.style.paddingRight = '4px';
}
/**
 * Fake a button release
 */
function fakeRelease(button) {
    if (typeof (button) != 'object')
        button = document.getElementById(button);
    if (!button.style)
        return;
    button.style.paddingTop = button.style.paddingBottom = button.style.paddingLeft = button.style.paddingRight = '';
}

/**
 * Use closure to return a function that can be called without arguments (e.g. for setTimeout)
 * Usage: var zeroArguments = zeroArgumentClosure(someFunction, argument1, argument2, ...);
 */
function zeroArgumentClosure(func) {
    var args = Array.prototype.slice.call(arguments,1);
    return function() {
        return func.apply(this,args);
    }
}

// Make background click close modal popups
function addModalBackgroundClickFactory(id) {
    return function () {
        var bg = document.getElementById(id + '_backgroundElement');
        if (!bg)
            return;
        bg.onclick = popupHiderFactory(id);
        var i, elems = getElementsByClassName('DialogContainer');
        for (i = 0; i < elems.length; ++i)
            elems[i].style.display = 'block';
    }
}

// Make background click close modal popups
function addModalBackgroundClickFactoryAndRedirect(id, url) {
    return function () {
        var bg = document.getElementById(id + '_backgroundElement');
        if (!bg)
            return;
        bg.onclick = function () { goTo(url); };
        var i, elems = getElementsByClassName('DialogContainer');
        for (i = 0; i < elems.length; ++i)
            elems[i].style.display = 'block';
    }
}

// Return function that hides modal popup by BehaviorID
function popupHiderFactory(id) {
    return function() {
        closePopup(id);
    }
}

// Close the modal popup
function closePopup(popListName) {
    var popup = $find(popListName); 
    if (popup) {
        popup.hide(); 
    }
}

// Show the popup
//function showPopup(popListName) {
//    var popup = $find(popListName)
//    if (popup) {
//        popup.show();
//    }
//}

function showPopup(popListName, dynamicHeight) {
    var popup = $find(popListName)
    if (popup) {
        if (dynamicHeight) {
            var originalY = popup._yCoordinate;
            popup.reset = function () { this._yCoordinate = originalY; };
            popup.set_Y(getPageScroll().y + 50);
        } else if (popup.reset)
            popup.reset();
        popup.show();
    }
} 


function  getPageScroll(){
 
  var  scrollY;
      
      if (document.all)
      {
                        
         if (!document.documentElement.scrollTop)
            scrollY = document.body.scrollTop;
         else
            scrollY = document.documentElement.scrollTop;
      }   
      else
      {
        
         scrollY = window.pageYOffset;
      }

      return {x:undefined, y:scrollY};
}

function showHideElement(elem) {
    if (elem.style.display == 'none') {
        elem.style.display = 'block';
    } else {
        elem.style.display = 'none';
    }
}

function showChildren(elem) {
    for (i = 0; i < elem.childNodes.length; i++) {
        var child = elem.childNodes[i];
        if (child.style.display) {
            showHideElement(child);
        }
    }
}

// Return false or a parsed bool value
function boolParse(value) {
    return value.toString() in {'true':1,'True':1,'1':1};
}

// Force a character limit on (multiline) text input fields
function limitChars(element, limit, labelIDs){
    if(element.value.length > limit )
        element.value = element.value.slice(0,limit);
    if (labelIDs)
        for (var i=0; i<labelIDs.length; ++i)
            document.getElementById(labelIDs[i]).innerHTML = limit-element.value.length;
}

// Create an array with a value range
function range(start, end, step) {
    start = Math.round(start);
    end = Math.round(end);
    step = Math.round(step);
    if (start < end && step > 0)
        return [];
    var i, result = [];
    for (i = start; i < end; i += step)
        result.push(i);
}

// WEB METHOD CHECK ADDRESS
function webMethodCheckAddress(streetID, houseNumberID, zipcodeID, cityID) {
    var zip = document.getElementById(zipcodeID).value, num = document.getElementById(houseNumberID).value;
    if (!num || !zip) {
        with (document.getElementById(streetID)) { readOnly = false; value = ''; }
        with (document.getElementById(cityID)) { readOnly = disabled = false; value = ''; }
        $.updnWatermark.attachAll();
        return;
    }
    PageMethods.webMethodCheckAddress(zip, num, function (ob) {
        if (ob.succes) {
            document.getElementById(streetID).value = ob.street;
            var ddl = document.getElementById(cityID);
            if (ddl.tagName === "SELECT") {
                for (i = 0; i < ddl.options.length; i++) {
                    if (ddl.options[i].text == ob.city) {
                        ddl.selectedIndex = i;
                    }
                }
                document.getElementById(cityID).disabled = true;
            } else {
                ddl.value = ob.city;
            }
            document.getElementById(streetID).readOnly = true;
            document.getElementById(cityID).readOnly = true;
        } else {
            if (ob.error in { 2: 1, 1: 1 }) {
                with (document.getElementById(streetID)) { readOnly = false; value = ''; }
                with (document.getElementById(cityID)) { readOnly = disabled = false; value = ''; }
            }
        }
        $.updnWatermark.attachAll();
        $().blur();
    });
}

// Firefox-compatible innerText setting
function setInnerText(element,text){
    if (element.textContent === undefined)
        element.innerText = text;
    else
        element.textContent = text;
}

// HTML encode
function encodeHTML(text) {
    var b = document.createElement('b');
    setInnerText(b, text);
    return b.innerHTML;
}

// Capitalize first letter
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

// Format name
function formatName(first, middle, last) {
    middle = (middle||'').trim();
    first = (first||'').trim();
    last = (last||'').trim();
    var name = first;
    if (middle) {
        if (!name)
            name = capitalize(middle.toLowerCase());
        else
            name += ' ' + middle.toLowerCase();
    }
    if (!name)
        name = last;
    else
        name += ' ' + last;
    return name.trim();
}

// WebMethod to select a branch
function webMethodBranchSelect(branchID, professionID) {
    var branchSelect = document.getElementById(branchID);
    var branchOption = branchSelect.options[branchSelect.selectedIndex];

    PageMethods.webMethodBranchSelect(branchOption.value, function (ob) {
        if (ob.success) {
            var professionSelect = document.getElementById(professionID);

            if (professionSelect.hasChildNodes()) {
                while (professionSelect.childNodes.length >= 1) {
                    professionSelect.removeChild(professionSelect.firstChild);
                }
            }

            for (i = 0; i < ob.name.length; i++) {
                $("#" + professionID).append('<option value="' + ob.value[i] + '">' + ob.name[i] + '</option>');
            }
        }
    });
}

// Load a script file asynchronously
function scriptAsync(source) {
    var po = document.createElement('script'), s = document.getElementsByTagName('script')[0];
    po.type = 'text/javascript'; po.async = true; po.src = source;
    s.parentNode.insertBefore(po, s);
}

// Preload an image
function preload(img) {
    var x = new Image();
    x.src = img;
}
