var sSecurity = "";   
var sProvince = "";
var __sProvinceName = "";
var arrWindow;
var loadStatus;

//START - include validation rules
var html_doc = document.getElementsByTagName('head').item(0);
var js = document.createElement('script');
js.setAttribute('language', 'javascript');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', "resources/javascript/datacheck.js");
html_doc.appendChild(js);
//END - include validation rules

setupSecurity();

function getWeek() {
    var dt = new Date();
    var onejan = new Date(dt.getFullYear(),0,1);
    return Math.ceil((((dt - onejan) / 86400000) + onejan.getDay())/7);
}

//Handling for automatic logout
function body_onClick(){
    resetTimer();
}

function body_onKeyPress(){
    resetTimer();
}

function resetTimer(){
    var failSafe = 20;
    if(window.dialogHeight){
        return;
    }

    var oParent = window;

    while((!oParent.setLastActivity)&&(oParent.parent)&&failSafe){
        oParent = oParent.parent;
        failSafe--;
    }

    if(oParent.setLastActivity){
        oParent.setLastActivity();
    }
}

function document_onReadyStateChange(){
    if(document.readyState == "complete"){
        //Bind the body events
        if(document.body){
            document.body.attachEvent("onclick", body_onClick);
            document.body.attachEvent("onkeypress", body_onKeyPress);
        }
    }
}

document.attachEvent("onreadystatechange", document_onReadyStateChange);

function setupSecurity(){
	try{
	    var arrWindow = window.location.pathname.toString().split("/");
	    arrWindow = arrWindow[arrWindow.length -1].split("?");
	    if ((arrWindow[0]=="frmReturnDate.html")
			||(arrWindow[0]=="frmCaseNotes.asp")
			||(arrWindow[0]=="frmAddNewRecord.html")
			||(arrWindow[0]=="frmCPRSliderMenu.html")
			||(arrWindow[0]=="frmCPRCoolbar.html")
			||(arrWindow[0]=="frmMonitorProgress2.html")
			||(arrWindow[0]=="frmSearchRecords.html")
			||(arrWindow[0]=="frmNamesFound.asp")
			||(arrWindow[0]=="frmPerpDetails.html")
			||(arrWindow[0]=="frmContacts.html")
			||(arrWindow[0]=="frmUserDetails.html") 
			||(arrWindow[0]=="frmUserDetails.asp") 
			||(arrWindow[0]=="frmUserHistory.asp") 
			||(arrWindow[0]=="frmAddUser.html")
			||(arrWindow[0]=="frmRegionMaintenance.html")
			||(arrWindow[0]=="frmTownDetails.html")
			||(arrWindow[0]=="frmCaseSearch.asp")){
		    var oXMLPost = new ActiveXObject("Microsoft.XMLHTTP");
		    oXMLPost.Open("POST","resources/proxies/AdminLevel.asp",false);
		    oXMLPost.Send();
		    var oXML = new ActiveXObject("Microsoft.XMLDOM")
		    oXML.async = false
		    oXML.loadXML(oXMLPost.responseText);
		    sSecurity = oXML.selectSingleNode("//root/AdminLevels").text;
		    sProvince = oXML.selectSingleNode("//Province").text;
		    __sProvinceName = sProvince;
	    }
    }
    catch(err){
        alert(err.description);
    }
}

var oStatusLoading;

function showStatusLoading(){
    if(!oStatusLoading){
        oStatusLoading = document.createElement("DIV");
        oStatusLoading.style.left = 0;
        oStatusLoading.style.top = 0;
        oStatusLoading.style.width = "100%";
        oStatusLoading.style.height = "100%";
        oStatusLoading.style.textAlign = "center";
        oStatusLoading.style.textAlign = "center";
        oStatusLoading.style.zIndex = 2147483646;
        var oImg = document.createElement("IMG");
        oImg.src = "resources/image/loading.gif";
        oStatusLoading.appendChild(oImg);
        document.body.appendChild(oStatusLoading);
    }
    oStatusLoading.style.display = "block";
}

function hideStatusLoading(){
    if(oStatusLoading){
        oStatusLoading.style.display = "none";
    }
}

function showLoadingImage() 
{
	if (loadStatus) 
	{ //load status already running
		return;
	}
	loadStatus = window.showModelessDialog("statusLoading.html", "", "dialogWidth:200px;dialogHeight:200px;help:no;status:no;unadorned:yes");
}

function hideLoadingImage() 
{
	if (!loadStatus) 
	{ //load status not currently running
		return;
	}	
	loadStatus.close();
	loadStatus = ""; //re-initialize
}

function OpenModalDialog(sURL, sName, sFeatures){
	CurrURL = window.location.toString();
	arrExtension = CurrURL.split(".");
	arrExtension = arrExtension[arrExtension.length-1].split("?");
	sURL = VBReplace(sURL, ".csp", "."+arrExtension[0]);
	return window.showModalDialog(sURL,sName,sFeatures);
}

function OpenMainWindow(sURL, sName, sFeatures){
	CurrURL = window.location.toString();
	arrExtension = CurrURL.split(".");
	arrExtension = arrExtension[arrExtension.length-1].split("?");
	sURL = VBReplace(sURL, ".csp", "."+arrExtension[0]);
	window.parent.document.all("ApplicationPage").src = sURL
}

function OpenModelessDialog(sURL, sName, sFeatures)
{
	CurrURL = window.location.toString();
	arrExtension = CurrURL.split(".");
	arrExtension = arrExtension[arrExtension.length-1].split("?");
	sURL = VBReplace(sURL, ".csp", "."+arrExtension[0]);
	var oDialogArguments = new Object;
	oDialogArguments.window = window;
	oDialogArguments.User = sName
	return window.showModelessDialog(sURL,oDialogArguments,sFeatures);
}

function ChangeExtention(sURL)
{
	CurrURL = window.location.toString();
	arrExtension = CurrURL.split(".");
	arrExtension = arrExtension[arrExtension.length-1].split("?");
	sURL = VBReplace(sURL, ".csp", "."+arrExtension[0]);
	return sURL;
}

function checkIDNumber(iIDNumber){
	var sIDNumber = iIDNumber.toString();
	if(sIDNumber == "")
		return false;	
	if(sIDNumber.length != 13){
		alert("Please enter valid ID Number.");
		return false;
	}	
	var iCurrentElement = 0;
	var sCurrentElement = "";
	var IDTotal = 0;
	var indexOfDot = 0;

	for(var count = 1; count <= 13; count++){
		sCurrentElement = sIDNumber.substr(count-1,1);
		iCurrentElement = parseInt(sCurrentElement);
		
		if((count == 2)||(count == 4)||(count == 6)||(count == 8)||(count == 10)||(count == 12)){
			iCurrentElement = iCurrentElement * 2
			if(iCurrentElement >= 10){
				sCurrentElement = iCurrentElement.toString();
				iCurrentElement = parseInt(sCurrentElement.substr(0,1)) + parseInt(sCurrentElement.substr(1,1));
			}
		}
		IDTotal = IDTotal + iCurrentElement;
	}
	IDTotal = IDTotal / 10;
	indexOfDot = IDTotal.toString();
	indexOfDot = indexOfDot.indexOf(".");
	if(indexOfDot == -1){
		return true;
	}
	else{
		alert("Please enter valid ID Number.");
		return false;
	}	
}

function CheckDate(sDate)
{
	if (sDate == "") return false;
	arrDate = sDate.split("/");
	if (arrDate.length  != 3) return false;
	// Date Format - dd/mm/yyyy
	var oDate = new Date()
	if (arrDate[2] > oDate.getYear()) {
		alert("Invalid date, cannot assign future date(s)!");
		return false;
	} else if(arrDate[2] == oDate.getYear()) {
		if (arrDate[1] > (oDate.getMonth() + 1)) {
			alert("Invalid date, cannot assign future date(s)!");
			return false;
		} else if(arrDate[1] == (oDate.getMonth() + 1)) {
			if (arrDate[0] > oDate.getDate()) {
				alert("Invalid date, cannot assign future date(s)!");
				return false;
			}
		}
	}
	return true;
}

//check that Comparison Date is not greater that "Date of Incident"
function CheckAgainstIncidentDate(CompName,sCompDate,IncName,sIncDate) {
	arrCompDate = sCompDate.split("/");
	arrIncDate = sIncDate.split("/");
	
	if (arrCompDate.length != 3) { 
		alert(CompName + " is invalid");
		return false;
	}
		
	// Date Format - dd/mm/yyyy	
	if (arrCompDate[2] < arrIncDate[2]) {
		//return false;
		//return = CompName + " cannot be earlier than " + IncName;
		alert("'" +CompName+ "' cannot occur before '" +IncName+ "'");
		return false;
	} 
	else if(arrCompDate[2] == arrIncDate[2]) {
		if (arrCompDate[1] < arrIncDate[1]) {
			alert("'" +CompName+ "' cannot occur before '" +IncName+ "'");
			return false;
		} 
		else if(arrCompDate[1] == arrIncDate[1]) {
			if (arrCompDate[0] < arrIncDate[0]) {
				alert("'" +CompName+ "' cannot occur before '" +IncName+ "'");
				return false;
			}
		}
	}
	return true;
}

function MoveFirstPage() {
	var oNode =event.srcElement
	var bFound = false
	while ((oNode.parentElement) && (bFound ==false)) {
		oNode = oNode.parentElement;
		if (oNode.HTMLControlID) {
			bFound = true 
		}
    }
    var oDataGrid = oNode;
    var oDataSource = document.all(oNode.tagValues.selectSingleNode("//xmlRecordsetID").text);
   
    oDataGrid.cancelEvent = true;  
    oDataSource.ExecuteCMD(oDataSource.ActiveCommand,"First");
}
 
function MoveLastPage() {
	var oNode =event.srcElement
	var bFound = false
	while ((oNode.parentElement) && (bFound ==false)) {
		oNode = oNode.parentElement;
		if (oNode.HTMLControlID) {
			bFound = true 
		}
    }
    var oDataGrid = oNode;
    var oDataSource = document.all(oNode.tagValues.selectSingleNode("//xmlRecordsetID").text);
   
    oDataSource.ExecuteCMD(oDataSource.ActiveCommand,"Last");
    oDataGrid.cancelEvent = true;
}
 
function MoveNextPage() {
	var oNode =event.srcElement
	var bFound = false
	while ((oNode.parentElement) && (bFound ==false)) {
		oNode = oNode.parentElement;
		if (oNode.HTMLControlID) {
			bFound = true 
		}
    }
    var oDataGrid = oNode;
    var oDataSource = document.all(oNode.tagValues.selectSingleNode("//xmlRecordsetID").text);
   
    if (oDataSource.CommandSpecs.selectSingleNode("//" + oDataSource.ActiveCommand).getAttribute("EOF") != 1 && oDataSource.CommandSpecs.selectSingleNode("//" + oDataSource.ActiveCommand).getAttribute("EOF") != "1") {
        oDataSource.ExecuteCMD(oDataSource.ActiveCommand,"Next");
                
    }
     oDataGrid.cancelEvent = true;
}
 
function MovePreviousPage() {
	var oNode =event.srcElement
	var bFound = false
	while ((oNode.parentElement) && (bFound ==false)) {
		oNode = oNode.parentElement;
		if (oNode.HTMLControlID) {
			bFound = true 
		}
    }
    var oDataGrid = oNode;
    var oDataSource = document.all(oNode.tagValues.selectSingleNode("//xmlRecordsetID").text);
    if (oDataSource.CommandSpecs.selectSingleNode("//" + oDataSource.ActiveCommand).getAttribute("BOF") != 1 && oDataSource.CommandSpecs.selectSingleNode("//" + oDataSource.ActiveCommand).getAttribute("BOF") != "1") {
		oDataSource.ExecuteCMD(oDataSource.ActiveCommand,"Previous");     
    }
    oDataGrid.cancelEvent = true;
    
}

function SaveScreenPosition(sFormName){
	try{
		setCookie(sFormName+"_Top",window.screenTop - 30);
		setCookie(sFormName+"_Left",window.screenLeft);
		setCookie(sFormName+"_Width",document.body.offsetWidth - 5);
		setCookie(sFormName+"_Height",document.body.offsetHeight - 5);
	}
	catch(err){}
}

function PositionedOpenWindow(sURL,sFormName,sDialogArguments)
{
	var sTop = getCookie(sFormName+"_Top");
	var sTopArgument = "";
	if (sTop !=null){
		if (parseInt(sTop,10)< 0){
			sTop = 0;
		}
		sTopArgument = ",top = "+sTop+"px";
	}
	var sLeft = getCookie(sFormName+"_Left");
	var sLeftArgument = "";
	if (sLeft !=null){
		if (parseInt(sLeft,10)< 0){
			sLeft = 0;
		}
		sLeftArgument = ",left = "+sLeft+"px";
	}
	var sWidth = getCookie(sFormName+"_Width");
	var sWidthArgument = "";
	if (sWidth !=null){
		sWidthArgument = ",width = "+sWidth+"px";
	}
	var sHeight = getCookie(sFormName+"_Height");
	var sHeightArgument = "";
	if (sHeight !=null){
		sHeightArgument = ",height = "+sHeight+"px";
	}
	var oWindow = window.open(sURL, sFormName,sDialogArguments+sTopArgument+sLeftArgument+sWidthArgument+sHeightArgument);
	return oWindow;
}

function setCookie(sName, sValue)
{
  date = new Date();
  date.setFullYear(parseInt(date.getFullYear()+1,10));
  document.cookie = sName + "=" + escape(sValue) + "; expires=" + date.toGMTString();
}


function getCookie(sName)
{
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
      return unescape(aCrumb[1]);
  }
  return null;
}

function ShowColumnSelector() {
	var oElement = event.srcElement;
	var sGridID;
	while (oElement) {
		if(oElement.tagName == "DIV") {
			if(oElement.id.substring(0,5) == "div__") { 
				sGridID = oElement.id.split("__")[1];
				break;
			}
		}
		oElement = oElement.parentElement;
	}
	if(sGridID == null) return;
	var oGrid = document.all(sGridID);
	if(oGrid == null) return;
	oGrid.showColumnSelector();
}
