function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function is_array(input){
	return typeof(input)=='object'&&(input instanceof Array);
}
function formatPhone(phoneNumber,check){
	var tempPhone = phoneNumber.replace(/[^0-9]/g,"");
	if(tempPhone.substring(0,1)==1){
		tempPhone = tempPhone.substring(1);
	}
	var length = tempPhone.length;
	//tempPhone = tempPhone.replace(/[xX]/g,"x");

	var newPhone = tempPhone;
	if(length == 7){
		newPhone = newPhone.substring(0,3) + '-' + newPhone.substring(3,7);
	}else if(length > 7){
		newPhone = '(' + newPhone.substring(0,3) + ') ' + newPhone.substring(3,6) + '-' + newPhone.substring(6,10);
	}
	
	if(length > 10){
		newPhone += ' x' +  tempPhone.substring(10)
	}
	if(check){
		if(length >= 7){
			return newPhone;
		}else{
			createDialogBox('Error','Invalid Phone Number','The phone number your entered was incorrect. A phone number must be a valid 10 digit number.');
			return '';
		}
	}else{
		return newPhone;
	}
}
function hexToDeci(num)
{
	res4 = 999;
	args = num;

	k =args.length-1;
	for(var i=0; i<args.length; i++)
	{
	 	thisnum = args.substring(i,i+1) ;
	 	var resd = Math.pow(16,k);
		if(thisnum=='a')
			thisnum=10;
		else if(thisnum=='b')
			thisnum=11;
		else if(thisnum=='c')
			thisnum=12;
		else if(thisnum=='d')
			thisnum=13;
		else if(thisnum=='e')
			thisnum=14;
		else if(thisnum=='f')
			thisnum=15;
		 resd = resd*thisnum;
		 k=k-1;
		 if(res4 == 999)
			{
				res4=resd.toString();
			}
			else
			{
				res4=parseInt(res4)+parseInt(resd);
			}
	}

	return res4;
}
function colorToHex(color){
	color = color.replace('#','');
	var hex = '';
	color.toLowerCase();
	if(color.length == 6){
		var sdx = color.substring(0,2);
		var hex = hexToDeci(sdx)
		
		sdx = color.substring(2,4);
		hex = hex+","+hexToDeci(sdx)

		sdx = color.substring(4,6);
		hex = hex+","+hexToDeci(sdx)
	}
	return hex;
}
function popupPage(url, name, widgets){
	if(typeof popupWin == 'object'){
		popupWin.close();
	}
	popupWin = window.open(url, name, widgets);
	popupWin.opener.top.name = "opener";
	popupWin.focus();
}
function selectBoxesClass(className){
	var checked = true;
	if($("." + className).length>0){
		if($("." + className + ":eq(0)").attr('checked')){
			checked = false;
		}
		$("." + className).attr('checked',checked);
	}
}
function selectBoxes(FormName, FieldName, CheckValue){
	if(!document.forms[FormName]){
		return;
	}

	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes){
		return;
	}
	var countCheckBoxes = objCheckBoxes.length;
	
	if(!countCheckBoxes){
		if(objCheckBoxes.checked==false){
			objCheckBoxes.checked = true;
		}else{
			objCheckBoxes.checked = false;
		}
	}else{
		if(CheckValue=='auto'){
			if(objCheckBoxes[0].checked==true){
				CheckValue = false;
			}else{
				CheckValue = true;
			}
		}
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++){
			objCheckBoxes[i].checked = CheckValue;
		}
	}
	markChecked();
}
function selectAllOptions(FormName, FieldName){
	if(!document.forms[FormName])
		return;
	var field = document.forms[FormName].elements[FieldName];
	if(!field){ return; }
	var options = field.options;
	if(options[0].selected==true){
		var status=false;
	}else{
		var status=true;
	}
	for(var i=0; i< options.length; i++){
		options[i].selected = status;
	}
}

function processDecimal(number,spaces){
	number = number.toString();
	var negitive = false;
	if(number.search('-')>-1){
		negitive = true;
	}
	number = number.replace(/[^0-9.]/g,"");
	if(number==''){
		number = 0;
	}
	number = parseFloat(number);
	number = number.toFixed(spaces);
	if(negitive){
		number = '-' + number;
	}
	return number;
}

//process number forom form field
function processNum(number){
	var negitive = false;
	number = number.toString();
	if(number.search('-')>-1){
		negitive = true;
	}
	number = number.replace(/[^0-9.]/g,"");
	if(number.length>0){
		number = parseFloat(number);
		number = Math.round(number);
	}else{
		number=0;
	}
	if(negitive){
		number = '-' + number;
	}
	return parseInt(number);
}
//add commas to a number
function addCommas(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//global function that checks for required fields
function checkForm(formName){
	var checkedFields = new Array();
	var errorCount = 0;
	var minCharError = 0;
	//loop through all fields  of the form provided and check for required fields
	var fields = document.forms[formName].elements;
	for(var i=0; i<fields.length; i++){
		//skip over disabled fields
		if($(fields[i]).attr("disabled")==true){
			continue;
		}
		
		//make sure we haven't already check this field
		if(jQuery.inArray(fields[i].name, checkedFields)>-1){
			continue;
		}else{
			//put the name in the check fields array
			checkedFields.push(fields[i].name);
		}
		
		//only check for required fields
		if( $(fields[i]).hasClass('required') ){
			if(fields[i].type=='checkbox' || fields[i].type=='radio'){
				//make sure at least one is selected
				var checkFound=false;
				var boxes = document.forms[formName].elements[fields[i].name];
				if(boxes.length){
					for(var j=0; j<boxes.length; j++){
						if(boxes[j].checked==true){
							checkFound=true;
							break;
						}
					}
					if(checkFound==false){
						for(var j=0; j<boxes.length; j++){
							$(boxes[j]).parent().addClass("formCheckboxError");
						}
					}
				}else{
					if(boxes.checked==true){
						checkFound=true;
					}else{
						$(boxes).parent().addClass("formCheckboxError");
					}
				}
				if(checkFound==false){
					errorCount++;
				}
			}else if(fields[i].type=='select-multiple'){
				if(fields[i].value==''){
					errorCount++;
					$(fields[i]).addClass('fieldError');
				}
			}else{
				if( $(fields[i]).attr("requirements") ){
					var require = $(fields[i]).attr("requirements").split("|");
				}
				if(require){
					if(require[0]){
						if($(fields[i]).attr("value").length < require[0]){
							if($(fields[i]).attr("value")==''){
								errorCount++;
							}else{
								minCharError++;
							}
							//$(fields[i]).removeClass('fieldInput');
							$(fields[i]).addClass('fieldError');
						}
					}
					if(require[1]){
						//check for specific types here
					}
				}else{
					if($(fields[i]).attr("value")==''){
						errorCount++;
						//$(fields[i]).removeClass('fieldInput');
						$(fields[i]).addClass('fieldError');
					}
				}
			}
		}
	}
	if(errorCount>0){
		createDialogBox('Error','Missing Required Fields','All fields marked in red must be completed to continue.');
		return false;
	}else if(minCharError>0){
		createDialogBox('Error','Required Fields Incomplete','All fields marked in red do not meet their minimum character lengths.');
		return false;
	}else{
		return true;
	}
}
function resizeRegistration(){
	if($("#registration").length>0){
		var maxHeight = 500;
		var height = maxHeight;
		var width = 600;
		var tHeight = $(window).height();
		var tWidth = $(window).width();
		var tMar = 0;
		var lMar = 0;
		if(tHeight>height){
			tMar = Math.round((tHeight-height)/2);
		}else{
			height = tHeight-20;
			tMar=10
		}
		if(tWidth>width){
			lMar = Math.round((tWidth-width)/2);
		}else{
			width = tWidth-20;
			lMar=10
		}
		$("#registration").css("height",height+'px').css("margin-top",tMar+'px').css("margin-left",lMar+'px').css("width",width+'px');
	}
}
function forceRegistration(mode){
	if($("#dimmer").length==0){
		$("body").append('<div id="dimmer"></div>');
	}
	if($("#registration").length==0){
		$("body").append('<div id="registration">Loading...</div>');
	}else{
		$("#registration").html('Loading...');
	}
	$("body").css("overflow","hidden");
	
	$.ajax({
		type: "GET",
		cache: false,
		url: 'helpers/registration.php?action=' + mode,
		dataType: 'html',
		success: function(html) {
			$("#registration").html(html);
			resizeRegistration();
			pageSetup();
		}
	});
}
function registerUser(mode){
	if(checkForm('regForm')){
		var options = { 
			success: function(html){
				if(mode=='finish'){
					closeRegistration();
				}else{
					$("#registration").html(html);
					pageSetup();
				}
			},
			type: 'post',
			dataType: 'html',
			cache: false
		};
		//SUBMIT THE FORM
		$('#regForm').ajaxSubmit(options);
	}
}
function loginUser(){
	$("#loginError").css("display","none");
	if(checkForm('loginForm')){
		var options = { 
			success: function(html){
				var result = html.split('|');
				if(result[0]=='SUCCESS'){
					closeRegistration();
				}else{
					$("#loginError").html(result[1]).fadeIn();
				}
			},
			type: 'post',
			dataType: 'html',
			cache: false
		};
		//SUBMIT THE FORM
		$('#loginForm').ajaxSubmit(options);
	}	
}
function exitRegistration(){
	var loc = window.location.href;
	loc = loc.split('?');
	if(loc[0]==window.location.href){
		window.location.reload(true);
	}else{
		window.location.href=loc[0];
	}
	return;
}

function closeRegistration(){
	window.location.reload(true);
}

function addFavorite(id,add,login){
	if(login){
		$.ajax({
			url: 'helpers/registration.php?action=favorite&add=' + add + '&id=' + id,
			success: function(result) {
				if(result=='SUCCESS'){
					closeRegistration();
				}else{
					forceRegistration();
				}
			}
		});
	}else{
		forceRegistration();
	}
}

//************************ADVANCED INTERFACE FUNCTIONS*************************************/
function createDialogBox(type,title,message,myButtons){
	alert(message);
}

function setupSpecialFields(){
	//numbers
	$(".formNumber").change(function(){
		if($(this).val()!=''){
			var value = $(this).val();
			value = value.replace('k','000');
			value = value.replace('K','000');
			$(this).val( addCommas(processNum( value )) );
		}
	});
	//decimals
	$(".formDecimal").change(function(){
		if($(this).val()!=''){
			$(this).val( addCommas(processDecimal( $(this).val(),2 )) );
		}
	});
	//phones
	$(".phone").change(function(){
		if($(this).hasClass("required")){
			$(this).attr("value",formatPhone( $(this).attr("value"),true ) );
		}else{
			$(this).attr("value",formatPhone( $(this).attr("value"),false ) );
		}
	});


}

function formFieldFocus(field){
	$(field).removeClass("fieldError");
	$(field).removeClass("fieldInput");
	$(field).addClass("fieldFocus");
}

function formFieldBlur(field){
	$(field).removeClass("fieldFocus");
	$(field).addClass("fieldInput");
}

function clearCheckBoxError(field){
	var boxes = $("input[name='" + field.name + "']");
	if(boxes.length){
		for(var j=0; j<boxes.length; j++){
			$(boxes[j]).parent().removeClass("fieldError").removeClass("formCheckboxError");
		}
	}
}

function setupFormStyles(){
	$("textarea," + ":text," + ":password").addClass("fieldInput").focusin( function(){ formFieldFocus(this) }).focusout( function(){ formFieldBlur(this) });
	$("select").addClass("fieldInput").focusout( function(){ $(this).removeClass("fieldError") });
	$("textarea[disabled=true]," + "select[disabled=true]," + ":text[disabled=true]," + ":password[disabled=true]," + ":text[Locked=true]").unbind().removeClass("fieldInput").addClass("fieldDisabled");
	$(":submit," + ":button," + ":file," + ":reset").addClass("button");
	$(":radio").addClass("radio").click( function(){ clearCheckBoxError(this); } );
	$(":checkbox").addClass("myCheckbox").click( function(){ clearCheckBoxError(this); } );
	//checkboxes
	if($(".checkboxEntry").length>0){
		var width = 0;
		$(".checkboxEntry").each(function(){
			if($(this).outerWidth()>width){
				width = $(this).outerWidth();
			}
		});
		$(".checkboxEntry").css("width",width+"px");
	}
}

function createColorList(){
	//color the colorList
	$(".colorList").each(function(index){
		if($(this).find('th').length>0){
			var newClass = 'odd';
			var lastClass = 'even';
		}else{
			var newClass = 'even';
			var lastClass = 'odd';
		}
		
		$(this).children().children().each(function(index, element){
			if( $(element).css("display") != 'none' ){
				var temp = newClass;
				newClass = lastClass;
				lastClass = temp;
			}
			$(element).removeClass(newClass).removeClass(lastClass).addClass(newClass);
		});
	});
}

function pageSetup(){
	//set form styles
	setupFormStyles();
	//colist tables
	createColorList();
	//setup form numbers and decimals
	setupSpecialFields();
	
	//text shadows
	$(".shadow").textShadow();
	
}
var winResizeTimeout;
$(window).resize(function(){
	clearTimeout(winResizeTimeout);
	winResizeTimeout = setTimeout('resizeRegistration()',350);
});

//when doc is ready run page functions.
$(document).ready(function(){
	pageSetup();
	if($("#simpleCalculator").length>0){
		simpleLoan();
	}
});

$(window).scroll(function(){
	if($("#registration").length>0){
		$(window).scrollTop(0);
	}
});


/************SIMPLE LOAN CALCULATOR*****************/
function simpleLoan(){
	var h = processNum($("#lprice").val());
	var d = processNum($("#ldown").val());
	var p = h-d;
	$("#lamt").val(addCommas(processNum(p)));
	var r = processDecimal($("#lrate").val(),2)/100;
	var y = processNum($("#lterm").val());
	var m = mortgagePayment(p,r/12,y*12);
	$("#lpayment").text(addCommas(processNum(m),2));
}
function mortgagePayment(p,r,y){
	return futureValue(p,r,y)/geomSeries(1+r,0,y-1);
}
function futureValue(p,r,y){
	return p*Math.pow(1+r,y);
}
function geomSeries(z,m,n){
	var amt;
	if (z == 1.0) amt = n + 1;
	else amt = (Math.pow(z,n + 1) - 1)/(z - 1);
	if (m >= 1) amt -= geomSeries(z,0,m-1);
	return amt;
}
