function fixIEselectBug() { document.body.style.height = document.documentElement.scrollHeight + 'px'; }
addLoadEvent(fixIEselectBug);

function isCurrency(control) 
{
	var isPrice = /^\d+\.{0,1}\d{0,2}$/;
	if (control.value.trim() != '' && !isPrice.test( control.value ))
	{ 
		alert('The value you have entered is not a valid currency. \nAllowed format:  0.00 ');
		control.focus();
		control.select()
	}	
}

function isNumberKeys2(evt, allowDotAndComma) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (allowDotAndComma) {
        if (charCode == 44 || charCode == 46 || charCode == 45) { return true; }
    }
    if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; }

    return true;
}

function isNumberKey(evt) {
    return isNumberKeys2(evt, false);
}

function isProperName(control,evt, allowSpace) 
{
	var charCode;
	if (evt.which>0) 
		charCode = evt.which;
	else if (evt.charCode > 0) 
		charCode = evt.charCode;
	else
		charCode = evt.keyCode;
	
	if (allowSpace && charCode==32) return true;
	if ((charCode > 31 && charCode < 65)|| (charCode > 122 && charCode < 128) || (charCode > 90 && charCode < 96)) { return false; }

	if(control.value.trim().length == 1) 
	{
		control.value = control.value.toUpperCase();
		return true;
	}			

	return true;
}

function checkPhoneFormat(txtPhone) {
    if (txtPhone.value == "") { return; }
    var phoneNo = txtPhone.value;
    if (phoneNo.indexOf("-") != 3) {
        alert("Please use the following phone format: 123-1234");
        setTimeout(function() { if (txtPhone) { txtPhone.focus(); txtPhone.select(); } }, 100);
    }
    else {
        var s = phoneNo.substring(phoneNo.indexOf("-") + 1);
        if (s.length != 4) {
            alert("Please use the following phone format: 123-1234");
            setTimeout(function() { if (txtPhone) { txtPhone.focus(); txtPhone.select(); } }, 100);
        }
    }
}

function moveRight(id, hiddenId) {
    var rowDiv = window.document.getElementById(id);
    var hiddenControl = window.document.getElementById(hiddenId);
    if (hiddenControl.value == '') hiddenControl.value = 0;
    if (rowDiv != null) {
        try {
            hiddenControl.value = parseInt(hiddenControl.value) + 20;
            rowDiv.style.paddingLeft = hiddenControl.value + "px";
        }
        catch (e) {
            hiddenControl.value = 0;
        }
    }
    return false;
}

function moveLeft(id, hiddenId) {
    var rowDiv = window.document.getElementById(id);
    var hiddenControl = window.document.getElementById(hiddenId);
    if (hiddenControl.value == '') hiddenControl.value = 0;
    if (rowDiv != null) {
        try {
            hiddenControl.value = parseInt(hiddenControl.value) - 20;
            rowDiv.style.paddingLeft = hiddenControl.value + "px";
        }
        catch (e) {
            //document.write(e.message + "<br/>")
            hiddenControl.value = 0;
        }
    }
    return false;
}

function Selection(id, roleId, textboxId, fieldName) {
    var ddlControl = window.document.getElementById(id)
    var roleControl = window.document.getElementById(roleId)
    var fieldNameControl = window.document.getElementById(fieldName)

    if (fieldNameControl.value == 'Role' || fieldNameControl.value == 'Gender') {
        window.document.getElementById(textboxId).style.width = "0px";
        window.document.getElementById(roleId).style.width = "155px";
    }
    else {
        window.document.getElementById(textboxId).style.width = "155px";
        window.document.getElementById(roleId).style.width = "0px";
    }

    return false;
}

function navigateTo(url) {
    window.location.href = url;
}

function navigateToNewWindow(url) {
    window.open(url);
}

function ImgExpandCollapse(imgID, obj1ID, obj2ID) {
    var img = document.getElementById(imgID);

    var obj1 = document.getElementById(obj1ID);

    var obj2 = document.getElementById(obj2ID);

    if (obj1.style.display == "none") {
        obj1.style.display = "";
        obj2.style.display = "none";
        img.src = "Resources.aspx?Res=expand.gif";
    }
    else {
        obj1.style.display = "none";
        obj2.style.display = "";
        img.src = "Resources.aspx?Res=collapse.gif";
    }
}

function ImgExpandCollapseO(imgID, obj1ID) {
    var img = document.getElementById(imgID);

    var obj1 = document.getElementById(obj1ID);

    if (obj1.style.display == "none") {
        obj1.style.display = "block";
        img.src = "Resources.aspx?Res=collapse.gif";
    }
    else {
        obj1.style.display = "none";
        img.src = "Resources.aspx?Res=expand.gif";
    }
}

function ShowHideDivBtn(obj1ID, obj2ID) {
    var obj1 = document.getElementById(obj1ID);

    var obj2 = document.getElementById(obj2ID);

    if (obj1.style.display == "none") {
        obj1.style.display = "";
        obj2.style.display = "none";
    }
    else {
        obj1.style.display = "none";
        obj2.style.display = "";
    }
}

function ExpandColapseFieldSets(parentId, imageId) {
    var parentObj = document.getElementById(parentId);

    var obj = document.getElementById(imageId);

    divs = parentObj.getElementsByTagName("div");

    for (i = 0; i < divs.length; i++) {
        div = divs[i];
        if (div.className == "fieldset_hidden") {
            if (div.style.display == "") {
                div.style.display = "none";
                obj.src = "Resources.aspx?Res=expand.gif";
                obj.alt = "Expand";
            }
            else {
                div.style.display = "";
                obj.src = "Resources.aspx?Res=collapse.gif";
                obj.alt = "Collapse";
            }
        }
    }
}

function ShowHideGrid(imageID, imageExpID) {
    var img = document.getElementById(imageID);

    var imgExp = document.getElementById(imageExpID);

    var obj = document.getElementById("Grid_container");

    if (obj.style.display == "block") {
        document.getElementById("Grid_container").style.display = "none";
        document.getElementById("fieldsets").style.display = "block";
        img.src = "images/grid.gif"
        if (imgExp != null)
            imgExp.style.display = "block";
    }
    else {
        document.getElementById("Grid_container").style.display = "block";
        document.getElementById("fieldsets").style.display = "none";
        img.src = "images/gridhide.gif"
        if (imgExp != null)
            imgExp.style.display = "none";
    }
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}

function commonCheck(validationElement) {
    var emptyString = /^\s*$/;
    return !(emptyString.test(validationElement.value));
}

function validateDDL(validationElement) {
    return !(validationElement.selectedIndex == 0);
}

function commonCheckID(validationElement) {
    var emptyString = /^\s*$/;
    if (emptyString.test(validationElement.value))
        return true;
    else {
        var tfld = trim(validationElement.value);
        var telnr2 = /^\d+$/;
        ///^([0-9])$/;
        return (telnr2.test(tfld))
    }
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function NavBarA_onItemSelect(sender, eventArgs) {
    var selectedItem = eventArgs.get_item();
    var parentItem = selectedItem.get_parentItem();

    if (parentItem)
        createCookie('AffiliationSelectedBar', parentItem.get_index());
}

function NavBarCourseManagement_onItemSelect(sender, eventArgs) {
    var selectedItem = eventArgs.get_item();
    var parentItem = selectedItem.get_parentItem();

    if (parentItem)
        createCookie('CourseManagement_SelectedBar', parentItem.get_index());
}

function NavBarProjectManagement_onItemSelect(sender, eventArgs) {
    var selectedItem = eventArgs.get_item();
    var parentItem = selectedItem.get_parentItem();

    if (parentItem)
        createCookie('ProjectManagementSelectedBar', parentItem.get_index());
}

function queryName() {
    if (document.getElementById("ctl00_ContentPlaceHolder_AdvancedSearchResultControl_lblQueryName").value == "") {
        document.getElementById("msgAdvResults").innerHTML = "<font color='red'>Please enter query name</font>"
        return false;
    }
    else {
        if (document.getElementById("msgAdvResults") != null)
            document.getElementById("msgAdvResults").innerHTML = "";

        return true;
    }
}

function addCategory(objId) {
    var newCategory = document.getElementById(objId);
    if (newCategory != null)
        newCategory.style.visibility = "visible";
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function showModal(src, top, height, width) {
	//get the vertical scroll and add it to the top so the popup always appears at top pixels from the top of the scrolled screen
	var scrolls = getScrollXY();
	if (typeof (scrolls) != 'undefined' && scrolls[1] > 0) top = (parseInt(top) + scrolls[1]).toString();
	 
    if (typeof window.parent.showModalWindow == 'function')
        window.parent.showModalWindow(src, top, height, width);
    else
        showModalWindow(src, top, height, width);
}

function showModalWindow(src, top, height, width) {
    var PopUPTop = (top) ? top : '50';
    PopUPTop = PopUPTop.replace('px', '');

    var PopUPWidth = (width) ? width.replace('px', '') : '825';
    var PopUPHeight = (height) ? height.replace('px', '') : height;
    
    var PopUPLeft = (document.body.offsetWidth - PopUPWidth) / 2;

    var iframeName;
    var PopUPWindow = document.getElementById('PopUPWindow');
    if (PopUPWindow) {
        PopUPWindow.style.display = 'none';
        PopUPWindowID = 'PopUPWindow_1';
        iframeName = 'iframeNew';
    }
    else {
        PopUPWindowID = 'PopUPWindow';
        iframeName = 'iframeOriginal';
    }

    var IEv = (navigator.appName == 'Microsoft Internet Explorer') ?
                            parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]) : -1;

    var is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);

    var transparentbackHeight = (IEv == 8 || IEv == 7 || IEv == 6) ? document.documentElement.scrollHeight + 'px' : is_khtml ? document.body.offsetHeight : window.innerHeight + window.scrollMaxY + 'px';

    var newNode = document.createElement('div');
    newNode.id = PopUPWindowID;
    newNode.innerHTML =
    "<div style='background-color:#ffffff;position:absolute;left:" + PopUPLeft + "px;width:" + PopUPWidth +
    "px;height:0;display:block;z-index:917200;top:" + PopUPTop + "px;'" +
    "><iframe name='" + iframeName + "' id='iframeContent' hspace='0' vspace='0' marginwidth='0' marginheight='0' onload='ShowModalWindowAfterAWhile(" + PopUPHeight + ");' frameborder='0' width='" +
    PopUPWidth + "px' scrolling='no' height='0'" +
    "src='" + src + "&PopUPHeight=" + PopUPHeight + "&PopUPWidth=" + PopUPWidth + "'></iframe></div>";

    var transparentback = document.createElement('div');
    transparentback.className = 'transparentback';
    transparentback.style.height = transparentbackHeight;
    newNode.appendChild(transparentback);

    var waitImage = document.createElement('div');
    waitImage.innerHTML = "<img src='Resources.aspx?Res=ajax-loader.gif' alt=''/>";
    waitImage.style.display = 'block';
    waitImage.style.position = 'absolute';
    waitImage.style.left = '40%';
    waitImage.style.top = '40%';
    waitImage.style.zIndex = '917101';
    newNode.appendChild(waitImage);

    document.body.appendChild(newNode);
}

function ShowModalWindowAfterAWhile(PopUPHeight) {
    var PopUPWindow = document.getElementById('PopUPWindow_1');
    if (!PopUPWindow)
        PopUPWindow = document.getElementById('PopUPWindow');

    if (PopUPWindow) {
    	setTimeout(
                function() {
                	//Find which pupup we are working on
                	var PopUPWindow = document.getElementById('PopUPWindow_1');
                	
                	if (typeof (PopUPWindow) == 'undefined' || PopUPWindow == null)
                		PopUPWindow = document.getElementById('PopUPWindow');

                	if (typeof (PopUPWindow) == 'undefined' || PopUPWindow == null)
                		return;

                	if (PopUPWindow.childNodes[2])
                		PopUPWindow.childNodes[2].style.display = 'none';  // hide the loader indicator image
                	if (PopUPWindow.childNodes[0]) {
                		PopUPWindow.childNodes[0].style.display = 'block';  // make the popup visible

                		PopUPWindow.childNodes[0].className = 'PopupBorder';

                		//var iframe = document.getElementById('iframeContent');
                		var iframe = PopUPWindow.childNodes[0].childNodes[0];
                		var the_height = 0;
                		if (typeof (PopUPHeight) != 'undefined' && PopUPHeight != '0')
                			the_height = PopUPHeight;
                		else
                			the_height = iframe.contentWindow.document.body.scrollHeight;

                		if (the_height == 0)
                			return;

                		//minimal height of 550
                		if (the_height > 600)
                			the_height = 600

                		//change height
                		iframe.height = the_height + 'px';
                		var ContainerDIV = iframe.contentWindow.document.getElementById('ContainerDIV');
                		if (ContainerDIV)
                			ContainerDIV.style.height = (the_height - 38) + 'px';
                		iframe.parentNode.style.height = the_height + 'px';
                	}
                }
                , 300);
    }
}

function closeModal(reload) {
    var PopUPWindow = document.getElementById('PopUPWindow_1');
    if (PopUPWindow) // if the second popup exists
    {
        //make the first one visible again
        if (reload) {
            var f = document.getElementById('iframeContent');
            if (f)
                f.contentWindow.location.reload(true);
        }

        var originalPopUp = document.getElementById('PopUPWindow')
        if (originalPopUp)
            originalPopUp.style.display = 'block';
    }
    else
        PopUPWindow = document.getElementById('PopUPWindow');

    if(PopUPWindow) PopUPWindow.style.display = 'none';

    //delete the popup object from the DOM after 1 second has passed in order to allow the 
    //Microsoft's AJAX sys object to initialize 
    setTimeout(
                function() {
                    if (PopUPWindow)
                        document.body.removeChild(PopUPWindow);
                }
                , 1500);
}

function showAddDataControl(src, width, height, scrolliframe, iFrameContainerId, expandImageId, expandPlaceHolderId, isCollapsable) {
    var scrollframe;
    if (scrolliframe == "Yes" || scrolliframe == "yes") { scrollframe = "auto"; }
    else { scrollframe = "no"; }

    var collapsable = (isCollapsable != null && isCollapsable.toLowerCase() == 'true'); //this mode is for expand collapse behaviour (when show/hide image is clicked)

    var iFrameContainer = document.getElementById(iFrameContainerId);
    if (!collapsable || iFrameContainer.innerHTML == "") {
        iFrameContainer.innerHTML = "<iframe name='iframeOriginal' id='iframeContent' frameborder='0' width=" + width + " src=" + src + " height=" + height + " scrolling=" + scrollframe + "></iframe>";
        ImgExpandOA(expandImageId, expandPlaceHolderId);
    }
    else { ImgExpandCollapseOA(expandImageId, expandPlaceHolderId); } //when show/hide image is clicked do not reload the control if already loaded to save an unnecessary postback
}

function isMaxLength(obj) {
    var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : "";
    isMaxLength(obj, mlength);
}

function isMaxLength(obj, maxLength) {
    isMaxLength(obj, maxLength, false)
}

function isMaxLength(obj, maxLength, hasAlert)
{
    if (obj.getAttribute && obj.value.length > maxLength) {
        obj.value = obj.value.substring(0, maxLength);
        if(hasAlert)
            alert("Too many characters have been entered.");
    }
}


function showPleaseWait() {
    document.getElementById("waitImage").style.visibility = 'visible';
}

function validateQuickSearch() {
    var emptyString = /^\s*$/;
    var errs1 = 0;
    var errs2 = 0;
    if (!commonCheck(document.getElementById("_ctl0_header1_txtIndividual"))) errs1 += 1;
    if (!commonCheck(document.getElementById("_ctl0_header1_txtOrganisation"))) errs1 += 1;
    if (!commonCheckID(document.getElementById("_ctl0_header1_txtIndividualID"))) errs2 += 1;

    if (errs2 == 1) {
        alert("Not a correct id. Please try again.");
        return false;
    }
    else if (errs1 == 2) {
        if (emptyString.test(document.getElementById("_ctl0_header1_txtIndividualID").value)) {
            alert("Please provide at least one search term");
            return false;
        }
        else return true;
    }
    else return true;
}

function onDelete(item) {
    if (confirm("Delete record?"))
        return true;
    else
        return false;
}

function onCallbackError(excString) {
    alert('An error has occured.');
}

function ImgExpandCollapseOA(imgID, obj1ID) {
    var img = document.getElementById(imgID);

    var obj1 = document.getElementById(obj1ID);

    if (obj1.style.display == "none") {
        obj1.style.display = "";
        img.src = "Resources.aspx?Res=collapse.gif";
    }
    else {
        obj1.style.display = "none";
        img.src = "Resources.aspx?Res=expand.gif";
    }
}

function ImgExpandOA(expandImageId, expandPlaceHolderId) {
    var img = document.getElementById(expandImageId);
    var placeHolder = document.getElementById(expandPlaceHolderId);
    if (placeHolder != null) placeHolder.style.display = "";
    if (img != null) img.src = "Resources.aspx?Res=collapse.gif";
}

function submitFormImport(hidName) {
    var ss = document.getElementById(hidName);
    if (ss.value == 1) {
        theForm.submit();
        return false;
    }
}

function submitForm(hidName) {
    var ss = document.getElementById(hidName);
    if (ss.value == 1) {
        theForm.submit();
        return false;
    }
}

function FileUpload(obj, hiddenFieldID) {
    if (obj.value != "") {
        document.getElementById(hiddenFieldID).value = "1";
    }
}

function ShowHideExportCSV(objID) {
    var obj = document.getElementById(objID);

    if (obj != null) {
        if (obj.style.display == "none") {
            obj.style.display = "";
        }
        else {
            obj.style.display = "none";
        }
    }
}

function ExportBtnClick(objID, hiddenField) {
    var hidn = document.getElementById(hiddenField);
    if (hidn != null) {
        if (hidn.value == "" || hidn.value == ";") {
            alert("Please select some records to export.");
            return false;
        }
    }
    ShowHideExportCSV(objID);
    return true;
}

function EmailBtnClick(hiddenField) {
    var hidn = document.getElementById(hiddenField);
    if (hidn != null) {
        if (hidn.value == "" || hidn.value == ";") {
            alert("Please select Individual(s) to email.");
            return false;
        }
    }
    return true;
}

function GroupBtnClick(hiddenField) {
    var hidn = document.getElementById(hiddenField);
    if (hidn != null) {
        if (hidn.value == "" || hidn.value == ";") {
            alert("Please select Individual(s) to group.");
            return false;
        }
    }
    return true;
}

function ShowHideExport(ObjID) {
    var obj = document.getElementById(ObjID);
    if (obj != null) {
        if (obj.style.display == "none") {
            obj.style.display = "";
        }
        else {
            obj.style.display = "none";
        }
    }
}

function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue) {
    var arrElements = (strTagName == "*" && oElm.all) ? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var oAttributeValue = (typeof strAttributeValue != "undefined") ? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)", "i") : null;
    var oCurrent;
    var oAttribute;
    for (var i = 0; i < arrElements.length; i++) {
        oCurrent = arrElements[i];
        oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName, 0);
        if (typeof oAttribute == "string" && oAttribute.length > 0) {
            if (typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))) {
                arrReturnElements.push(oCurrent);
            }
        }
    }

    return arrReturnElements;
}

function ValidateSearch(DivContainer, msg) {
    var container = document.getElementById(DivContainer);
    var inputElems = container.getElementsByTagName("input");

    for (var i = 0; i < inputElems.length; i++) {
        var elemValue = inputElems[i].value;
        if (inputElems[i].type != "button" && inputElems[i].type != "submit") {
            
            if (inputElems[i].type == "checkbox") {
                if (inputElems[i].checked == true)
					return true;
                else
					elemValue = "";
			}

			if (inputElems[i].id.indexOf('_displayTXT_') >= 0)
				continue;

            if (elemValue != "" && inputElems[i].type != "hidden")
				return true;
        }
    }

    var selectElems = container.getElementsByTagName("select");

    for (var i = 0; i < selectElems.length; i++) {
        if (selectElems[i].value != "")
			return true;
    }

    if (msg != null && typeof msg != 'undefined')
		alert(msg);
    else
		alert("Please provide at least one search term");
    return false;
}

function ClearFields(fieldContainer) {
	var container = (typeof (fieldContainer) == 'undefined' || fieldContainer == null) ? document : document.getElementById(fieldContainer);
	
	if (typeof (container) == 'undefined' || container == null)
		return;
		
    var inputElems = container.getElementsByTagName("input");
    var selectElems = container.getElementsByTagName("select");
    var areaElems = container.getElementsByTagName("textarea");

    for (var i = 0; i < inputElems.length; i++) {
        if (inputElems[i].type != "button" && inputElems[i].type != "submit" && !inputElems[i].disabled) {

        	if (inputElems[i].type != "checkbox" && inputElems[i].type != "radio" && !inputElems[i].disabled) {
        		//Do not clear the input fields that hold the display text fot Text Boxes with the DisplayText Property set to ON
        		if (inputElems[i].id.indexOf('_displayTXT_') < 0)
        			inputElems[i].value = "";
        	}
			
			if (inputElems[i].type == "checkbox" && !inputElems[i].disabled) {
				inputElems[i].checked = false;
			}
			
			if (inputElems[i].id.indexOf('GridCheckedIds') == 0)
				inputElems[i].value = ';';
			if (inputElems[i].id.indexOf('AllSelected') == 0)
				inputElems[i].value = 'false'; 
        }
    }

    for (var i = 0; i < selectElems.length; i++)
		selectElems[i].value = "";
    for (var i = 0; i < areaElems.length; i++)
		areaElems[i].value = "";

    return true;
}

function isdefined(variable) {
    return (typeof (window[variable]) == "undefined") ? false : true;
}

var GridToRefresh;

function RefreshGridAfterAWhile() {
    Grid = eval('(' + GridToRefresh + ')');
    Grid.callback();
}

function closeModalAndRefreshGrid(GridName, RefreshCallBack) {
	closeModal();

	if (GridName != '' && typeof (GridName) != 'undefined') {
		var Grid = eval('(' + GridName + ')');
		Grid.callback();
	}

    var RefreshCB = (typeof RefreshCallBack != 'undefined') ? RefreshCallBack : true;

    if (typeof CallCallback == 'function' && RefreshCB == true) {
        CallCallback();
    }
}

function closeModalAAndRefreshGrid(GridName) {
    var Grid = eval('(' + GridName + ')');
    Grid.callback();
}

function RefreshGrid(GridName, RefreshCallBack) {
	if (GridName != '' && typeof (GridName) != 'undefined') {
		GridToRefresh = GridName;
		setTimeout("RefreshGridAfterAWhile()", 500);
	}    

    var RefreshCB = (typeof RefreshCallBack == 'undefined') ? RefreshCallBack : true;

    if (typeof CallCallback == 'function' && RefreshCB == true)
        CallCallback();
}

function closeModalAndRefreshAttachmentsGrid(width, height, GridName) {
    closeModal();
    if (width > 0)
        displayNewImage(width, height);

    var Grid = eval('(' + GridName + ')');
    Grid.callback();
}

function RefreshAttachmentsGrid(width, height, GridName) {
    if (width > 0)
        displayNewImage(width, height);

    GridToRefresh = GridName;
    setTimeout("RefreshGridAfterAWhile()", 500);
}

function CloseModalAndRefreshGridAndDDL(GridName, ddlText, ddlValue) {
    closeModal();
    GridToRefresh = GridName;
    setTimeout("RefreshGridAfterAWhile()", 500);
    InsertInDDL(ddlText, ddlValue);
    if (typeof CallCallback == 'function')
        CallCallback();
}

function RefreshGridAndDDL(GridName, ddlText, ddlValue) {
    GridToRefresh = GridName;
    setTimeout("RefreshGridAfterAWhile()", 500);
    InsertInDDL(ddlText, ddlValue);
    if (typeof CallCallback == 'function')
        CallCallback();
}

function InsertInDDL(ddlText, ddlValue) {
    var pointerDIV = document.getElementById("pointerDIV");
    if (pointerDIV) {
        ddl = pointerDIV.nextSibling;
        var found = false;
        var i = 0;

        for (i = 0; i < ddl.length; i++) {
            if (ddl.options[i].value == ddlValue)
				found = true;
        }

        if (found == false)
        	ddl.options[ddl.length] = new Option(ddlText, ddlValue);
    }
}

function CheckAll(mEvent, SectionID, column) {
    var IsChecked = false;
    if (mEvent.srcElement) {
        IsChecked = mEvent.srcElement.checked;
    }
    //Firefox
    else if (mEvent.target) {
        IsChecked = mEvent.target.checked;
    }

    var container = document.getElementById(SectionID);
    var inputElems = container.getElementsByTagName("input");

    for (var i = 0; i < inputElems.length; i++) {
        if (inputElems[i].type == "checkbox") {
            if (inputElems[i].id.indexOf(column) > 0) {
                inputElems[i].checked = IsChecked;
            }
        }
    }
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function RefreshGridWithDropDown(mEvent, SessionVarKey, MethodToExecute) {
    var DDL;
    if (mEvent.srcElement) { DDL = mEvent.srcElement; }
    //Firefox
    else if (mEvent.target) { DDL = mEvent.target; }

    var page = 'AJAX.aspx?method=SetSessionKey&SessionKey=' + SessionVarKey + '&SessionValue=' + DDL.options[DDL.selectedIndex].value;
    makeGETRequest(page, MethodToExecute);
}

function RefreshGridAfterDropDownSelect() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            result = http_request.responseText;
            if (result == 'OK') {
                GridToRefresh.page(0);
                GridToRefresh.callback();
            }
            else { alert('A problem has occured.'); }
        }
        else { alert('There was a problem with the request.'); }
    }
}

var GridToRefresh;
function AJAXGridRefresh(mEvent, GridName, SessionVarKey) {
    GridToRefresh = GridName;
    RefreshGridWithDropDown(mEvent, SessionVarKey, RefreshGridAfterDropDownSelect);
}

function ViewActivityAttachments(ID) {
    document.getElementById("Attachments").style.display = "block";
    document.getElementById("Activities").style.display = "none";
    grdAttachments.set_callbackParameter(ID);
    grdAttachments.callback();
}

function ViewActivities() {
    document.getElementById("Attachments").style.display = "none";
    document.getElementById("Activities").style.display = "block";
}

function ValidateGridsSelectedItems(hiddenFieldID, message) {
    var hdn = document.getElementById(hiddenFieldID);
    if (typeof (hdn) != 'undefined' && hdn != null) {
    	if (hdn.value == "" || hdn.value == ";") {
    		if (message)
    			alert(message);
    		else
    			alert("Please select at least one item from the grid");
    		return false;
    	}
    }
    return true;
}

function GetQueryStringVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return '';
    //alert('Query Variable ' + variable + ' not found');
}

function GetDataFromControl(ControlID, esc) {
	var Ctrl = document.getElementById(ControlID);
	if (typeof esc == 'undefined' || esc == true)
		return (Ctrl) ? escape(Ctrl.value) : "";
	else
		return (Ctrl) ? Ctrl.value : "";
}

function putAddress(windowA, Id, Building, Number, Address1, Address2, City, County, PostalCode, Country) {
	var main_window;
	if (windowA.name == "iframeNew") {
		if (typeof (window.parent.frames["iframeOriginal"]) != 'undefined')
			main_window = window.parent.frames["iframeOriginal"];
		else
			main_window = window.parent;
	}
	else
		main_window = window.parent;

	if (typeof main_window.SetDatabaseAddress == 'function') {
		main_window.SetDatabaseAddress(Id, Building, Number, Address1, Address2, City, County, PostalCode, Country);
	}
	else {
		if (typeof parent.SetDatabaseAddress == 'function') {
			parent.SetDatabaseAddress(Id, Building, Number, Address1, Address2, City, County, PostalCode, Country);
		}
		else {
			window.frames[0].SetDatabaseAddress(Id, Building, Number, Address1, Address2, City, County, PostalCode, Country);
		}
	}
	
	//main_window.SetDatabaseAddress(Id, Building, Number, Address1, Address2, City, County, PostalCode, Country);
	window.parent.closeModal();
}

/*
* The AddDataContol.aspx page holds a div that overlaps all elements on the page. 
* This is there so it can be made visible on a button click and prevent the user
* from executing other events while he waits for the initial event to finish.
* This method is attached to all buttons of the footer of the pop up window. This
* method can be also attached to any other control that has a server event attached to it.
*/
function ShowPleaseWaitLayer() {
	if (typeof (Page_ClientValidate) == "function") {
		var validated = Page_ClientValidate();
		if (validated) {
			var PleaseWaitBox = document.getElementById('PleaseWaitBox');
			var PleaseWaitBoxBackgroudCover = document.getElementById('PleaseWaitBoxBackgroudCover');

			if (typeof (PleaseWaitBox) != 'undefined' && PleaseWaitBox != null) {
				PleaseWaitBox.style.display = 'block';
			}

			if (typeof (PleaseWaitBoxBackgroudCover) != 'undefined' && PleaseWaitBoxBackgroudCover != null) {
				PleaseWaitBoxBackgroudCover.style.display = 'block';
			}
		}
	}
}

function SetReportParams(reportName, queryBuilderInstance, identityColumnName, gridSelectedItemsHiddenFieldID, gridAllSelectedHiddenFieldID, strExtraReportParameters) {
    //This function is called by all report methods getting some of their parameters prepopulated 
    //from the grids (ticked checkboxes) or the page.
    //After calling the ajax handler method which sets the session variables for the parameters it redirects to the report page.
    //Parameters: 
    //  - reportName - this is the report name to be initialised 
    //  - queryBuilderInstance - this is a session variable of the QB instance 
    //  - identityColumnName - "Id" by default for most of the grid, but it could be something else (i.e. "ContactID", etc)
    //  - gridSelectedItemsHiddenFieldID - set that from the grid FSISelectedItemsHiddenFieldID
    //  - gridAllSelectedHiddenFieldID - set that from the grid FSIAllSelectedHiddenFieldID
    //  - strExtraReportParameters - if the report needs more parameters to be put in the session this is used to provide them (for example "&MyParam=15" 
    //    in a report named "MyReport" would automatically set in the session the following variable: Session["MyReport_MyParam"]=15)

    var selIds = document.getElementById(gridSelectedItemsHiddenFieldID).value;
    var allSelected = document.getElementById(gridAllSelectedHiddenFieldID).value;

    if ((selIds == "" || selIds == ';' || selIds == ';;') && allSelected == "false") {
        alert("Please select at least one row from the grid");
        return;
    }

    var page = "AJAX.aspx?method=SetCrystalSessionParams" +
                "&AllSelected=" + allSelected +
                "&Ids=" + selIds +
                "&ReportName=" + reportName +
                "&QBInstance=" + queryBuilderInstance +
                "&IdentityColumnName=" + identityColumnName +
                strExtraReportParameters;

    makeGETRequest(page, function() {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                if (http_request.responseText == 'OK') {
                    window.location = 'viewreport.aspx?ReportName=' + reportName;
                }
            }
            else
                alert('There was a problem with the request.');
        }
    });
   }

function CloseAddEditPopup() {
   	var emptyString = /^\s*$/;
   	var container = document.getElementById('ContainerDIV');
   	var inputElems = container.getElementsByTagName("input");
   	var selectElems = container.getElementsByTagName("select");
   	var areaElems = container.getElementsByTagName("textarea");

   	var produceWarning = false;

   	for (var i = 0; i < inputElems.length; i++) {
   		if (inputElems[i].type != "button" && inputElems[i].type != "submit" && inputElems[i].type != "hidden" && !inputElems[i].disabled) {

   			if (inputElems[i].type != "checkbox" && !emptyString.test(inputElems[i].value) && !inputElems[i].disabled) {
   				produceWarning = true;
   				break;
   			}

   			if (inputElems[i].type == "checkbox" && inputElems[i].checked && !inputElems[i].disabled) {
   				produceWarning = true;
   				break;
   			}
   		}
   	}

   	for (var i = 0; i < selectElems.length; i++) {
   		if (selectElems[i].selectedIndex > 0 && !selectElems[i].disabled) {
   			produceWarning = true;
   			break;
   		}
   	}

   	for (var i = 0; i < areaElems.length; i++) {
   		if (!emptyString.test(areaElems[i].value) && !areaElems[i].disabled) {
   			produceWarning = true;
   			break;
   		}
   	}

   	if (produceWarning) {
   		if (confirm("Are you sure you want to close this window?\n\nYou have unsaved changes.\n\nPress OK to continue or press CANCEL to leave the window open."))
   			parent.closeModal();
   	}
   	else
   		parent.closeModal();
   }
