var regExpNumber = new RegExp("^[0-9]\\d*$");
var tempNumber;

//Macromedia findObj method - finds any object reference from its name or id
function findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function hideQuestionRow(rowID)
{
  document.getElementById(rowID + "_row").className = "hiddenrow";
	//document.getElementById(rowID + "_row").style.visibility='hidden'; 
	//document.getElementById(rowID + "_row").style.position='absolute';
}
function showQuestionRow(rowID)
{
  document.getElementById(rowID + "_row").className = "row";
	//document.getElementById(rowID + "_row").style.visibility='visible'; 
	//document.getElementById(rowID + "_row").style.position='relative';
}
function showQuestionRowIfNumber(value, rowID)
{
  if(parseInt(value,10)>0)
  {
    document.getElementById(rowID + "_row").className = "row";
	  //document.getElementById(rowID + "_row").style.visibility='visible'; 
	  //document.getElementById(rowID + "_row").style.position='relative';
	}
	else
	{
	  hideRow(rowID + "_row")
	}
}
function showQuestionRowIfChecked(checkBoxID, rowID)
{
  if(document.getElementById(checkBoxID).checked)
  {
    document.getElementById(rowID + "_row").className = "row";
	  //document.getElementById(rowID + "_row").style.visibility='visible'; 
	  //document.getElementById(rowID + "_row").style.position='relative';
	}
	else
	{
	  hideRow(rowID + "_row")
	}
}
//shows a row if one of a group of checkboxes is checked
function showQuestionRowIfOneOfGroupChecked(checkBoxGroupID, rowID)
{
	var count = 1;
	var loop = true;
	var checked = false;
	
	while(loop)
	{
		//check if control existes
		if(document.getElementById(checkBoxGroupID + "_" + count) != null)
		{
			if(document.getElementById(checkBoxGroupID + "_" + count).checked)
			{
				checked = true;
			}
		
			//increment count
			count = count + 1
		}
		else
		{
			//control not found - cancel loop
			loop = false
		}
	}

  if(checked)
  {
	  document.getElementById(rowID + "_row").style.visibility='visible'; 
	  document.getElementById(rowID + "_row").style.position='relative';
	}
	else
	{
	  hideRow(rowID + "_row")
	}
}
function showQuestionRowIfOneOfControlsChecked(controls, rowID)
{
	var arrControls
	var checked = false;
  
  arrControls = controls.split(",")
  
  for(var i=0; i<arrControls.length; i++)
	{
		if(document.getElementById(arrControls[i]).checked)
		{
			checked = true
		}
	}
	
	if(checked)
	{
		showQuestionRow(rowID)
	}
	else
	{
		hideQuestionRow(rowID)
	}
}
//takes an array of controls with true selections and a target control to show
//if one of the controls has a true selection it shows the target control
//number of controls and selections must match
function showQuestionRowifOneOfGroupValid(controls, selected, rowID)
{
	var arrControls
	var arrSelected
	var valid = false;
	var object
  
  arrControls = controls.split(",")
  arrSelected = selected.split(",")
  
  for(var i=0; i<arrControls.length; i++)
	{
		object = findObj(arrControls[i])
		
		for(var j=0; j<object.length; j++)
		{
			//object value must match condition and must be checked
			if(object[j].value == arrSelected[i] && object[j].checked)
			{
				valid = true
			}
		}
	}
	
	if(valid)
	{
		showQuestionRow(rowID)
	}
	else
	{
		hideQuestionRow(rowID)
	}
}
//shows or hides controls depending on the dropdown option selected
//options array is matached to controls array
function showQuestionRowFromOption(value, options, controls)
{
  var arrOptions
  var arrControls
  
  arrOptions = options.split(",")
  arrControls = controls.split(",")

  //hide all controls first before testing what to display
  for(var i=0; i<arrControls.length; i++)
	{
	  if(arrControls[i] != "")
	  {
      hideQuestionRow(arrControls[i])
    }
  }

  for(var i=0; i<arrOptions.length; i++)
	{
			if(arrOptions[i] == value)
			{
			  if(arrControls[i] != "")
	      {
			    showQuestionRow(arrControls[i])
			  }
			}
	}
}

function hideRow(rowID)
{
  document.getElementById(rowID).className = "hiddenrow"; 
  //document.getElementById(rowID).style.setAttribute('visibility','hidden'); 
  //document.getElementById(rowID).style.position='absolute';
}
function showRow(rowID)
{
  document.getElementById(rowID).className = "row";
	//document.getElementById(rowID).style.visibility='visible'; 
	//document.getElementById(rowID).style.position='relative';
}
function hideControl(controlId)
{
	document.getElementById(controlId).style.visibility='hidden';
	document.getElementById(controlId).style.position='absolute'; 
}
function showControl(controlId)
{
	document.getElementById(controlId).style.visibility='visible';
	document.getElementById(controlId).style.position='relative';
}
function hideGridControl(controlId)
{
	document.getElementById(controlId).style.visibility='hidden';
	//document.getElementById(controlId).style.position='absolute'; 
}
function showGridControl(controlId)
{
	document.getElementById(controlId).style.visibility='visible';
	//document.getElementById(controlId).style.position='relative'; 
}
function showHideRowCheckbox(IDs, rowID)
{
	var checked = false;
		
	for(var i=0; i<IDs.length; i++)
	{
		if(document.getElementById(IDs[i]).checked)
		{
			checked = true;
		}
	}
	
	if(checked)
	{
		document.getElementById(rowID).style.visibility='visible'; 
		document.getElementById(rowID).style.position='relative';
	}
	else
	{
		document.getElementById(rowID).style.visibility='hidden'; 
		document.getElementById(rowID).style.position='absolute';
	}
}
function doAddition(elementID, IDs)
{	
	if(!isNaN(parseInt(tempNumber)))
	{
		for(var i=0; i<IDs.length; i++)
		{
			document.getElementById(IDs[i]).value = parseInt(document.getElementById(IDs[i]).value) - parseInt(tempNumber);
		}	
	}

	if(regExpNumber.test(document.getElementById(elementID).value))
	{
		for(var i=0; i<IDs.length; i++)
		{
			document.getElementById(IDs[i]).value = parseInt(document.getElementById(IDs[i]).value) + parseInt(document.getElementById(elementID).value);
		}
	}
}
function makeTotal(elementID, IDs)
{
	var total = 0;
	
	for(var i=0; i<IDs.length; i++)
	{
		total = parseInt(total) + parseInt(document.getElementById(IDs[i]).value);
	}
	
	document.getElementById(elementID).value = total;
}

//must have either 'postcode' or 'street and town'
function validateGazetteer()
{
  passed = true

  //reset validation
  document.getElementById("gazetteer-3").className = document.getElementById("gazetteer-3").className.replace("error", "")
  document.getElementById("gazetteer-4").className = document.getElementById("gazetteer-4").className.replace("error", "")
  document.getElementById("gazetteer-5").className = document.getElementById("gazetteer-5").className.replace("error", "")

  //postcode
  if(document.getElementById("gazetteer-3").value == "")
  {
    //street and town
    if(document.getElementById("gazetteer-4").value == "" || document.getElementById("gazetteer-5").value == "")
    {
      document.getElementById("gazetteer-3").className = document.getElementById("gazetteer-3").className + "error"
      document.getElementById("gazetteer-4").className = document.getElementById("gazetteer-4").className + "error"
      document.getElementById("gazetteer-5").className = document.getElementById("gazetteer-5").className + "error"
      
      passed = false
    }
  }
  
  if(!passed)
  {
    alert("You must fill in either Postcode, or a Street and Town combination")
  }
  
  return passed
}

function setCardFields()
{
  if(document.getElementById("cardtype").value == "debit")
  {
    document.getElementById("securitynumber").disabled = true
    document.getElementById("securitynumber").mandatory = ""
    document.getElementById("securitynumberlabel").className = "questionlabel"
    document.getElementById("secnumberstar").style.visibility = "hidden";
  }
  else
  {
    document.getElementById("securitynumber").disabled = false
    document.getElementById("securitynumber").mandatory = "true;number"
    document.getElementById("securitynumberlabel").className = "questionlabel"
    document.getElementById("secnumberstar").style.visibility = "visible";
  }
}

function validatePropertyCheckboxes()
{
  var valid = false;
  
  var f = document.getElementById("Form1");
  
  //for each element in the form f
	for (i = 0; i < f.length; i++)
	{
	  if(f.elements[i].checked)
	  {
	    valid = true
	  }
	}
	
	if(!valid)
	{
	  alert("You must choose at least one of the properties")
	}
	
	return valid;
}

function disableGazetteerNext()
{
  var foundResults;
  var nextButton;
  
  foundResults = window.document.Form1.foundResults.value;
  nextButton = document.getElementById("goNext");
  
  if (foundResults == 'false')
  {    
    nextButton.disabled = 'false';
  }
}

//tests all radio buttons on a form to ensure that one is checked
function validateRadioControls(formName)
{
  var f = findObj(formName);
  var checked = false;
  
  //for each element in the form f
	for (var i = 0; i < f.length; i++)
	{
	  if((f.elements[i].getAttribute('type') == "radio"))
		{
		  if(f.elements[i].checked == true)
		  {
        checked = true;		  
		  }
		}
	}
	
	if(checked == false)
	{
	  alert("You must choose one option")
	}
	
	return checked
}

//dynamically adds a row to a table
function addTableRow(tableId, gridId, rowId, columnId)
{
  var table = document.getElementById(tableId);
  var rowIdArray = rowId.split("copy");
  var rowId = rowIdArray[0].replace("row","")  
  var copyId = -1;
  
  if(rowIdArray[1] != null)
  {
    copyId = parseInt(rowIdArray[1],10);
  }
  
  var row = table.rows[rowId-1]  
  var newRow
  var rowLength = row.cells.length-1;
  var cell;
  var newCell
  var innerHtml
  
  var tableRowId = parseInt(rowId,10) + (copyId+1)
  
  //only add the row if it does not already exist
  if(tableRowId > table.rows.length-1 )
  {
    newRow = table.insertRow(tableRowId);
    
    for(var i=rowLength; i>-1; i--)
    {
      cell = row.cells[i] 
      
      newCell = newRow.insertCell(cell)
      
      innerHtml = cell.innerHTML

      //replace any mandatory markers in the new row
      replaceMandatoryString = 'mandatory="true"'   
      replaceNumberString = 'mandatory="number"'
      replaceDecimalString = 'mandatory="decimal"'
      innerHtml = innerHtml.replace(replaceMandatoryString, '').replace(replaceNumberString, '').replace(replaceDecimalString, '').replace('*', '')
      
      htmlArray = innerHtml.split("row" + rowId)
        
      innerHtml = "";
      
      for(var j=0; j<htmlArray.length; j++)
      {
        if(j == htmlArray.length-1)
        {
          innerHtml = innerHtml + htmlArray[j]
        }
        else
        {
          innerHtml = innerHtml + htmlArray[j].replace("copy" + copyId, "") + "row" + rowId + "copy" + (copyId+1)
        }
      }
      newCell.innerHTML = innerHtml
      //alert(newCell.outerHTML)
      //find each new control and reset its value = ""
      rowObject = findObj(gridId + "_row" + rowId + "copy" + (copyId+1) + "_column" + (i+1))
      //alert(gridId + "_row" + rowId + "copy" + (copyId+1) + "_column" + (i+1))
      //alert(rowObject)
			if(rowObject != null)//ignore hidden controls
			{
				//must be a collection
				if(rowObject.value == null)
				{
					for(k=0;k<rowObject.length;k++)
					{
						rowObject[k].checked = false				
					}
				}
				else
				{
				  //alert(rowObject.value)
					rowObject.value=""
				}
			}
    }
  }
}

function duplicateRow(rowName, copies)
{
  var table = findObj("questions")
  var row = findObj(rowName + "_row")
  var rowId
  var rowLength = row.cells.length-1;
  var cell;
  newCell
  var innerHtml
  var rowCopyExists

  for(var i=0; i<table.rows.length; i++)
  {
    if(table.rows[i].id == rowName + "_row")
    {      
      rowId = i + 1
    }
  }
  
  for(var j=0; j<=copies-1; j++)
  {
    rowCopyExists = true
    //alert(table.rows[rowId+j].id)
    //check that the row does not already exist
    if(table.rows[rowId+j] == null)
    {
      rowCopyExists = false
      //alert("1 " + table.rows[rowId+j])
    }
    else if(table.rows[rowId+j].id.split("copy")[0] != row.id)
    {
      rowCopyExists = false
      //alert("2 " + table.rows[rowId+j].id.split("copy")[0] + " " + row.id)
    }
    //row exists but has been hidden
    //show row and flag as no longer deleted
    else
    {
      showRow(table.rows[rowId+j].id)
      //alert("3 " + table.rows[rowId+j].id)
      //table.rows[rowId+j].attributes["deleted"].value = ""
    }
    
    if(!rowCopyExists)
    {
      newRow = table.insertRow(rowId + j); 
      
      newRow.setAttribute("id", row.attributes["id"].value + "copy" + j)
      
      //newRow.setAttribute("deleted", "")

      for(var k=rowLength; k>-1; k--)
      {          
        cell = row.cells[k]    
        var newCell = newRow.insertCell(cell)
        
        innerHtml = cell.innerHTML
        
        //set the new row name
        innerHtml = innerHtml.replace(rowName + "_row", rowName + "_row" + "copy" + j)
        
        var htmlArray      
      
        htmlArray = innerHtml.split(rowName.replace("-","_"))
        
        innerHtml = "";
        
        for(l=0; l<htmlArray.length; l++)
        {
          if(l == htmlArray.length-1)
          {
            innerHtml = innerHtml + htmlArray[l]
          }
          else
          {
            innerHtml = innerHtml + htmlArray[l] + rowName.replace("-","_") + "copy" + j
          }
        }
        
        newCell.innerHTML = innerHtml
        
        //alert(cell.attributes["valign"].value)
        //newCell.attributes["class"].value = cell.attributes["class"].value
      }
    }
  }
  
  deleteItems = findObj('deleteitems') 
  
  //loop through all rows and mark redundant rows as deleted
  for(i=table.rows.length-1; i>-1; i--)
  {
    if(table.rows[i].id.indexOf(rowName + "_rowcopy") != -1)
    {
    //alert(table.rows[i].id.split(rowName + "_rowcopy")[1])
    //alert(copies)  
      if(table.rows[i].id.split(rowName + "_rowcopy")[1] >= copies)
      {
        //first item doesnt need ,     
        if(deleteItems.value == "")
        {
          deleteItems.value = table.rows[i].id
        }
        else
        {
          deleteItems.value = deleteItems.value + "," + table.rows[i].id
        }
        
        table.deleteRow(i)
      }
      else
      {
        deleteItems.value = deleteItems.value.replace(table.rows[i].id + ",", "")
      }
    }
  }
}

function checkDate(startDate, endDate, daysDifference)
{
	var day;
	var month;
	var year;

	//split the string to get day, month ,year
	dateArray = startDate.split("/")
	
	day = dateArray[0];
	month = dateArray[1];
	year = dateArray[2];
	
	var jsStartDate = new Date(year, month - 1, day);
	
	//split the string to get day, month ,year
	dateArray = endDate.split("/")
	
	day = dateArray[0];
	month = dateArray[1];
	year = dateArray[2];
	
	var jsEndDate = new Date(year, month - 1, day);
	
  //get todays date + daysDifference
	//NewDate = new Date();
	var checkDate = new Date(jsStartDate.getTime() + (daysDifference * 86400000));

	if(checkDate > jsEndDate || isNaN(checkDate))
	{
		alert("You cannot proceed, as insufficient time has lapsed from the date of publication of the notice")
		return false
	}

	return true
}

function callEvents(formName)
{
  var f = findObj(formName);
   
  //for each element in the form f
	for (var i = 0; i < f.length; i++)
	{
	  if(f.elements[i].getAttribute('onchange') != null)
		{
		  //dont call for empty values
		  if(f.elements[i].getAttribute('value') != "")
		  {
			  f.elements[i].onchange();
		  }
		  //dropdowns can be called though
		  else if(f.elements[i].getAttribute('type') == "select-one")
		  {
			  f.elements[i].onchange();
		  }
		}
		if(f.elements[i].getAttribute('onclick') != null && f.elements[i].checked == true)
		{
		  f.elements[i].onclick();
		}
		if(f.elements[i].getAttribute('onload'))
		{
			//call the function that is passed
			setTimeout(f.elements[i].getAttribute('onload'), 1);
		}
	}
}

function checkCardDates()
{
  submit = true;
  
  issueDateMonth = document.Form1.issuedatemonth.value
  issueDateYear = document.Form1.issuedateyear.value
  expiryDateMonth = document.Form1.expirydatemonth.value
  expiryDateYear = document.Form1.expirydateyear.value
  
  var jsIssueDate = new Date(issueDateYear, issueDateMonth - 1, 1);
  var jsExpiryDate = new Date(expiryDateYear, expiryDateMonth - 1, 1);
  var today = new Date() 
   
  if(issueDateMonth != "" && issueDateYear != "")
  {   
    if(jsIssueDate >= jsExpiryDate)
    {
      submit = false;
    
      alert("Expiry date must be after issue date")    
    }
  }
  
  if(today.getMonth() > jsExpiryDate.getMonth() && today.getFullYear() >= jsExpiryDate.getFullYear())
  {
    submit = false;
    
    alert("Expiry date must be after todays date")  
  }
  
  return submit
}

//ensures the the previous address has been completed
function neighbourAddressComplete(formName, objectCount)
{
  var f = findObj(formName);
  var complete = false;
  
  var address = findObj("address" + objectCount)
  var town = findObj("town" + objectCount)
  var postcode = findObj("postcode" + objectCount)
	
	if(address.value != "" && town.value != "")
	{
	  complete = true
	}
	
	if(complete == false)
	{
	  alert("You must complete the previous address")
	}
	
	return complete
}

function checkEmailsMatch(obj1, obj2, message)
{
  var match = false
  var value1 = findObj(obj1).value
  var value2 = findObj(obj2).value
  
  if(value1 == value2)
  {
    match = true
  }
  else
  {
    alert(message)
  }

  return match
}

//service date must be within 21 days before today
function checkServiceDate(startDate)
{
	var day;
	var month;
	var year;
	var valid;

	//split the string to get day, month ,year
	dateArray = startDate.split("/")
	
	day = dateArray[0];
	month = dateArray[1];
	year = dateArray[2];
	
	var jsStartDate = new Date(year, month - 1, day);
	
  //get todays date + daysDifference
	todaysDate = new Date();
	
	var checkDate = new Date(todaysDate.getTime() - (21 * 86400000));	

	if(jsStartDate < checkDate)
	{
		alert("The Date of Service of Notice to the persons upon whom notice was served is not within the region of 21 days before today.\n\nThe Planning Service cannot accept this application")
		valid = false
	}
	if(jsStartDate > todaysDate)
	{
		alert("The Date of Service of Notice to the persons upon whom notice was served is not within the region of 21 days before today.\n\nThe Planning Service cannot accept this application")
		valid = false
	}

	return valid
}

function checkAllowedFileType(fileName)
{
  var extension = fileName.substring(fileName.length-4,fileName.length)
  var valid = true
  
  if(extension.toLowerCase() == ".exe")
  {
    alert("For security reasons .exe files cannot be uploaded")
    valid = false
  }
  
  return valid
}

//turns validation on or off for the passed in control
function setMandatoryControl(controlName, mandatory)
{  
  var control = findObj(controlName)
  
  if(mandatory == true)
  {
    control.setAttribute('mandatory','true')
  }
  else
  {
    control.setAttribute('mandatory', '')
  }
}

function resetRadioButtons(control)
{
	objControl = findObj(control)

	for(i=0; i<objControl.length; i++)
	{
	  objControl[i].checked = false;
	}	
}

function resetCheckBoxes(control)
{
  var loop = true;
  var i = 1;
  var id = "";

  while(loop)
  {
    id = control + "_" + i
    
    if(document.getElementById(id) != null)
    {
	    objControl = document.getElementById(id)    

	    objControl.checked = false;
	    
	    i++;
	  }
	  else
	  {
	    loop = false;
	  }
	}	
}

function resetDropdown(control)
{
	objControl = findObj(control)

	objControl.selectedIndex = 0;
}

function showHiddenStreets(streetsection)
{	
	var f = findObj(streetsection);
	
	f.style.display = "block";
}

function hideHiddenStreets(streetsection)
{	
	var f = findObj(streetsection);
	
	f.style.display = "none";
}

function clearTextbox(control)
{
	var obj = findObj(control);
	
	obj.value="";
}

var cX = 0;
var cY = 0;
var rX = 0;
var rY = 0;

function UpdateCursorPosition(e)
{
	cX = e.pageX;
	cY = e.pageY;
}
function UpdateCursorPositionDocAll(e)
{
	cX = event.clientX;
	cY = event.clientY;
}
if(document.all)
{
	document.onmousemove = UpdateCursorPositionDocAll;
}
else
{
	document.onmousemove = UpdateCursorPosition;
}

function AssignPosition(d)
{
	if(self.pageYOffset)
	{
		rX = self.pageXOffset;
		rY = self.pageYOffset;
	}
	else if(document.documentElement && document.documentElement.scrollTop)
	{
		rX = document.documentElement.scrollLeft;
		rY = document.documentElement.scrollTop;
	}
	else if(document.body)
	{
		rX = document.body.scrollLeft;
		rY = document.body.scrollTop;
	}
		
	if(document.all)
	{
		cX += rX; 
		cY += rY;
	}
	
	d.style.left = (cX+5) + "px";
	d.style.top = (cY+5) + "px";
}
function HideContent(d)
{
	if(d.length < 1)
	{
		return;
	}
	
	document.getElementById(d).style.display = "none";
}

function ShowContent(d)
{
	if(d.length < 1)
	{
		return;
	}
	
	var dd = document.getElementById(d);
	AssignPosition(dd);
	dd.style.display = "block";
}
function ReverseContentDisplay(d)
{
	if(d.length < 1)
	{
		return;
	}
	
	var dd = document.getElementById(d);
	AssignPosition(dd);
	
	if(dd.style.display == "none")
	{
		dd.style.display = "block";
	}
	else
	{
		dd.style.display = "none";
	}
}

function autoReload()
{
  if (window.name=='autoreload')
  {
     location.reload();
     window.name='';
  }
}
