// JScript source code
// Date Validation
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){		
		return false;
	}
	else{
		return true;
	}
}

function addLoadEvent(func) {	
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;		
	} 
	else {
		window.onload = function() {
		oldonload();
		func();
		}
	}
}

function confirmlogout(){
	if (confirm('Are you sure you want to logout?')){
		location.href='index.asp?Logout=True';
	}
}

function isValidEmail(str) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(str)){
		return true;
	}
	else {
		return false;
	}
}

function checklogin(){
	var ftxt = '';

	if (document.beamslogin.Username.value==''){
		ftxt += '\n- Please enter your Username.';
	}
	
	if (document.beamslogin.Password.value==''){
		ftxt += '\n- Please enter your Password.';
	}
		
	if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	}
}

// Session Countdown Timer
var _countDowncontainer=0;
var _currentSeconds=0;

function ActivateCountDown(strContainerID, initialValue) {
	_countDowncontainer = document.getElementById(strContainerID);
	
	if (!_countDowncontainer) {
		alert("count down error: container does not exist: "+strContainerID+
			"\nmake sure html element with this ID exists");
		return;
	}
	
	SetCountdownText(initialValue);
	window.setTimeout("CountDownTick()", 1000);
}

function CountDownTick() {
	SetCountdownText(_currentSeconds-1);
	window.setTimeout("CountDownTick()", 1000);
}

function SetCountdownText(seconds) {	
	_currentSeconds = seconds;
	var minutes=parseInt(seconds/60);		
	minutes = (minutes%60)+1;	
	var strText = AddZero(minutes)
	_countDowncontainer.innerHTML = strText;
}

function AddZero(num) {
	return ((num >= 0)&&(num < 10))?"0"+num:num+"";
}

/* Edit Profile */
function checkeditprofile(){
    var ftxt = '';
    
    if (document.updateprofile.Name.value==''){
        ftxt += '\n- Please enter your Name.';
    }
    
    /*
    if (document.updateprofile.Address.value==''){
        ftxt += '\n- Please enter your Address.';
    }
    
    if (document.updateprofile.Postcode.value==''){
        ftxt += '\n- Please enter your Postcode.';
    }
    */
    
    if (document.updateprofile.Telephone.value==''){
        ftxt += '\n- Please enter your Telephone Number.';
    }
    
    if (isValidEmail(document.updateprofile.EmailAddress.value)==false){
        ftxt += '\n- Please enter your Email Address.';
    }

    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	}
}

/* Staff Management */
function checkstaffform(){
    var ftxt = '';
    
    if (document.staffform.RoleID.value==''){
        ftxt += '\n- Please select a Role.';
    }
    
    if (document.staffform.Name.value==''){
        ftxt += '\n- Please enter a Name.';
    }
    
    /*
    if (document.staffform.Address.value==''){
        ftxt += '\n- Please enter your Address.';
    }
    
    if (document.staffform.Postcode.value==''){
        ftxt += '\n- Please enter your Postcode.';
    }
    */
    
    if (document.staffform.Telephone.value==''){
        ftxt += '\n- Please enter a Telephone Number.';
    }
    
    if (isValidEmail(document.staffform.EmailAddress.value)==false){
        ftxt += '\n- Please enter an Email Address.';
    }
    
    if (document.staffform.Position.value==''){
        ftxt += '\n- Please enter a Position.';
    }

    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	}
}

function checkstaffdelete(submitstring){
    if (confirm('** WARNING **\n\nAre you sure you want to delete this member of staff?')){
        location.href=submitstring;
    }
}

/* Client Functions */
var bnewcompany = false;
function enablecompanyform(formsubmit){
    var formarr = formsubmit.split("|");
    var newcompany = document.getElementById("newcompany");
    var clientuser = document.getElementById("clientuser");
    
    if (formarr[0]=='true'){
        bnewcompany = true;        
    }
    else {        
        bnewcompany = false;
    }
    
    if (formsubmit!==''){
        newcompany.style.display='block';
    }
    else {
        newcompany.style.display='none';
    }
    
    var qstring = "?ClientID=" + formarr[1];
	if(document.layers && document.layers['datadiv'].load){				
		document.layers['datadiv'].load('Scripts/GetCompanyInformation.asp' + qstring,0);		
	}
	else if(window.frames && window.frames.length){				
		window.frames['dataframe'].window.location.replace('Scripts/GetCompanyInformation.asp' + qstring);				
	}	
	
	clientuser.style.display='block';
}

function dataCatchCompanyDetails(formheader,companyname,companyaddress,companypostcode,companytelephone,isextended){   	
    document.getElementById("formheader").innerHTML = formheader;
	document.clientform.Company.value = companyname;
	document.clientform.Address.value = companyaddress;
	document.clientform.Postcode.value = companypostcode;
	document.clientform.Telephone.value = companytelephone;
	document.clientform.IsExtended.value = isextended;
}


function checkclientform(){
    var ftxt = '';
    
    var comptext = '';    
    /*
    if (document.clientform.Company.value==''){
        comptext += '\n- Please enter a Company Name.';
    }
    
    if (document.clientform.Address.value==''){
        comptext += '\n- Please enter an Address.';
    }
    
    if (document.clientform.Postcode.value==''){
        comptext += '\n- Please enter a Postcode.';
    }
    
    
    if (document.clientform.Telephone.value==''){
        comptext += '\n- Please enter a Telephone Number.';
    }
    */
    
    if (comptext!==''){
        ftxt += '\n** New Company Information **\n' + comptext;
    }
    
    var usercount = document.clientform.UserCount.value;
    if (usercount=='0'){  
        bnewcompany = true;
    }
    
    if (bnewcompany){
        var utxt = '';
        if (document.clientform.Name.value==''){
            utxt += '\n- Please enter a Contact Name.';
        }    
        
        /*
        if (isValidEmail(document.clientform.EmailAddress.value)==false){
            utxt += '\n- Please enter an Email Address.';
        }
        */
               
        if (utxt!==''){
            if (comptext!==''){
                ftxt +='\n'
            }
            ftxt += '\n** New Client User Information **\n' + utxt;
        }
    }
    else {
        var userarr = document.clientform.UserArr.value;
        var userlist = userarr.split(",");
        
        var etxt = '';
        for (var i=0;i<userlist.length;i++){
            if (eval('document.clientform.Name_' + userlist[i] + '.value')==''){
                etxt += '\n- Please enter all Names.';
            }
            
            /*
            if (isValidEmail(eval('document.clientform.EmailAddress_' + userlist[i] + '.value'))==false){
                etxt += '\n- Please enter all Email Addresses.';
            }
            */
        }  
        
        if (etxt!==''){
            if (comptext!==''){
                ftxt +='\n'
            }
            ftxt += '\n** Update User Information **\n' + etxt;
        }      
    }

    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	}
}

function checksignaturedelete(submitstring){
    if (confirm('Are you sure you want to remove this signature?')){
        location.href=submitstring;
    }
}

function checkclientsearch(){
    if (document.clientsearch.Name.value==''&&document.clientsearch.Company.value==''){
        alert('Please enter a Name or Company Name.');
        return false;
    }
    else {
        return true;
    }
}

function showClientMenu(menuid,maxnum){
    var menu = document.getElementById("menu" + menuid);
    
    if (menu.style.display=='none'){
        menu.style.display='block';       
    }   
    else {
        menu.style.display='none';    
    }
    
    for (var i=0;i<maxnum;i++){
        if ((i+1)!==menuid){
            document.getElementById("menu" + (i+1)).style.display='none';           
        }
    }
}

function checkuserdelete(submitstring){
    if (confirm('** WARNING **\n\nAre you sure you want to delete this user?\n\nRemoving this user will also remove any reports or re-inspections that have been created by this user. This action cannot be reversed.\n\nAre you sure you wish to proceed?')){
        location.href=submitstring;
    }
}

function checklogodelete(submitstring){
    if (confirm('Are you sure you want to remove this logo?')){
        location.href=submitstring;
    }
}

/* Site Photo */
function checkphotodelete(submitstring){
    if (confirm('Are you sure you want to remove this site photograph?')){
        location.href=submitstring;
    }
}

/* Site Search */
function checksitesearch(){
    if (document.sitesearch.SiteName.value==''&&document.sitesearch.Company.value==''&&document.sitesearch.SurveyNumber.value==''){    
        alert('Please enter your Search Criteria.');
        return false;
    }
    else {
        return true;
    }
}

/* Survey Search */
function checksurveysearch(){
    if (document.surveysearch.SurveyNumber.value==''){    
        alert('Please enter your Search Criteria.');
        return false;
    }
    else {
        return true;
    }
}

/* Reports Search */
function checkreportsearch(){
    if (document.reportsearch.Company.value==''&&document.reportsearch.ReportNumber.value==''){    
        alert('Please enter your Search Criteria.');
        return false;
    }
    else {
        return true;
    }
}

/* Site Functions */
function ShowRoomSaveButton(showbutton){    
    var savebutton = document.getElementById("savebutton");
    if (showbutton){
        savebutton.style.display='block';
    }
    else {
        savebutton.style.display='none';
    }    
}

function showSiteRecord(recordNumber,bControl,bNewRecord){ 
    var roomcount = document.surveyform.RoomCount.value;
    var siteID = document.surveyform.SiteID.value;
    var surveyID = document.surveyform.SurveyID.value;
    
    if (bControl){	        
        SaveRoomInformation(recordNumber,siteID,bNewRecord);	    
    }
    
    // Room Copy Button
    var roomcopybutton = document.getElementById("roomcopybutton");   
    if (recordNumber<roomcount){
        roomcopybutton.style.display='block';
    }
    else {
        roomcopybutton.style.display='none';
    }
    
    // Room Delete Button
    var roomdeletebutton = document.getElementById("roomdeletebutton");   
    if (recordNumber<roomcount){
        roomdeletebutton.style.display='block';        
    }
    else {
        roomdeletebutton.style.display='none';
    }
    
    if (recordNumber<=roomcount){          
        var qstring = "?SiteID=" + siteID + '&SurveyID='+ surveyID +'&RecordNumber=' + recordNumber;
	    if(document.layers && document.layers['roomdatadiv'].load){				
		    document.layers['roomdatadiv'].load('Scripts/GetSiteRoom.asp' + qstring,0);		
	    }
	    else if(window.frames && window.frames.length){				
		    window.frames['roomdataframe'].window.location.replace('Scripts/GetSiteRoom.asp' + qstring);				
	    }	
	
	    //alert('Scripts/GetSiteRoom.asp' + qstring)
	    if (bNewRecord){
	        ShowRoomSaveButton(true);
	    }
	    else {
	        if (roomcount==recordNumber){
	            ShowRoomSaveButton(true); 
	        }   
	        else {
	            ShowRoomSaveButton(false);
	        }
	    }
	}
}

var _dialogPromptID=null;
var _blackoutPromptID=null;
var val = null;

function ConfirmRoomCopy(submitstring,numbercopy){   
   if (numbercopy==null||numbercopy==''){   
       var thetext = 'Please enter the Quantity of this record you wish to copy (enter number).'
       var thevalue = 0;
       var thenum = 0;
       
       that=this;
           
       // Check to see if this is MSIE 7.   This isn't a great general purpose
       // detection system but it works well enough just to find MSIE 7.
       var _isIE7=(navigator.userAgent.indexOf('MSIE 7')>0);

       this.wrapupPrompt = function(){      
          if (_isIE7) {    
             _dialogPromptID.style.display='none';        
             _blackoutPromptID.style.display='none'; 
             
             thenum = document.getElementById("iepromptfield").value;
             ConfirmRoomCopy(submitstring,thenum);
          }  
       }
          
       if (_isIE7) {      
          if (_dialogPromptID==null) {         
             var tbody = document.getElementsByTagName("body")[0];         
             tnode = document.createElement('div');         
             tnode.id='IEPromptBox';         
             tbody.appendChild(tnode);        
             _dialogPromptID=document.getElementById('IEPromptBox');         
             tnode = document.createElement('div');         
             tnode.id='promptBlackout';        
             tbody.appendChild(tnode);        
             _blackoutPromptID=document.getElementById('promptBlackout');         
             //_blackoutPromptID.style.opacity='.9';
             _blackoutPromptID.style.position='absolute';
             _blackoutPromptID.style.top='0px';
             _blackoutPromptID.style.left='0px';
             //_blackoutPromptID.style.backgroundColor='#555555';
             //_blackoutPromptID.style.filter='alpha(opacity=90)';
             _blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
             _blackoutPromptID.style.display='block';
             _blackoutPromptID.style.zIndex='50';
             // assign the styles to the dialog box
             _dialogPromptID.style.border='2px solid blue';
             _dialogPromptID.style.backgroundColor='#DDDDDD';
             _dialogPromptID.style.position='absolute';
             _dialogPromptID.style.width='330px';
             _dialogPromptID.style.zIndex='100';
          }
         
          var tmp = '<div style="width: 100%; background-color: blue; color: white; font-family: verdana; font-size: 10pt; font-weight: bold; height: 20px">Input Required</div>';
          tmp += '<div style="padding: 10px">'+thetext + '<BR><BR>';      
          tmp += '<input id="iepromptfield" name="iepromptdata" type=text size=46 value="'+thevalue+'">';
          tmp += '<br><br><center>';
          tmp += '<input type="button" onclick="that.wrapupPrompt()" value="&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;">';
          tmp += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
          tmp += '<input type="button" onclick="that.wrapupPrompt()" value="&nbsp;Cancel&nbsp;">';
          tmp += '</div>';
         
          _blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
          _blackoutPromptID.style.width='100%';
          _blackoutPromptID.style.display='block';
         
          _dialogPromptID.innerHTML=tmp;
          _dialogPromptID.style.top=parseInt(document.documentElement.scrollTop+(screen.height/3))+'px';
          _dialogPromptID.style.left=parseInt((document.body.offsetWidth-315)/2)+'px';
          _dialogPromptID.style.display='block';
          
          document.getElementById('iepromptfield').focus();      
        } else {
            // we are not using IE7 so do things "normally"
            thenum = prompt(thetext,thevalue);  
            if (thenum!==''&&thenum!==null&&thenum>0){    
                ConfirmRoomCopy(submitstring,thenum); 
            }
        }
    }
    else {   
        //alert(numbercopy);
        if (numbercopy>0){
            location.href=submitstring + '&NumberCopy=' + numbercopy;
        }
    }      
}

function dataCatchRoomDetails(RoomID,RecordNumber,FloorLevel,BlockNumberName,RoomNumber,RoomDescription,AccessOptionID,Ceiling,Walls,FloorDescription,AccessOther,ItemNotAccessed,ReasonNoAccess,IsExtended){
	document.surveyform.RoomID.value = RoomID;
	document.surveyform.RecordNumber.value = RecordNumber;
	document.surveyform.FloorLevel.value = FloorLevel;
	document.surveyform.BlockNumberName.value = BlockNumberName;
	document.surveyform.RoomNumber.value = RoomNumber;
	document.surveyform.RoomDescription.value = RoomDescription;
	document.surveyform.AccessOptionID.value = AccessOptionID;
	
	//alert(RoomID);
	
	if (IsExtended==true){
	    document.surveyform.Ceiling.value = Ceiling;
	    document.surveyform.Walls.value = Walls;
	    document.surveyform.FloorDescription.value = FloorDescription;
	    document.surveyform.AccessOther.value = AccessOther;
	}
	
	document.surveyform.ItemNotAccessed.value = ItemNotAccessed;
	document.surveyform.ReasonNoAccess.value = ReasonNoAccess;
	
	// Update Counters	
	textCounter(document.surveyform.ItemNotAccessed,'INA_Char',250);
	textCounter(document.surveyform.ReasonNoAccess,'RNA_Char',250)
}

// Room Check
function SaveRoomInformation(recordNumber,siteID,newRecord){
    var surveyID = document.surveyform.SurveyID.value;
    var IsExtended = document.surveyform.IsExtended.value;
    
    var ftxt = '';
    
    if (document.surveyform.FloorLevel.value==''){ ftxt += '\n- Please enter a Floor Level.'; } 
    if (document.surveyform.BlockNumberName.value==''){ ftxt += '\n- Please enter a Block.'; }
    if (document.surveyform.RoomNumber.value==''){ ftxt += '\n- Please enter a Room Number.'; } 
    //if (document.surveyform.RoomDescription.value==''){ ftxt += '\n- Please enter a Room Description.'; }
    if (document.surveyform.AccessOptionID.value==''){ ftxt += '\n- Please if the Room has been Accessed.'; }
    
    /* Check to see if Duplicate Room */  
    if (window.XMLHttpRequest) {
        http = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        http = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    var url = 'Scripts/RoomChecker.asp?';    
    var fullurl = url + 'do=check_exists&SurveyID='+ document.surveyform.SurveyID.value +'&RoomNumber=' + document.surveyform.RoomNumber.value + '&RoomID=' + document.surveyform.RoomID.value;
    //var fullurl = url + 'do=check_exists&SurveyID=96&RoomNumber=Room 1';
    
    //alert(fullurl);
    
    http.open("GET", fullurl, false);
    http.send();
    
    var xmlObj = http.responseXML;
    var xmlResult = xmlObj.getElementsByTagName('notfound').item(0).firstChild.data;
    
    //return xmlResult; 
    
    if (xmlResult=='False'){
        ftxt += '\n- The Room Number you have entered is already used in this survey.';
    }   
    
    /* Handle Errors etc */
    if (ftxt!==''){
        if (newRecord){
            alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
            return false;
        }
        else {
            return 'One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.';        
        }
    }
    else {
        var qstring = '?frmAutoSubmit=True&frmMode=Room&SiteID=' + siteID + '&SurveyID='+ surveyID + '&RecordNumber=' + recordNumber;    
        
        if (IsExtended==true){
            var fieldarr = new Array("RoomID","FloorLevel","BlockNumberName","RoomNumber","RoomDescription","AccessOptionID","Ceiling","Walls","FloorDescription","AccessOther","ItemNotAccessed","ReasonNoAccess");
        }
        else {
            var fieldarr = new Array("RoomID","FloorLevel","BlockNumberName","RoomNumber","RoomDescription","AccessOptionID","ItemNotAccessed","ReasonNoAccess");
        }
        for (var i=0;i<fieldarr.length;i++){
            //var thevalue = escape(eval('document.surveyform.'+fieldarr[i]+'.value')); 
            var thevalue = eval('document.surveyform.'+fieldarr[i]+'.value'); 
            //alert(thevalue);
            thevalue = thevalue.replace("\n","<br />");
            qstring += '&' + fieldarr[i] + '=' + thevalue;
        }
        
        //alert(qstring);
        
        /*
        if(document.layers && document.layers['roomupdatedatadiv'].load){				
	        document.layers['roomupdatedatadiv'].load('system_survey_form.asp' + qstring,0);		
        }
        else if(window.frames && window.frames.length){				
	        window.frames['roomupdatedataframe'].window.location.replace('system_survey_form.asp' + qstring);				
        }
        */
        
        var roomurl = 'system_survey_form.asp' + qstring;
                
        http.open("GET", roomurl, false);
        http.send();	
        
        //alert(roomurl);
                
        if (document.surveyform.RoomID.value==''){
            location.href='system_survey_form.asp?SiteID='+ siteID +'&SurveyID=' + surveyID  + '&GotoRecord='+ (recordNumber+1) +'#tabs-rooms'
        }
        else {
            //showSiteRecord((recordNumber+1),true,false);
        }
        
        return false;
    }   
}

/* Manage Survey Item Number - Changes Sample Analysed by to Not Applicable */
var oversampleanalysedby = false;
function manageSurveyItemNumber(theval){
    var thevalue = theval.toLowerCase();

    if (thevalue=='as'){
        oversampleanalysedby = true;
    }
    else if (thevalue=='no sample - presumed'){
        oversampleanalysedby = true;
    }
    else {
        oversampleanalysedby = false;
    }
    
    if (oversampleanalysedby){
        // Change the Sample Anaylysed By to show "Not Applicable" (second item in the list)
        document.surveyform.SampleAnalysedByUserID.selectedIndex = 0;
        
        // Change the Asbestos Amount for No 1 to Strongly Presumed
        document.surveyform.AsbestosAmountID_1.selectedIndex = 1;
    }
}

function checknewitem(){
    var newitemtext = '';
    // Room Information
    if (document.siteform.BlockNumberName_NEW.value==''){ newitemtext += '\n- Please enter a Block Number Name.'; }        
    if (document.siteform.RoomNumber_NEW.value==''){ newitemtext += '\n- Please enter a Room Number.'; }
    if (document.siteform.RoomDescription_NEW.value==''){ newitemtext += '\n- Please enter a Description.'; }        
    if (document.siteform.AccessOptionID_NEW.value==''){ newitemtext += '\n- Please select an Access Gained Option.'; }
    if (document.siteform.FloorLevel_NEW.value==''){ newitemtext += '\n- Please enter a Floor Level.'; }      
    if (document.siteform.SurveyItemNumber_NEW.value==''){ newitemtext += '\n- Please enter a Survey Item Number.'; }
    if (document.siteform.SampleNumber_NEW.value==''){ newitemtext += '\n- Please enter a Sample Number.'; }  
    if (document.siteform.RoomExtent_NEW.value==''){ newitemtext += '\n- Please select a Extent.'; }  
    if (document.siteform.MaterialID_NEW.value!==''){
        if (document.siteform.ExtentBCLScoreID_NEW.value==''){ newitemtext += '\n- Please select a Extent Score.'; }
    }    
    //if (document.siteform.MaterialID_NEW.value==''){ newitemtext += '\n- Please select a Product Type.'; } 
    if (document.siteform.ItemDescription_NEW.value==''){ newitemtext += '\n- Please enter an Item Description.'; } 
    if (document.siteform.Comments_NEW.value==''){ newitemtext += '\n- Please enter Comments.'; }
    
    // Sample Information
    if (document.siteform.AsbestosTypeID_1_NEW.value==''){ newitemtext += '\n- Please select a Sample 1 Sample Type.'; }  
    if (document.siteform.AsbestosTypeID_1_NEW.value!==''){
        if (document.siteform.AsbestosAmountID_1_NEW.value==''){ newitemtext += '\n- Please select a Sample 1 Sample Amount.'; }
    }
    if (oversampleanalysedby==false){
        //if (document.siteform.SampleAnalysedByUserID_NEW.value==''){ newitemtext += '\n- Please select a Sample Analysed By User.'; }        
    }
    if (document.siteform.NotifiableID_NEW.value==''){ newitemtext += '\n- Please select a Licensable.'; }
    if (document.siteform.SurfaceTreatmentID_NEW.value==''){ newitemtext += '\n- Please select a Surface Treatment.'; }
    if (document.siteform.ConditionID_NEW.value==''){ newitemtext += '\n- Please select a Condition.'; }
    //if (document.siteform.PriorityID_NEW.value==''){ newitemtext += '\n- Please select a Priority.'; } 
    if (document.siteform.Priority_NEW.value==''){ newitemtext += '\n- Please select or enter a Priority.'; } 
    if (document.siteform.AccessibilityID_NEW.value==''){ newitemtext += '\n- Please select a Accessibility.'; } 
    if (document.siteform.LocationID_NEW.value==''){ newitemtext += '\n- Please select a Location.'; }   
    if (document.siteform.RecommendationID_NEW.value==''){ newitemtext += '\n- Please select a Recommendation.'; }        
  
    return newitemtext;
}

function addMonth(d,month){
    t  = new Date (d);
    t.setMonth(d.getMonth()+ month) ;
    if (t.getDate() < d.getDate())
    {
        t.setDate(0);
    }
    return t;
} 



function changeReinspectionDate(monthsval){
    if (monthsval!==''){
        var dateofwork = document.siteform.DateofWork.value;
                
        var monthsadd = parseFloat(monthsval);
        
        d = new Date();           
        var newdate = new Date(addMonth(d,monthsadd));
        
        //alert(newdate.getDay());
        
        var newday = newdate.getDate();
        if (newday<10){
	        newday = '0' + newday;
        }

        var newmonth = (newdate.getMonth()+1);
        if (newmonth<10){
	        newmonth = '0' + newmonth;
        }

        //alert(newday + '/' + newmonth + '/' + newdate.getFullYear());

        document.siteform.ReInspectionDate.value = (newday + '/' + newmonth + '/' + newdate.getFullYear());
        //document.siteform.ReInspectionDate.value = 'TEST';
    }
}

function checksiteform(){    
    var ftxt = '';
    if (document.siteform.SiteName.value==''){
        ftxt += '\n- Please enter a Site Name.';
    }
    
    /*
    if (document.siteform.SiteAddress1.value==''){
        ftxt += '\n- Please enter a Site Address 1.';
    }
    
    if (document.siteform.Town.value==''){
        ftxt += '\n- Please enter a Town.';
    }
    
    if (document.siteform.County.value==''){
        ftxt += '\n- Please enter a County.';
    }
    
    if (document.siteform.Postcode.value==''){
        ftxt += '\n- Please enter a Postcode.';
    }
    */
   
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		return true;
	}
}

function confirmsiteduplication(submitstring){
    if (confirm('** WARNING **\n\nAre you sure you want to duplicate this site?')){
        location.href=submitstring;
    }
    else {
        return false;
    }
}

function controlAsbestosAmount(fieldval,fieldname){
    var field = document.getElementById(fieldname);
    
    
}

function checksiteitemremove(siteid,itemid,reinspectionid,clientid){
    if (isDate(eval('document.siteform.RemovalTreatmentDate_'+itemid+'.value'))==false){
        alert('Please enter a Removal / Treatment Date (Management Tab)');
        return false;
    }
    else {
        if (confirm('** WARNING **\n\nAre you sure you wish to confirm this item has been removed?')){
            location.href='system_site_form.asp?SiteID='+siteid+'&ItemID='+itemid+'&Mode=RemoveItem&ReinspectionID=' + reinspectionid + '&ClientID=' + clientid;           
            
        }
        else {
            return false;
        }
    }
}

function copyitem(siteid,itemid){
    var numcopy = prompt("Please enter the number of copies you wish to make","1");
    
    if (numcopy==null){
        return false;
    } 
    else {
        if (confirm('** WARNING **\n\nAre you sure you wish to copy this site item ' + numcopy + ' times?\n\nOnce confirmed you will need to manually remove the copies!\n\nAre you sure you wish to proceed?')){
            location.href='system_site_form.asp?SiteID='+siteid+'&ItemID='+itemid+'&NumberCopy='+numcopy+'&Mode=CopyItem';  
        }
    }
}

/* Reinspection Functions */
function confirmreinspection(submitstring){
    if (confirm('Are you sure you want to create a re-inspection of this site?')){
        location.href=submitstring;
    }
}

/*
function checkreinspectionform(){
    var ftxt = '';
    
    if (isDate(document.reinspectionform.ReinspectionDate.value)==false){
        ftxt += '\n- Please enter a Date of Reinspection.';
    }
    
    if (document.reinspectionform.ReportNumber.value==''||document.reinspectionform.ReportNumber=='S'){
        ftxt += '\n- Please enter a Report Number.';
    }
    
    if (document.reinspectionform.SignedUserID.value==''){
        ftxt += '\n- Please select a Passed By User.';
    }
    
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
		if (confirm('** ALERT **\n\nBy confirming this message box you are accepting that the reinspection has now been done and verified.\n\nConfirming this message will generate a new report based on the reinspection details and will be put into the Pending Review Queue.\n\nAre you sure you wish to proceed?')){
		    return true;
		}
		else {
		    return false;
		}
	}
}
*/

/* Reports Functions */
function reportcomponent(submitstring){
    if (confirm('Are you sure you wish to generate and download the selected report component?')){
        location.href=submitstring;
    }
}

function plandownload(submitstring){
    if (confirm('Are you sure you wish to download this Report Plan?')){
        location.href=submitstring;
    }
}

function checkreportplanupload(){
    if (document.planupload.File.value==''){
        alert('Please select a Plan to Upload.');
        return false;
    }
    else {
        return true;
    }
}

function checkreportsignoff(){    
    var ftxt = '';    
    
    /*
    if (document.reportsignoff.OrderPlacedBy.value==''){
        ftxt += '\n- Please enter an Order Placed By Name.';       
    }
        
    if (document.reportsignoff.TechnicalManager.value==''){
        ftxt += '\n- Please enter a Technical Manager Name.';       
    }
    */
    
    if (document.reportsignoff.SignedUserID.value==''){
        ftxt += '\n- Please select a Signed User.';       
    }
    
    if (document.reportsignoff.NotifyClient.value=='True'&&document.reportsignoff.NotifyUserID.value==''){
        ftxt += '\n- Please select a Notify User.';
    }
    
    if (ftxt!==''){
        alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
    }
    else {
        if (confirm('Are you sure you want to sign-off this report?')){
            return true;
        }
        else {
            return false;
        }
    }
}

function confirmdeleteplan(submitstring){
    if (confirm('Are you sure you want to delete this plan?')){
        location.href=submitstring;
    }
}

// JScript File
function toggle_reportnumber(userid) {
    if (window.XMLHttpRequest) {
        http = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        http = new ActiveXObject("Microsoft.XMLHTTP");
    }
    handle = document.getElementById(userid);
    var url = 'Scripts/ReportChecker.asp?';
    if(handle.value.length > 0) {
        var fullurl = url + 'do=check_reportnumber_exists&reportnumber=' + encodeURIComponent(handle.value);
        http.open("GET", fullurl, true);
        http.send(null);
        http.onreadystatechange = statechange_reportnumber;
    }else{
        //document.getElementById('emailaddress_exists').innerHTML = '';
    }
    
    //alert(fullurl);
}

var reportoverwrite = false;
function statechange_reportnumber() {    
    if (http.readyState == 4) {
        var xmlObj = http.responseXML;
        var xmlResult = xmlObj.getElementsByTagName('result').item(0).firstChild.data;
        
        //alert(xmlResult);
        
        if (xmlResult=='True'){        
            reportoverwrite = true;
        }
        else if(xmlResult=='False') {
            reportoverwrite = false;
        }
    }
}

function checkcreatereport(){
    var ftxt = '';
    
    //alert(reportoverwrite);
    
    if (document.createreport.ReportNumber.value==''||document.createreport.ReportNumber.value=='S'){
        ftxt += '\n- Please enter a Report Number.';
    }    
            
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
	    if (reportoverwrite){
	        if (confirm('** WARNING **\n\nThe report number you have specified has already been used.\n\nAre you sure you wish to overwrite (permanently) the existing report?')){
	            return true;
	        }
	        else {
	            return false;
	        }
	    }        
	    else {    
		    if (confirm('Are you sure you want to create this new report?')){
		        return true;
		    }
		    else { 
		        return false;
		    }
		}
	}
}

function enablenotifyclientuser(bool){
    var NotifyUserID = document.getElementById("NotifyUserID");
    
    if (bool=='True'){
        NotifyUserID.disabled = false;
    }
    else {
        NotifyUserID.disabled = true;
    }
}

/* Survey Type Dropdown */
function controlSurveyType(){   
    var thefield = document.surveyform.TypeID.value;
    var thearr = thefield.split("|");
    
    var caveatfield = document.getElementById("CaveatField");
    var scopeextended = document.getElementById("ScopeExtended");
    
    if (thearr[1]=='True'){
        caveatfield.style.display='block';
    }
    else {
        caveatfield.style.display='none';
    }
    
    if (thearr[2]=='True'){
        scopeextended.style.display='block';
    }
    else {
        scopeextended.style.display='none';
    }
}

/* Survey */
function checksurveyform(){
    var ftxt = '';
    
    if (document.surveyform.SurveyNumber.value==''||document.surveyform.SurveyNumber.value=='S'){
        ftxt += '\n- Please enter a Survey Number.';
    }
    
    /*
    if (isDate(document.surveyform.DateofWork.value)==false){
        ftxt += '\n- Please enter a Date of Work.';
    }
    */
    if (document.surveyform.DateofWork.value==''){
        ftxt += '\n- Please enter a Date of Work.';
    }
    
    if (document.surveyform.SiteContact.value==''){
        ftxt += '\n- Please enter a Site Contact.';
    }
    
    if (isDate(document.surveyform.ReinspectionDate.value)==false){
        ftxt += '\n- Please enter a Re-Inspection Date.';
    }
    
    if (document.surveyform.TechnicalManagerID.value==''){
        ftxt += '\n- Please select a Technical Manager.';
    }
    
    if (document.surveyform.TypeID.value==''){
        ftxt += '\n- Please select a Survey Type.';
    }
    
    if (document.surveyform.OrderPlacedBy.value==''){
        ftxt += '\n- Please enter an Order Placed By Name.';
    }    
    
    if (document.surveyform.OfficeID.value==''){
        ftxt += '\n- Please select an Office.';
    }
    
    /* Optional - For Custom Fields */
    if (document.surveyform.CustomFieldsArr.value!==''){
        var CustomFieldsArr = document.surveyform.CustomFieldsArr.value;
        var CustomArr = CustomFieldsArr.split(",");
        
        var customcounter = 0;
        var customlength = 0
        
        for (var i=0;i<CustomArr.length;i++){
            customlength += 1;
        
            if (eval('document.surveyform.CustomValue' + CustomArr[i] + '.value')!==''){
                customcounter += 1;
            }
        }
        
        if (customcounter<customlength){
            ftxt += '\n- Please enter a value for all Custom Fields.';
        }
    }
    
    if (document.surveyform.Surveyor1.value==''){
        ftxt += '\n- Please select a Surveyor 1 (Lead)';
    }
    
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
	    return true;
	}
}

function checkitemphotodelete(submitstring){
    if (confirm('Are you sure you want to delete this photo?')){
        location.href=submitstring;
    }
}

function ShowSurveySaveButton(showbutton){    
    var itemsavebutton = document.getElementById("itemsavebutton");
    var managementsavebutton = document.getElementById("managementsavebutton");
    if (showbutton){
        itemsavebutton.style.display='block';
        managementsavebutton.style.display='block';
    }
    else {
        itemsavebutton.style.display='none';
        managementsavebutton.style.display='none';
    }
}

function showSurveyRecord(recordNumber,bControl,bNewRecord,bReinspection){ 
    var itemcount = document.surveyform.ItemCount.value;
    var siteID = document.surveyform.SiteID.value;
    var surveyID = document.surveyform.SurveyID.value;
    
    // Item Copy Button
    var itemcopybutton = document.getElementById("itemcopybutton");   
    if (recordNumber<itemcount){
        itemcopybutton.style.display='block';
    }
    else {
        itemcopybutton.style.display='none';
    }
    
    // Item Delete Button
    var itemdeletebutton = document.getElementById("itemdeletebutton");   
    if (recordNumber<itemcount){
        itemdeletebutton.style.display='block';
    }
    else {
        itemdeletebutton.style.display='none';
    }
              
    if (recordNumber<=itemcount){         
	    if (bNewRecord){
	        //ShowSurveySaveButton(true);
	    }
	    else {
	        if (itemcount==recordNumber){
	            //ShowSurveySaveButton(true); 
	        }   
	        else {
	            //ShowSurveySaveButton(false);
	        }
	    }	    
	  	    
	    if (bControl){	       
	        var SaveInfo = SaveSurveyInformation(recordNumber,siteID,false)
	        if (SaveInfo!==''&&SaveInfo!==false){
	            alert(SaveInfo);
	        }
	        else {
	            var qstring = "?SiteID=" + siteID + '&SurveyID='+surveyID+'&RecordNumber=' + recordNumber;
	            if(document.layers && document.layers['datadiv'].load){				
		            document.layers['datadiv'].load('Scripts/GetSurveyItem.asp' + qstring,0);		
	            }
	            else if(window.frames && window.frames.length){				
		            window.frames['dataframe'].window.location.replace('Scripts/GetSurveyItem.asp' + qstring);				
	            }		
	            //alert('Scripts/GetSurveyItem.asp' + qstring)
	        }
	    }
	    else {
	        var qstring = "?SiteID=" + siteID + '&SurveyID='+surveyID+'&RecordNumber=' + recordNumber;
            if(document.layers && document.layers['datadiv'].load){				
	            document.layers['datadiv'].load('Scripts/GetSurveyItem.asp' + qstring,0);		
            }
            else if(window.frames && window.frames.length){				
	            window.frames['dataframe'].window.location.replace('Scripts/GetSurveyItem.asp' + qstring);				
            }		
            //alert('Scripts/GetSurveyItem.asp' + qstring)
	    }
	}
	else {
	    //ShowSurveySaveButton(true);	    
	}
	
	if (bReinspection==false){
	    ShowSurveySaveButton(true);
	}
	
	//$("#itemphotograph").load("Includes/ItemRegisterPhoto.asp?SurveyID=" + surveyID + "&RecordNumber=" + recordNumber);
    var thephoto = document.getElementById("itemphotograph");
    thephoto.src = "Includes/ItemRegisterPhoto.asp?SurveyID=" + surveyID + "&RecordNumber=" + recordNumber;	
}

function ConfirmItemCopy(submitstring,numbercopy){
    if (numbercopy==null||numbercopy==''){   
       var thetext = 'Please enter the Quantity of this record you wish to copy (enter number).'
       var thevalue = 0;
       var thenum = 0;
       
       that=this;
           
       // Check to see if this is MSIE 7.   This isn't a great general purpose
       // detection system but it works well enough just to find MSIE 7.
       var _isIE7=(navigator.userAgent.indexOf('MSIE 7')>0);

       this.wrapupPrompt = function(){      
          if (_isIE7) {    
             _dialogPromptID.style.display='none';        
             _blackoutPromptID.style.display='none'; 
             
             thenum = document.getElementById("iepromptfield").value;
             ConfirmItemCopy(submitstring,thenum);
          }  
       }
          
       if (_isIE7) {      
          if (_dialogPromptID==null) {         
             var tbody = document.getElementsByTagName("body")[0];         
             tnode = document.createElement('div');         
             tnode.id='IEPromptBox';         
             tbody.appendChild(tnode);        
             _dialogPromptID=document.getElementById('IEPromptBox');         
             tnode = document.createElement('div');         
             tnode.id='promptBlackout';        
             tbody.appendChild(tnode);        
             _blackoutPromptID=document.getElementById('promptBlackout');         
             //_blackoutPromptID.style.opacity='.9';
             _blackoutPromptID.style.position='absolute';
             _blackoutPromptID.style.top='0px';
             _blackoutPromptID.style.left='0px';
             //_blackoutPromptID.style.backgroundColor='#555555';
             //_blackoutPromptID.style.filter='alpha(opacity=90)';
             _blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
             _blackoutPromptID.style.display='block';
             _blackoutPromptID.style.zIndex='50';
             // assign the styles to the dialog box
             _dialogPromptID.style.border='2px solid blue';
             _dialogPromptID.style.backgroundColor='#DDDDDD';
             _dialogPromptID.style.position='absolute';
             _dialogPromptID.style.width='330px';
             _dialogPromptID.style.zIndex='100';
          }
         
          var tmp = '<div style="width: 100%; background-color: blue; color: white; font-family: verdana; font-size: 10pt; font-weight: bold; height: 20px">Input Required</div>';
          tmp += '<div style="padding: 10px">'+thetext + '<BR><BR>';      
          tmp += '<input id="iepromptfield" name="iepromptdata" type=text size=46 value="'+thevalue+'">';
          tmp += '<br><br><center>';
          tmp += '<input type="button" onclick="that.wrapupPrompt()" value="&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;">';
          tmp += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
          tmp += '<input type="button" onclick="that.wrapupPrompt()" value="&nbsp;Cancel&nbsp;">';
          tmp += '</div>';
         
          _blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
          _blackoutPromptID.style.width='100%';
          _blackoutPromptID.style.display='block';
         
          _dialogPromptID.innerHTML=tmp;
          _dialogPromptID.style.top=parseInt(document.documentElement.scrollTop+(screen.height/3))+'px';
          _dialogPromptID.style.left=parseInt((document.body.offsetWidth-315)/2)+'px';
          _dialogPromptID.style.display='block';
          
          document.getElementById('iepromptfield').focus();      
        } else {
            // we are not using IE7 so do things "normally"
            thenum = prompt(thetext,thevalue);  
            if (thenum!==''&&thenum!==null&&thenum>0){    
                ConfirmItemCopy(submitstring,thenum); 
            }
        }
    }
    else {   
        //alert(numbercopy);
        if (numbercopy>0){
            location.href=submitstring + '&NumberCopy=' + numbercopy;
        }
    }
}

function controlRemovePanels(bool){
    var fieldarr = new Array("managementdisabled","itemregisterdisabled");
        
    if (bool){            
        document.getElementById("managementdisabled").style.display='block';
        document.getElementById("itemregisterdisabled").style.display='block';
    }
    else {
        document.getElementById("managementdisabled").style.display='none';
        document.getElementById("itemregisterdisabled").style.display='none';
    }   
}

function showHideSamples(thebool){
    var SampleRow3 = document.getElementById("SampleRow3");
    var SampleRow4 = document.getElementById("SampleRow4");
    
    if (thebool){
        SampleRow3.style.display='block';
        SampleRow4.style.display='block';
    }
    else {
        SampleRow3.style.display='none';
        SampleRow4.style.display='none';
    }
}

function textCounter(field,cntfield,maxlimit) {    
    if (field.value.length > maxlimit){
        field.value = field.value.substring(0, maxlimit);
    }
    else {
        //cntfield.value = maxlimit - field.value.length;
        document.getElementById(cntfield).innerHTML = maxlimit - field.value.length;
    }
}

function dataCatchSurveyDetails(RecordNumber,ItemID,RoomID,SurveyItemNumber,SampleNumber,PhotoReference,RoomExtent,ExtentBCLScoreID,MaterialID,ItemDescription,Comments,AsbestosTypeID_1,AsbestosAmountID_1,AsbestosTypeID_2,AsbestosAmountID_2,AsbestosTypeID_3,AsbestosAmountID_3,AsbestosTypeID_4,AsbestosAmountID_4,SampleAnalysedByUserID,NotifiableID,SurfaceTreatmentID,ConditionID,PriorityID,AccessibilityID,LocationID,RecommendationID,ReinspectionInterval,AuditConditionID,RemovalTreatmentDate,Consultants,PassedByUserID,JobTypeID,Contractor,JobDescription,JobNotes,ItemRemoved,CommentsCopy){
	//alert(RecordNumber);
	
	document.surveyform.ItemID.value = ItemID;	
	document.surveyform.RecordNumber1.value = RecordNumber;		
	
	document.surveyform.ChosenRoomID.value = RoomID;	
	document.surveyform.SurveyItemNumber.value = SurveyItemNumber;
	document.surveyform.SampleNumber.value = SampleNumber;
	//document.surveyform.PhotoReference.value = PhotoReference;
	document.surveyform.RoomExtent.value = RoomExtent;
	document.surveyform.ExtentBCLScoreID.value = ExtentBCLScoreID;
	document.surveyform.MaterialID.value = MaterialID;
	
	//alert(MaterialID);
	
	document.surveyform.ItemDescription.value = ItemDescription;
	document.surveyform.Comments.value = Comments;
	
	document.surveyform.AsbestosTypeID_1.value = AsbestosTypeID_1;
	document.surveyform.AsbestosAmountID_1.value = AsbestosAmountID_1;
	document.surveyform.AsbestosTypeID_2.value = AsbestosTypeID_2;
	document.surveyform.AsbestosAmountID_2.value = AsbestosAmountID_2;
	document.surveyform.AsbestosTypeID_3.value = AsbestosTypeID_3;
	document.surveyform.AsbestosAmountID_3.value = AsbestosAmountID_3;
	document.surveyform.AsbestosTypeID_4.value = AsbestosTypeID_4;
	document.surveyform.AsbestosAmountID_4.value = AsbestosAmountID_4;
	
	/* Show/Hide for the 2 other fields */
	if (AsbestosTypeID_3!==''||AsbestosTypeID_4!==''){
	    showHideSamples(true);		        
	}
	else {
	    showHideSamples(false);
	}
	
	/* Rest of Fields */
	document.surveyform.SampleAnalysedByUserID.value = SampleAnalysedByUserID;
	document.surveyform.NotifiableID.value = NotifiableID;
	document.surveyform.SurfaceTreatmentID.value = SurfaceTreatmentID;
	document.surveyform.ConditionID.value = ConditionID;
	//document.surveyform.PriorityID.value = PriorityID;
	document.surveyform.Priority.value = PriorityID;
	document.surveyform.AccessibilityID.value = AccessibilityID;
	document.surveyform.LocationID.value = LocationID;
	document.surveyform.RecommendationID.value = RecommendationID;
	document.surveyform.ReinspectionInterval.value = ReinspectionInterval
	
	document.surveyform.AuditConditionID.value = AuditConditionID;
	document.surveyform.RemovalTreatmentDate.value = RemovalTreatmentDate;
	document.surveyform.Consultants.value = Consultants;
	document.surveyform.PassedByUserID.value = PassedByUserID;
	document.surveyform.JobTypeID.value = JobTypeID;
	document.surveyform.Contractor.value = Contractor;
	document.surveyform.JobDescription.value = JobDescription;
	document.surveyform.JobNotes.value = JobNotes;
	
	document.surveyform.RecordNumber2.value = RecordNumber;
	
	if (ItemRemoved=='True'){
	    controlRemovePanels(true);
	}
	else {
	    controlRemovePanels(false);
	}
	
	// Comments Reminder
	if (ItemID==''){
	    document.getElementById("commentsavereminder").style.display='block';
	}
	
	// Text Counter for Comments
    textCounter(document.surveyform.Comments,'COMM_Char',250);
	
	enableSampleFields(AsbestosTypeID_1);
	controlExtentScore();
	calculatePriority();
	controlLicensable();
	
	manageSurveyItemNumber(SurveyItemNumber);
		
	populateCopyCommentField(CommentsCopy);
}

function SaveSurveyInformation(recordNumber,siteID,newRecord){
    var ftxt = '';
    
    if (document.surveyform.ChosenRoomID.value!==''||document.surveyform.SurveyItemNumber.value!==''||document.surveyform.SampleNumber.value!==''||document.surveyform.RoomExtent.value!==''||document.surveyform.ExtentBCLScoreID.value!==''||document.surveyform.MaterialID.value!==''||document.surveyform.ItemDescription.value!==''||document.surveyform.AsbestosTypeID_1.value!==''||document.surveyform.SampleAnalysedByUserID.value!==''){    
        if (document.surveyform.ChosenRoomID.value==''){ ftxt += '\n- Please select a Room Number.'; } 
        if (document.surveyform.SurveyItemNumber.value==''){ ftxt += '\n- Please enter an Item Number.'; }
        if (document.surveyform.SampleNumber.value==''){ ftxt += '\n- Please enter a Sample Number.'; } 
        if (document.surveyform.RoomExtent.value==''){ ftxt += '\n- Please enter an Extent.'; }
        
        if (document.surveyform.MaterialID.value!==''){        
            if (document.surveyform.ExtentBCLScoreID.value==''){ ftxt += '\n- Please select a Extent Score.'; }
        }
        
        //if (document.surveyform.MaterialID.value==''){ ftxt += '\n- Please select a Product Type.'; }
        if (document.surveyform.ItemDescription.value==''){ ftxt += '\n- Please enter an Item Description.'; }
        if (document.surveyform.AsbestosTypeID_1.value==''){ ftxt += '\n- Please select a Sample 1 Sample Type.'; }  
        if (oversampleanalysedby==false){   
            //if (document.surveyform.SampleAnalysedByUserID.value==''){ ftxt += '\n- Please select a Sample Analysed By User.'; }
        }
        
        if (document.surveyform.AsbestosTypeID_1.value!=='5'){    
            if (document.surveyform.NotifiableID.value==''){ ftxt += '\n- Please select a Licensable.'; }     
            if (document.surveyform.SurfaceTreatmentID.value==''){ ftxt += '\n- Please select a Surface Treatment.'; }   
            if (document.surveyform.ConditionID.value==''){ ftxt += '\n- Please select a Condition.'; }  
            //if (document.surveyform.PriorityID.value==''){ ftxt += '\n- Please select a Priority.'; }
            if (document.surveyform.Priority.value==''){ ftxt += '\n- Please select or enter a Priority.'; }
            if (document.surveyform.AccessibilityID.value==''){ ftxt += '\n- Please select a Accessibility.'; } 
            if (document.surveyform.LocationID.value==''){ ftxt += '\n- Please select a Location.'; }        
            if (document.surveyform.RecommendationID.value==''){ ftxt += '\n- Please select a Recommendation.'; } 
            if (document.surveyform.ReinspectionInterval.value==''){ ftxt += '\n- Please select a Reinspection Interval.'; }
        }       
    }
      
    if (ftxt!==''){
        if (newRecord){
            alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
            return false;
        }
        else {
            return 'One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.';        
        }
    }
    else {
        var qstring = '?frmAutoSubmit=True&frmMode=Item&SiteID=' + siteID + '&RecordNumber=' + recordNumber;

        //var fieldarr = new Array("ItemID","SurveyID","ChosenRoomID","SurveyItemNumber","SampleNumber","PhotoReference","RoomExtent","ExtentBCLScoreID","MaterialID","ItemDescription","Comments","AsbestosTypeID_1","AsbestosAmountID_1","AsbestosTypeID_2","AsbestosAmountID_2","AsbestosTypeID_3","AsbestosAmountID_3","AsbestosTypeID_4","AsbestosAmountID_4","SampleAnalysedByUserID","NotifiableID","SurfaceTreatmentID","ConditionID","PriorityID","AccessibilityID","LocationID","RecommendationID","ReinspectionInterval","AuditConditionID","RemovalTreatmentDate","Consultants","PassedByUserID","JobTypeID","Contractor","JobDescription","JobNotes");
        var fieldarr = new Array("ItemID","SurveyID","ChosenRoomID","SurveyItemNumber","SampleNumber","RoomExtent","ExtentBCLScoreID","MaterialID","ItemDescription","Comments","AsbestosTypeID_1","AsbestosAmountID_1","AsbestosTypeID_2","AsbestosAmountID_2","AsbestosTypeID_3","AsbestosAmountID_3","AsbestosTypeID_4","AsbestosAmountID_4","SampleAnalysedByUserID","NotifiableID","SurfaceTreatmentID","ConditionID","Priority","AccessibilityID","LocationID","RecommendationID","ReinspectionInterval","AuditConditionID","RemovalTreatmentDate","Consultants","PassedByUserID","JobTypeID","Contractor","JobDescription","JobNotes");
        for (var i=0;i<fieldarr.length;i++){
            qstring += '&' + fieldarr[i] + '=' + escape(eval('document.surveyform.'+fieldarr[i]+'.value'));
        }
        
        /*
        if(document.layers && document.layers['updatedatadiv'].load){				
	        document.layers['updatedatadiv'].load('system_survey_form.asp' + qstring,0);		
        }
        else if(window.frames && window.frames.length){				
	        window.frames['updatedataframe'].window.location.replace('system_survey_form.asp' + qstring);				
        }
        */
        
        /* Check to see if Duplicate Room */  
        if (window.XMLHttpRequest) {
            http = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            http = new ActiveXObject("Microsoft.XMLHTTP");
        }	
        
        var itemurl = 'system_survey_form.asp' + qstring;
                
                //alert(itemurl);
                
        http.open("GET", itemurl, false);
        http.send();	
        
        //alert('system_survey_form.asp' + qstring);
        //alert(newRecord);
        if (newRecord==true){
            //alert('** Item Saved **');
            location.href='system_survey_form.asp?SiteID='+ siteID +'&SurveyID='+ document.surveyform.SurveyID.value +'&GotoRecord='+ (recordNumber) +'#tabs-itemregister'            
        }
        else {
            return false;   
        }
    }
}

function ConfirmItemRegisterRemove(submitstring){
    if (confirm('** WARNING **\n\nAre you sure you want to remove this item?\n\nThis process cannot be undone!\n\nAre you sure you wish to proceed?')){
        location.href=submitstring;
    }
}

/* Enable or Disable Sample Fields */
function enableSampleFields(fieldval){   
    //var fieldArr = new Array("NotifiableID|3","SurfaceTreatmentID|2","ConditionID|5","PriorityID|4","AccessibilityID|5","LocationID|5","RecommendationID|6","ReinspectionInterval|1");
    var fieldArr = new Array("NotifiableID|3", "SurfaceTreatmentID|2", "ConditionID|5", "Priority|Not applicable", "AccessibilityID|5", "LocationID|5", "RecommendationID|6", "ReinspectionInterval|1", "ExtentBCLScoreID|5");

    for (var i=0;i<fieldArr.length;i++){
        var innerArr = fieldArr[i].split("|");
        if (fieldval!=='5'){
            // Enable
            eval('document.surveyform.' + innerArr[0] + '.disabled=false');            
        }
        else {
            // Disable
            eval('document.surveyform.' + innerArr[0] + '.disabled=true');
            if (innerArr[1]=='Not applicable'){
                eval('document.surveyform.' + innerArr[0] + '.value="Not applicable"');                
            }
            else {
                eval('document.surveyform.' + innerArr[0] + '.value=' + innerArr[1]);
            }            
        }
    }
}

/* Change Photograph Warning */
function checkchangephoto(submitstring){
    if (confirm('** WARNING **\n\nYou must save any changes before proceeding to change this site photograph.\n\nHave you saved all of your changes?')){
        location.href=submitstring;
    }
}

/* Reinspection Form */
function checkreinspectionform(){
    var ftxt = '';
    
    /*
    if (isDate(document.reinspectionform.DateofWork.value)==false){
        ftxt += '\n- Please enter a Date of Work.';
    }
    */
    if (document.reinspectionform.DateofWork.value==''){
        ftxt += '\n- Please enter a Date of Work.';
    }
    
    if (document.reinspectionform.SurveyNumber.value==''||document.reinspectionform.SurveyNumber.value=='S'){
        ftxt += '\n- Please enter a New Survey Number.';
    }
    
    if (document.reinspectionform.SiteContact.value==''){
        ftxt += '\n- Please enter a Site Contact.';
    }
    
    if (document.reinspectionform.TechnicalManagerID.value==''){
        ftxt += '\n- Please select a Technical Manager.';
    }
    
    if (isDate(document.reinspectionform.ReinspectionDate.value)==false){
        ftxt += '\n- Please enter a Re-Inspection Date.';
    }
    
    if (document.reinspectionform.OrderPlacedBy.value==''){
        ftxt += '\n- Please enter an Order Placed By Name.';
    }    
    
    if (document.reinspectionform.OfficeID.value==''){
        ftxt += '\n- Please select an Office.';
    }
    
    if (document.reinspectionform.Surveyor1.value==''){
        ftxt += '\n- Please select a Surveyor 1 (Lead)';
    }
    
    if (ftxt!==''){
		alert('One or more errors were found while submitting this form. The errors found are displayed below.\n' + ftxt + '\n\nPlease correct the above errors and try again.');
		return false;
	}
	else {
	    return true;
	}
}

/* Item Delete */
function ConfirmItemDelete(submitstring){
    if (confirm('** WARNING **\n\nAre you sure you want to delete this item?\n\nRemoving this item will permanently remove it from the database.\n\nAre you sure you want to proceed?')){
        location.href=submitstring;
    }
}


/* ------ PHASE 2 NEW FEATURES ------ */
/* Survey Copy */
function ConfirmSurveyCopy(submitstring,numbercopy){   
   if (numbercopy==null||numbercopy==''){   
       var thetext = 'Please enter the New Survey Number for the duplicated survey.'
       var thevalue = 'S';
       var thenum = 0;
       
       that=this;
           
       // Check to see if this is MSIE 7.   This isn't a great general purpose
       // detection system but it works well enough just to find MSIE 7.
       var _isIE7=(navigator.userAgent.indexOf('MSIE 7')>0);

       this.wrapupPrompt = function(){      
          if (_isIE7) {    
             _dialogPromptID.style.display='none';        
             _blackoutPromptID.style.display='none'; 
             
             thenum = document.getElementById("iepromptfield").value;
             ConfirmSurveyCopy(submitstring,thenum);
          }  
       }
          
       if (_isIE7) {      
          if (_dialogPromptID==null) {         
             var tbody = document.getElementsByTagName("body")[0];         
             tnode = document.createElement('div');         
             tnode.id='IEPromptBox';         
             tbody.appendChild(tnode);        
             _dialogPromptID=document.getElementById('IEPromptBox');         
             tnode = document.createElement('div');         
             tnode.id='promptBlackout';        
             tbody.appendChild(tnode);        
             _blackoutPromptID=document.getElementById('promptBlackout');         
             //_blackoutPromptID.style.opacity='.9';
             _blackoutPromptID.style.position='absolute';
             _blackoutPromptID.style.top='0px';
             _blackoutPromptID.style.left='0px';
             //_blackoutPromptID.style.backgroundColor='#555555';
             //_blackoutPromptID.style.filter='alpha(opacity=90)';
             _blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
             _blackoutPromptID.style.display='block';
             _blackoutPromptID.style.zIndex='50';
             // assign the styles to the dialog box
             _dialogPromptID.style.border='2px solid blue';
             _dialogPromptID.style.backgroundColor='#DDDDDD';
             _dialogPromptID.style.position='absolute';
             _dialogPromptID.style.width='330px';
             _dialogPromptID.style.zIndex='100';
          }
         
          var tmp = '<div style="width: 100%; background-color: blue; color: white; font-family: verdana; font-size: 10pt; font-weight: bold; height: 20px">Input Required</div>';
          tmp += '<div style="padding: 10px">'+thetext + '<BR><BR>';      
          tmp += '<input id="iepromptfield" name="iepromptdata" type=text size=46 value="'+thevalue+'">';
          tmp += '<br><br><center>';
          tmp += '<input type="button" onclick="that.wrapupPrompt()" value="&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;">';
          tmp += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
          tmp += '<input type="button" onclick="that.wrapupPrompt()" value="&nbsp;Cancel&nbsp;">';
          tmp += '</div>';
         
          _blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
          _blackoutPromptID.style.width='100%';
          _blackoutPromptID.style.display='block';
         
          _dialogPromptID.innerHTML=tmp;
          _dialogPromptID.style.top=parseInt(document.documentElement.scrollTop+(screen.height/3))+'px';
          _dialogPromptID.style.left=parseInt((document.body.offsetWidth-315)/2)+'px';
          _dialogPromptID.style.display='block';
          
          document.getElementById('iepromptfield').focus();      
        } else {
            // we are not using IE7 so do things "normally"
            thenum = prompt(thetext,thevalue);  
            if (thenum!==''&&thenum!==null&&thenum!=='S'){    
                ConfirmSurveyCopy(submitstring,thenum); 
            }
        }
    }
    else {   
        //alert(numbercopy);
        if (numbercopy!==''&&numbercopy!=='S'){
            location.href=submitstring + '&NewSurveyNumber=' + numbercopy;
        }
    }      
}

/* Goto Item */
function ConfirmItemGoto(submitstring,numbercopy){   
   if (numbercopy==null||numbercopy==''){   
       var thetext = 'Please enter the record number you would like go to.'
       var thevalue = 0;
       var thenum = 0;
       
       that=this;
           
       // Check to see if this is MSIE 7.   This isn't a great general purpose
       // detection system but it works well enough just to find MSIE 7.
       var _isIE7=(navigator.userAgent.indexOf('MSIE 7')>0);

       this.wrapupPrompt = function(){      
          if (_isIE7) {    
             _dialogPromptID.style.display='none';        
             _blackoutPromptID.style.display='none'; 
             
             thenum = document.getElementById("iepromptfield").value;
             ConfirmItemGoto(submitstring,thenum);
          }  
       }
          
       if (_isIE7) {      
          if (_dialogPromptID==null) {         
             var tbody = document.getElementsByTagName("body")[0];         
             tnode = document.createElement('div');         
             tnode.id='IEPromptBox';         
             tbody.appendChild(tnode);        
             _dialogPromptID=document.getElementById('IEPromptBox');         
             tnode = document.createElement('div');         
             tnode.id='promptBlackout';        
             tbody.appendChild(tnode);        
             _blackoutPromptID=document.getElementById('promptBlackout');         
             //_blackoutPromptID.style.opacity='.9';
             _blackoutPromptID.style.position='absolute';
             _blackoutPromptID.style.top='0px';
             _blackoutPromptID.style.left='0px';
             //_blackoutPromptID.style.backgroundColor='#555555';
             //_blackoutPromptID.style.filter='alpha(opacity=90)';
             _blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
             _blackoutPromptID.style.display='block';
             _blackoutPromptID.style.zIndex='50';
             // assign the styles to the dialog box
             _dialogPromptID.style.border='2px solid blue';
             _dialogPromptID.style.backgroundColor='#DDDDDD';
             _dialogPromptID.style.position='absolute';
             _dialogPromptID.style.width='330px';
             _dialogPromptID.style.zIndex='100';
          }
         
          var tmp = '<div style="width: 100%; background-color: blue; color: white; font-family: verdana; font-size: 10pt; font-weight: bold; height: 20px">Input Required</div>';
          tmp += '<div style="padding: 10px">'+thetext + '<BR><BR>';      
          tmp += '<input id="iepromptfield" name="iepromptdata" type=text size=46 value="'+thevalue+'">';
          tmp += '<br><br><center>';
          tmp += '<input type="button" onclick="that.wrapupPrompt()" value="&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;">';
          tmp += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
          tmp += '<input type="button" onclick="that.wrapupPrompt()" value="&nbsp;Cancel&nbsp;">';
          tmp += '</div>';
         
          _blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
          _blackoutPromptID.style.width='100%';
          _blackoutPromptID.style.display='block';
         
          _dialogPromptID.innerHTML=tmp;
          _dialogPromptID.style.top=parseInt(document.documentElement.scrollTop+(screen.height/3))+'px';
          _dialogPromptID.style.left=parseInt((document.body.offsetWidth-315)/2)+'px';
          _dialogPromptID.style.display='block';
          
          document.getElementById('iepromptfield').focus();      
        } else {
            // we are not using IE7 so do things "normally"
            thenum = prompt(thetext,thevalue);  
            if (thenum!==''&&thenum!==null&&thenum>0){    
                ConfirmItemGoto(submitstring,thenum); 
            }
        }
    }
    else {   
        //alert(numbercopy);
        if (numbercopy!==''&&numbercopy>0){
            //location.href=submitstring + '&GotoCopyRecord=' + numbercopy;
            showSurveyRecord(numbercopy,true,false,false);
        }
    }      
}

/* Goto Room */
function ConfirmRoomGoto(submitstring,numbercopy){   
   if (numbercopy==null||numbercopy==''){   
       var thetext = 'Please enter the room number you would like go to.'
       var thevalue = 0;
       var thenum = 0;
       
       that=this;
           
       // Check to see if this is MSIE 7.   This isn't a great general purpose
       // detection system but it works well enough just to find MSIE 7.
       var _isIE7=(navigator.userAgent.indexOf('MSIE 7')>0);

       this.wrapupPrompt = function(){      
          if (_isIE7) {    
             _dialogPromptID.style.display='none';        
             _blackoutPromptID.style.display='none'; 
             
             thenum = document.getElementById("iepromptfield").value;
             ConfirmRoomGoto(submitstring,thenum);
          }  
       }
          
       if (_isIE7) {      
          if (_dialogPromptID==null) {         
             var tbody = document.getElementsByTagName("body")[0];         
             tnode = document.createElement('div');         
             tnode.id='IEPromptBox';         
             tbody.appendChild(tnode);        
             _dialogPromptID=document.getElementById('IEPromptBox');         
             tnode = document.createElement('div');         
             tnode.id='promptBlackout';        
             tbody.appendChild(tnode);        
             _blackoutPromptID=document.getElementById('promptBlackout');         
             //_blackoutPromptID.style.opacity='.9';
             _blackoutPromptID.style.position='absolute';
             _blackoutPromptID.style.top='0px';
             _blackoutPromptID.style.left='0px';
             //_blackoutPromptID.style.backgroundColor='#555555';
             //_blackoutPromptID.style.filter='alpha(opacity=90)';
             _blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
             _blackoutPromptID.style.display='block';
             _blackoutPromptID.style.zIndex='50';
             // assign the styles to the dialog box
             _dialogPromptID.style.border='2px solid blue';
             _dialogPromptID.style.backgroundColor='#DDDDDD';
             _dialogPromptID.style.position='absolute';
             _dialogPromptID.style.width='330px';
             _dialogPromptID.style.zIndex='100';
          }
         
          var tmp = '<div style="width: 100%; background-color: blue; color: white; font-family: verdana; font-size: 10pt; font-weight: bold; height: 20px">Input Required</div>';
          tmp += '<div style="padding: 10px">'+thetext + '<BR><BR>';      
          tmp += '<input id="iepromptfield" name="iepromptdata" type="text" size="46" value="">';
          tmp += '<br><br><center>';
          tmp += '<input type="button" onclick="that.wrapupPrompt()" value="&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;">';
          tmp += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
          tmp += '<input type="button" onclick="that.wrapupPrompt()" value="&nbsp;Cancel&nbsp;">';
          tmp += '</div>';
         
          _blackoutPromptID.style.height=(document.body.offsetHeight<screen.height) ? screen.height+'px' : document.body.offsetHeight+20+'px'; 
          _blackoutPromptID.style.width='100%';
          _blackoutPromptID.style.display='block';
         
          _dialogPromptID.innerHTML=tmp;
          _dialogPromptID.style.top=parseInt(document.documentElement.scrollTop+(screen.height/3))+'px';
          _dialogPromptID.style.left=parseInt((document.body.offsetWidth-315)/2)+'px';
          _dialogPromptID.style.display='block';
          
          document.getElementById('iepromptfield').focus();      
        } else {
            // we are not using IE7 so do things "normally"
            thenum = prompt(thetext,'');  
            if (thenum!==''&&thenum!==null){    
                ConfirmRoomGoto(submitstring,thenum); 
            }
        }
    }
    else {           
        if (numbercopy!==''){   
            /* Check to see if the room exists, and if so, get the Position! */
            if (window.XMLHttpRequest) {
                http = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
                http = new ActiveXObject("Microsoft.XMLHTTP");
            }
            
            var url = 'Scripts/RoomFinder.asp?SurveyID=' + document.surveyform.SurveyID.value + '&RoomNumber=' + numbercopy;                
            
            //alert(url);
            
            http.open("GET", url, false);
            http.send();
            
            var xmlObj = http.responseXML;
            var xmlPosition = xmlObj.getElementsByTagName('position').item(0).firstChild.data;
            
            if (xmlPosition==0){
                alert('Sorry, but the Room Number entered was not found. Please try again.');
            }
            else {
                //alert(xmlPosition);
                showSiteRecord(parseInt(xmlPosition),true,false);
            }
        }
    }      
}

/* Control Extent Score */
function controlExtentScore(){
    if (document.surveyform.MaterialID.value==''){
        document.surveyform.ExtentBCLScoreID.disabled=true;
    }
    else {
        document.surveyform.ExtentBCLScoreID.disabled=false;
    }
}

/* Control Copy of Comments */
function populateCopyCommentField(thestring){  
    //001---Present within floor void to all rooms with exception to room 05, approximately 350 sqm in total.
  
    var thearray = thestring.split("|");
    var dropDown = document.surveyform.CommentsSelector;
    
    //alert(thearray.length);
    
    if (thearray.length>0){
        if (dropDown)  {		
		    dropDown.length = 0;
		    var innerrecord = '';
		    
		    dropDown[0] = new Option("Select Copy Item >>","");
		    		    
		    for (var i=0;i<thearray.length;i++){
		        innerrecord = thearray[i];
		        //alert(thearray[i]);
		        if (innerrecord!==''){		                 		        
		            var innerarray = innerrecord.split("---");		  
		             
		            if (innerarray.length>0){     
		                dropDown[(i+1)] = new Option("Copy from Item Number: " + innerarray[0],innerarray[1]);		        
		            }
		        }
		    }
		}
	}
}

function controlCommentsCopy(thecomment){
    if (thecomment!==''&&thecomment!==null){
        document.surveyform.Comments.value=thecomment;
    }
}

/* Room Delete */
function ConfirmRoomDelete(submitstring){
    //alert(submitstring);
    if (confirm('** WARNING !! **\n\nAre you sure you want to delete this room?\n\nDeleting this room will PERMANENTLY delete all Items (and their photos) within the selected room.\n\nAre you sure you want to delete this room?')){
        location.href=submitstring;
    }
}

/* Remove Signoff */
function confirmRemoveSignoff(submitstring){
    if (confirm('** WARNING !! **\n\nAre you sure you want to remove the sign-off of this report?\n\nDoing so will prevent the client from viewing or downloading this report in part or its entirety.\n\nAre you sure you want to proceed?')){
        location.href=submitstring;
    }
}

/* Auto-Priority Score Input */
function calculatePriority(){    
    var qstring = ""
    var thefields = new Array("MaterialID","ConditionID","SurfaceTreatmentID","LocationID","AccessibilityID","ExtentBCLScoreID","AsbestosTypeID_1","AsbestosTypeID_2","AsbestosTypeID_3","AsbestosTypeID_4")
    
    for (var i=0;i<thefields.length;i++){            
        var thevalue = eval('document.surveyform.'+thefields[i]+'.value'); 
        //alert(thevalue);
        thevalue = thevalue.replace("\n","<br />");
        if (qstring!==''){
            qstring += '&';
        }
        qstring += thefields[i] + '=' + thevalue;
    }
        
	if(document.layers && document.layers['datadiv'].load){				
		document.layers['datadiv'].load('Scripts/GetPriorityScore.asp?' + qstring,0);		
	}
	else if(window.frames && window.frames.length){				
		window.frames['dataframe'].window.location.replace('Scripts/GetPriorityScore.asp?' + qstring);				
	}	
	
	//alert('Scripts/GetPriorityScore.asp?' + qstring);
}

function controlLicensable(){
    var matval = document.surveyform.MaterialID.value;
    var matarr = matval.split("|");
    
    if (matarr[1]=='True'){
        document.surveyform.NotifiableID.selectedIndex = 3;
    }
}

function in_array( what, where ){
	var a=false;
	for(var i=0;i<where.length;i++){
	  if(what == where[i]){
	    a=true;
        break;
	  }
	}
	return a;
}

function dataCatchPriority(riskscore){   	
    // RISK SCORE CALCULATED HERE
    
    // Auto Values - References later by Position!
    var ValueList = new Array("High","Medium","Low","Very Low","Not applicable");
    var Priority = document.surveyform.Priority;
    
    //if (in_array(Priority.value,ValueList)==false){
    if (riskscore==0){
        Priority.value = ValueList[4];
    }
    else if (riskscore>=1&&riskscore<=6){
        Priority.value = ValueList[3];
    }
    else if (riskscore>=7&&riskscore<=10){
        Priority.value = ValueList[2];
    }
    else if (riskscore>=11&&riskscore<=15){
        Priority.value = ValueList[1];
    }    
    else if (riskscore>=16){
        Priority.value = ValueList[0];
    }
}

// Launch Intrustion Photograph Manager
function launchIntrustionPhotographManager(surveyId) {
    var w = 800;
    var h = 600;

    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2);
    var targetWin = window.open('system_survey_photomanager.asp?SurveyID=' + surveyId, 'PhotoManager', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
}

/* Disclaimers */
function checkDisclaimerDelete(submitstring) {
    if (confirm('Are you sure you want to delete this disclaimer?')) {
        location.href = submitstring;
    }
}

/* Removal and Reinstation of Sites */
function confirmReinstateSite(submitstring) {
    if (confirm('Are you sure you want to reinstate this site and remove the removed marker?')) {
        location.href = submitstring;
    }
}

function confirmRemoveSite(submitstring) {
    if (confirm('Are you sure you want to remove this site?')) {
        location.href = submitstring;
    }
}
