Event.observe(window, 'load', initialize, false);

function initialize(){
	// attach form events to sidebar
	
	if($('fname')){attachFieldEvents('fname');}
	if($('lname')){attachFieldEvents('lname');}
	if($('question')){attachFieldEvents('question');}
	if($('company')){attachFieldEvents('company');}
	if($('email')){attachFieldEvents('email');}
	if($('phone')){attachFieldEvents('phone');}
	
	if($('termscheckbox')){
		Event.observe($('termscheckbox'), 'click', function(){enableForm()}, false);
	}
	if($('contactbutton')){Event.observe($('contactbutton'), 'click', function(){sendSidebarInfo()}, false);}
	
	// these are for the hide/show of additional sections
	
	if($('bankruptcyyes') && $('bankruptcyanswer')){Event.observe($('bankruptcyyes'), 'click', function(){$('bankruptcyanswer').style.display='block';}, false);}
	if($('bankruptcyno') && $('bankruptcyanswer')){Event.observe($('bankruptcyno'), 'click', function(){$('bankruptcyanswer').style.display='none';}, false);}
	if($('addpreviousbank')){Event.observe($('addpreviousbank'), 'click', function(){hideDisplay('addpreviousbank','previousbank')}, false);}
	if($('addfirm')){Event.observe($('addfirm'), 'click', function(){hideDisplay('addfirm','firm2')}, false);}
	if($('addprincipal')){Event.observe($('addprincipal'), 'click', function(){hideDisplay('addprincipal','principal2')}, false);}
	
	if($('submitbtn')){Event.observe($('submitbtn'), 'click', function(e){validateForm(e)}, false);}
	
	if($('termspop')){Event.observe($('termspop'), 'click', function(e){popwindow(e,$('termspop'),'440','300')}, false);}
	
	//attach pop up to all "PDF" links
	pdfEls = document.getElementsByClassName('pdf');
	if(pdfEls.length > 0){
		//alert(pdfEls.length);
		pdfEls.each(
			function(pdfel){
				//alert(pdfel.tagName.toLowerCase());
				if(pdfel.tagName.toLowerCase()=="a"){
					Event.observe(pdfel, 'click', function(e){popwindow(e,pdfel);}, false);
				}
			}
		);//end pdfEls.each
	}
	
	//if($$('defderflink')){Event.observe($('defderflink'), 'click', function(e){popwindow(e,$('defderflink'));}, false);}
	
}

// function for attaching clear and restore field
function attachFieldEvents(fieldId){
	Event.observe($(fieldId), 'focus', function(){clearField($(fieldId))}, false);
	Event.observe($(fieldId), 'blur', function(){restoreField($(fieldId))}, false);
}

function clearField (field){
	Element.addClassName(field,'focused');
	if ($F(field) == field.defaultValue){
		Field.clear(field);
		Element.addClassName(field,'notdefault');
	}
}
function restoreField(field){
	Element.removeClassName(field,'focused');
	if ($F(field) == "" || $F(field).toLowerCase() == field.defaultValue.toLowerCase()){
		field.value = field.defaultValue;
		Element.removeClassName(field,'notdefault');
	}
}

function hideDisplay(inputElement,toggleElement){
	display = ($(inputElement).checked)?"block":"none";
	$(toggleElement).style.display = display;	
}
function validateForm(ev){
	msgNodes = document.getElementsByClassName('msg',$('application'));
	msgNodes.each(
		function(n){
			n.parentNode.removeChild(n);
		}
	);
	
	requiredFields = document.getElementsByClassName('required',$('application'));
	isInvalid = '';
	requiredFields.each(
		function(element){
			fieldElement = getInputSelect(element);
			//alert(fieldElement);
			if(fieldElement.tagName!=null && (fieldElement.tagName.toLowerCase()=='input' || fieldElement.tagName.toLowerCase()=='select')){
				isInvalid += validateField(element,fieldElement,ev);
			}
		}
	);
	if(isInvalid==""){
		$('application').submit();
		window.open(siteRoot+"/docs/credit-check-authorization.pdf","auth","width=500,height=700,top=0,left=0,location=no,scrollbars=yes,menubars=yes,toolbar=yes,resizable=yes");
	}
}
function validateField(element,fieldElement,ev){
	if($F(fieldElement)=="" || $F(fieldElement)==-1){
		Element.addClassName(element,'invalid');
		new Insertion.After(fieldElement,"<span class=\"msg\">This field is required</span>");
		Event.stop(ev);
		return "invalid";
	}
	else {
		Element.removeClassName(element,'invalid');
		return "";
	}
}
function getInputSelect(parent){
	val = "";
	for(i=0;i<parent.childNodes.length;i++){
		n = parent.childNodes[i];
		if(n.nodeType==1 && (n.tagName.toLowerCase()=="input" || n.tagName.toLowerCase()=="select")){
			val = n;
		}
	}
	return val;
}
function enableForm(){
	if($('submitbtn')){
		if($('submitbtn').disabled==true){
			$('submitbtn').disabled = false;
			$('submitbtn').innerHTML = '<img src="'+siteRoot+'/images/submit-application-button.png" width="125" height="27" alt="Submit Application" class="png">';
		}
		else{
			$('submitbtn').disabled = true;
			$('submitbtn').innerHTML = '<img src="'+siteRoot+'/images/submit-application-button-disabled.png" width="125" height="27" alt="Submit Application" class="png">';
		}
	}
}
function sendSidebarInfo(){
	invalid = new Array();
	if($F('name')==""){
		invalid[invalid.length] = "name";
	}
	if ($F('comments')==""){
		invalid[invalid.length] = "comments";
	}
	if ($F('email')==""){
		invalid[invalid.length] = "email";
	}
	
	if(invalid.length>0){
		$$("#contactform label").each(function(label){
			Element.removeClassName(label,"alert");
		});
		
		for(x in invalid){
			elID = "for"+invalid[x]
			Element.addClassName($(elID),"alert")
		}
	}
	else {
		var pars = Form.serialize($('contactform'));
		//alert(pars);
		
		var myAjax = new Ajax.Request(
			"includes/mailer.php", 
			{
				method: 'get', 
				parameters: pars, 
				onLoading: showLoading,
				onComplete: showResponse
			}
		);
		Form.disable($('contactform'));
	}
}
function showLoading(){
	if($('loading')){$('loading').style.display="block";}
}
function showResponse(originalRequest){
	if($('loading')){$('loading').style.display="none";}
	$('contactform').innerHTML = originalRequest.responseText;
}

// pop up new window
function popwindow(ev,el,w,h){
	Event.stop(ev);
	
	width = (w!="")?w:"700";
	height = (h!="")?h:"500";
	
	// Detect existence of the popup
	try {
		if(typeof popup!="object"){ // check if the pop-up was created
			popup = window.open(el.href,"popwin","width="+width+",height="+height+",top=0,left=0,location=no,scrollbars=yes,menubars=yes,toolbar=yes,resizable=yes");
		}
		else if(typeof popup=="object" && popup.closed){ // check if popup was created, but the window is closed
			popup = window.open(el.href,"popwin","width="+width+",height="+height+",top=0,left=0,location=no,scrollbars=yes,menubars=yes,toolbar=yes,resizable=yes");
		}
	}
	catch(ex){
		popup = window.open(el.href,"popwin","width="+width+",height="+height+",top=0,left=0,location=no,scrollbars=yes,menubars=yes,toolbar=yes,resizable=yes");
	}

	popup.focus();
}

// IE workaround for bg images flicker
try {
	document.execCommand("BackgroundImageCache",false,true);
}
catch(e) {}