function createExplanation(text, title){
	var win = new Window({className: "alphacube", width:520, height:200, zIndex: 100, resizable: true, title: title, showEffect:Effect.BlindDown, hideEffect: Effect.SwitchOff, draggable:true, wiredDrag: true});
	win.getContent().innerHTML = text;
	win.showCenter();
}

function createPDF(url){
	var win = new Window({className: "alphacube", width:400, height:200, zIndex: 100, resizable: true, title: 'Creating PDF', showEffect:Effect.BlindDown, hideEffect: Effect.SwitchOff, draggable:true, wiredDrag: true});
	win.setURL('http://titlesourceusa.com/apps/HudResources/loading.html');
	win.showCenter();
	new Ajax.Request('/apps/HudResources/createPDF.php',
  {
    method:'post',
	parameters:{aURL:url},
    onSuccess: function(transport){
      var response = transport.responseText || "no response text";
      if(response=='1'){
		  win.setHTMLContent('<a href="#" onclick="javascript:window.open (\'http://www.titlesourceusa.com/apps/force_download.php?serverfile=/downloads/pdf/'+url+'.pdf\', \'pdfwindow\', \'resizable=1,location=0,scrollbar=1,toolbar=0,width=500,height=600\');" style="font-size:16pt;">Download PDF</a>');
		  win.setTitle('Download PDF');
		  //window.open ('http://www.titlesourceusa.com/apps/force_download.php?serverfile=/downloads/pdf/'+url+'.pdf', 'pdfwindow', 'resizable=1,location=0,scrollbar=1,toolbar=0,width=500,height=600');
		  //window.location = 'http://www.titlesourceusa.com/apps/force_download.php?serverfile=/downloads/pdf/'+url+'.pdf';
	  }
	  else{
		 win.setHTMLContent('Your PDF could not be created, please try again later.');
	  }
    },
    onFailure: function(){ alert('Something went wrong...') }
  });
}

function mortgageTrigger(element){
	var num;
	num = stripAlphaChars(element.value);
	if(num > 0){
		$('LenderInsuranceApplicable').options[0].selected = true;
		$('FormNineApplicable').options[0].selected = true;
		$('AltaEightApplicable').options[0].selected = true;
		//$('FivePointOneApplicable').options[0].selected = true;
		$('L1_IntangibleTaxOnMtgApplicable').options[0].selected = true;
		$('LoanClosingApplicable').options[0].selected = true;
		$('L1_MtgDocStampsApplicable').options[0].selected = true;
		$('CountyTaxReservesPaidByApplicable').options[0].selected = true;
	}
	else{
		$('LenderInsuranceApplicable').options[1].selected = true;
		$('FormNineApplicable').options[1].selected = true;
		$('AltaEightApplicable').options[1].selected = true;
		$('FivePointOneApplicable').options[1].selected = true;
		$('L1_IntangibleTaxOnMtgApplicable').options[1].selected = true;
		$('LoanClosingApplicable').options[1].selected = true;
		$('L1_MtgDocStampsApplicable').options[1].selected = true;
		$('CountyTaxReservesPaidByApplicable').options[1].selected = true;
	}
}

function stripAlphaChars(pstrSource){ 
	var m_strOut = new String(pstrSource); 
    m_strOut = m_strOut.replace(/[^0-9]/g, ''); 
    return m_strOut; 
}


function SubmitForm(){
    javascript:document.getElementById('spanresult').innerHTML='<p style="text-align: center; font-weight:bold; height:1500px; font-size: 24px;">Loading.....</p>';
    get(document.getElementById ('SettlementCalculatorForm'),'/apps/HudResources/hudOutput.php','spanresult');
    location.hash = 'results';
}



function ShowLoadingMessageByID(id){
	document.getElementById(id).innerHTML='<p style="text-align: center; font-weight:bold; font-size: 24px;">Loading.....</p>';
}

	
function CheckFields(){
	//alert("HI value: " + document.forms['CCC'].PurchaseOrRefinance[0].checked);
	if(document.forms['CCC'].PurchaseOrRefinance[0].checked==false && document.forms['CCC'].PurchaseOrRefinance[1].checked==false){
		alert('You must select whether this is a purchase or a refinance, and then input the appropriate information.');
		return false;
	}
	x = document.getElementsByName('ClosingDate');
	if(x[0].value == ""){
		alert('You must select a closing date.');
		return false;
	}
	if(document.getElementById('AgreeToTerms').checked==false){
		alert('You must agree to the terms and conditions.');
		return false;
	}
}

/* this is defined in /images/Common/common.js
function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}
*/

function showExplanation(){
	$('inputtable').style.display = 'none';
	$('text').style.display = '';
	$('explanation').style.display = 'none';
	$('Purchase').checked = false;
	$('Refinance').checked = false;
}

function ShowOrHidePurchaseRows(por){
	document.getElementById('inputtable').style.visibility = "visible";
	document.getElementById('inputtable').style.display = "";
	$('text').style.display = 'none';
	$('explanation').style.display = '';
	
	var elements = getElementsByClassName('PurchaseRow');
	var display = (por == "refinance") ? "none" : ""; //b/c the default for a tr tag is not block, it is null
	var visibility = (por == "refinance") ? "hidden" : "visible"; //probably not necessary.
	var length = elements.length;
	for(var i=0; i<length; i++){
		elements[i].style.display = display;
		elements[i].style.visibility = visibility; //why do something that is not necessary?
	}
	
	elements = getElementsByClassName('RefinanceRow');
	display = (por == "refinance") ? "" : "none"; //b/c the default for a tr tag is not block, it is null
	visibility = (por == "refinance") ? "visible" : "hidden"; //probably not necessary.
	length = elements.length;
	for(var i=0; i<length; i++){
		elements[i].style.display = display;
		elements[i].style.visibility = visibility; //why do something that is not necessary?
	}
}

function ToggleClass(classname){
	var elements = getElementsByClassName(classname);
	
	var newdisplay = (elements[0].style.display=='none')? '' : 'none';
	var length = elements.length;
	for(var i=0; i<length; i++){
		elements[i].style.display = newdisplay;
	}
}
/*
function WhoPaysForWhat(who,what){
	if(who=="buyer"){
		var whonot = "seller";}
	else{
		var whonot = "buyer";
	}
	var name = what + who;
	var celltoshade = document.getElementById(name);
	name = what + whonot;
	var celltowhite = document.getElementById(name);
	//var inputfield = document.getElementByName(what + "PaidBy"); 
	//alert("hi");
	//inputfield = inputfield[0];
	
	celltoshade.style.backgroundColor = "red";
	celltowhite.style.backgroundColor = "white";
	//inputfield.value = who;
	//alert(inputfield.value);
}
*/


//explanation window object
var inlinewin=dhtmlwindow.open("quickinfo", "inline", "This is some inline content. <a href='http://dynamicdrive.com'>Dynamic Drive</a>", "#2: Broadcast Title", "width=500px,height=200px,left=150px,top=10px,resize=1,scrolling=1", "recal");
inlinewin.hide();



//Ty's Modified AJAX form submit with a return value
function file_get_contents(formobj,url,instructions) {

		var getstr = "&"; //this needs to be there for the post request (otherwise the first variable sent gets screwed up)
		getFormNodes(formobj);
		for (i=0; i<formnodes.length; i++) {
			getstr += getValueOfNode(formnodes[i]);
		}
	
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      
      http_request.onreadystatechange = function(){
		  if (http_request.readyState == 4) {
			 if (http_request.status == 200) {
				//alert(http_request.responseText);
				result = http_request.responseText;
				//document.getElementById(outputid).innerHTML = result;   
				DoInstructions(instructions,result);
			 } else {
				alert('There was a problem with the request.');
			 }
		  }
	   };
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", getstr.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(getstr);
}


// AJAX Form Submit
	var formnodes = Array();
	var outputid;
   var http_request = false;
	function get(FormObj,file,resultsid) {
		outputid = resultsid;
		var getstr = "&"; //this needs to be there for the post request (otherwise the first variable sent gets screwed up)
		getFormNodes(FormObj);
		for (i=0; i<formnodes.length; i++) {
			getstr += getValueOfNode(formnodes[i]);
		}
		makePOSTRequest(file, getstr);
	}
	
	
	
	/* This is interesting, but POST is more useful
   function makeRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request.onreadystatechange = alertContents;
	  //alert(url + parameters);
      http_request.open('GET', url + '?' + parameters, true);//url + parameters
      http_request.send(null);
   }
   */
   
   function makePOSTRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      
      http_request.onreadystatechange = alertContents;
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
   }


   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById(outputid).innerHTML = result;            
         } else {
            alert('There was a problem with the request.');
         }
      }
   }


	function getFormNodes(node){
		//if we have a form element, store it in formnodes
		if(node.tagName == "INPUT" || node.tagName=="SELECT" || node.tagName=="TEXTAREA"){
			formnodes.push(node);
		}
		//if this node has child elements, handle them
		for (var m=0; m<node.childNodes.length; m++) {
			getFormNodes(node.childNodes[m]);
		}
	}


function getValueOfNode(node){
	var getstr = "";
	if (node.tagName == "INPUT") {
		if (node.type == "text" || node.type == "submit" || node.type == "textarea") {
		   getstr += node.name + "=" + node.value + "&";
		}
		if (node.type == "checkbox") {
		   if (node.checked) {
			  getstr += node.name + "=" + node.value + "&";
		   } else {
			  getstr += node.name + "=&";
		   }
		}
		if (node.type == "radio") {
		   if (node.checked) {
			  getstr += node.name + "=" + node.value + "&";
		   }
		}
	}   
	if (node.tagName == "SELECT") {
		var selval = node.options[node.selectedIndex].value;
		getstr += node.name + "=" + selval + "&";
		//alert(node.name + " is equal to " + selval);
	}
	return (getstr);
}



function getElementsByTagNames(list,obj) {
	if (!obj) var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}


function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}


function changeThisClass(ITEM,from, to) {
	ITEM.className = ITEM.className.replace(from, to);
	return false;
}


  // Function to attach events to objects.
  // (http://icant.co.uk/articles/from-dhtml-to-dom/from-dhtml-to-dom-scripting.html#domasset3)
  function addEvent(elm, evType, fn, useCapture){
    if (elm.addEventListener)
    {
      elm.addEventListener(evType, fn, useCapture);
      return true;
    } else if (elm.attachEvent) {
      var r = elm.attachEvent('on' + evType, fn);
      return r;
    } else {
      elm['on' + evType] = fn;
    }
  }

