$(document).ready(function(){
	var template = "individuals";
	$('#rotate .images')
	.after('<div id="nav">')
	.cycle({ 
		fx:     'fade', 
		timeout: 1000, 
		pager:  '#nav',
		cleartype: true,
		cleartypeNoBg: true,
		before:   function(){
			$('#rotate .imageTitle').html(this.alt); 
		}
	});
	$("#longheader").corner("5px");
	$("#topIntro").corner("5px");
	$("#sellingPoint").corner("5px");
	$("#bottomLast").corner("5px");
	$("#footer").corner("5px");
	$("#formContent").corner("10px");
	$(".sectionBgColor").corner("10px");
	$("a[rel^='prettyPhoto']").prettyPhoto({theme:'dark_rounded'});
	$('.tooltip').tipsy({
		fade: true,
		gravity: 'w'
	});
	
	if(!$(".info table").height() < 220){
		$(".mapOuterBox").css("height", $(".info table").height());
		$(".mapInnerBox").css("height", $(".info table").height());
	}
	
	$("#emailme").validate({
		rules: {
			emName: { required: true },
			emEmail: { required: true, email: true },
			emContact: { required: true, number: true }
		},
		messages: {
			emName: { required: "Name cannot be left empty." },
			emEmail: { required: "Email address cannot be left empty.", email: "This is not valid email address." },
			emContact: { required: "Contact number cannot be left empty." }
		},
		submitHandler: function() { 
			$("#emailme").ajaxSubmit({
				url: "/template/" + name + "/action.php?action=emailme&propertyid="+$("#propertyid").html(),
				type: $("#listingForm").attr("method"),
				timeout: 20000,
				beforeSubmit: function(){
				}, 
				error: function(xhr, desc, e) {
					var msg = (desc == 'timeout') ? 'Connection 20 sec Time Out, Please try again Later.': desc;
					alert("Failed to save: " + msg);
					// alert(xhr.responseText);
				},
				success: function(msg){
					var msg_arr = msg.split("||");
					switch(msg_arr[0]){
						case "true":
							$("#sucDialog").html(msg_arr[1]);
							$("#sucDialog").dialog("open");
							break;
						case "false":
							$("#errDialog").html(msg_arr[1]);
							$("#errDialog").dialog("open");
							break;
						default:
							alert(msg);
					}
				},
				complete: function(){
					//$('form').clearForm();// clear data
				}
			});
		}
	});
		
	/*
	$("#country").change(function(){
		$().ajaxSubmit({
			url: "template/" + template +"/action.php?action=getState&countryid=" + $("#country").val(),
			type: "POST",
			timeout: 60000,
			beforeSubmit: function(){}, 
			error: function(xhr, desc, e) {
				var msg = (desc == 'timeout') ? '1 minute time out. Please try again Later.': desc;
				//alert("Failed to save: " + msg);
				// alert(xhr.responseText);
			},
			success: function(msg){
				$("#switchArea").html(msg);
			},
			complete: function(){
			}
		});
	})
	*/
	
	$("#agency").keyup(function(){
		$().ajaxSubmit({
			url: "template/" + template +"/action.php?action=getStateFromAgency&agency=" + $("#agency").val(),
			type: "POST",
			timeout: 60000,
			beforeSubmit: function(){}, 
			error: function(xhr, desc, e) {
				var msg = (desc == 'timeout') ? '1 minute time out. Please try again Later.': desc;
				//alert("Failed to save: " + msg);
				// alert(xhr.responseText);
			},
			success: function(msg){
				if(msg)
					$("#state").selectOptions(msg);
			},
			complete: function(){
			}
		});
	})
	
	$("#month").change(function(){
		if($("#month").val() == "01" || $("#month").val() == "03" || $("#month").val() == "05" || $("#month").val() == "07" || $("#month").val() == "08" || $("#month").val() == "10" || $("#month").val() == "12"){
			if($("#date").children().length < 31) // check if 31 is already exist
				$("#date").addOption("31", "31"); 
		}else{
			$("#date").removeOption("31");
		}
	})
	$("#refreshCaptcha").click(function(){
		$.post('captcha/newsession.php');
		$("#captchaImage").load('captcha/image_req.php');
		return false;
	});
	$("#signUpForm").validate({
		rules: {
			agency: { required: true },
			firstname: { required: true },
			lastname: { required: true },
			email: { required: true, email: true, remote: "template/"+template+"/action.php?action=checkEmail" },
			mobile: { required: true, digits: true},
			username: {required: true, minlength: 5, maxlength: 10, remote: "template/"+template+"/action.php?action=checkUsername" },
			password: {required: true, minlength: 5, maxlength: 10},
			confirmpassword: {equalTo: "#password"},
			captcha: {required: true, remote: "../captcha/process.php" }
		},
		messages: {
			agency: { required: "Please select your agency." },
			firstname: { required: "Please enter your first name." },
			lastname: { required: "Please enter your last name." },
			email: { required: "Please enter your email address.", email: "This is not a correct email address format.", remote: "Your email address is registered."},
			mobile: { required: "Please enter your mobile number.", digits: "Please enter only numbers."},
			username: { required: "Please enter your username.", minlength: "Please enter at least 5 characters.", maxlength: "Please do not enter more than 10 characters.", remote: "Your username is taken." },
			password: { required: "Please enter your password.", minlength: "Please enter at least 5 characters.", maxlength: "Please do not enter more than 10 characters." },
			confirmpassword: { equalTo: "Please enter the same password again." },
			captcha: { required: "Please enter the characters as seen on the image.", remote: "Wrong characters entered." }		
		},
		submitHandler: function() {
			$("#signUpForm").ajaxSubmit({
				url: $("#signUpForm").attr("action"),
				type: $("#signUpForm").attr("method"),
				timeout: 60000,
				beforeSubmit: function(){
					$("#submit").hide();
					$("#signUpLoader").show();
				},
				error: function(xhr, desc, e) {
					var msg = (desc == 'timeout') ? '1 minute time out. Please try again Later.': desc;
					//alert("Failed to signup: " + msg);
					// alert(xhr.responseText);
				},
				success: function(msg){
					var msg_arr = msg.split("||");
					switch(msg_arr[0]){
						case "true":
							$("#sucDialog").html(msg_arr[1]);
							$('#signUpForm').resetForm();
							$("#signUpLoader").hide();
							$("#sucDialog").dialog("open");
							window.location = "http://www.x-panels.com/login";
							break;
						case "false":
							$("#errDialog").html(msg_arr[1]);
							$("#errDialog").dialog("open");
							$("#submit").show();
							$("#signUpLoader").hide();
							break;
						default:
							alert(msg);
							alert($("#signUpForm [agency]").val());
							$("#submit").show();
							$("#signUpLoader").hide();
					}
				},
				complete: function(){}
			})
		}
	})
	
	$('#errDialog').dialog({
		autoOpen: false,
		width: 400,
		modal: true,
		zIndex: 3999,
		resizable: false,
		buttons: {
			"Ok": function() {
				$(this).dialog("close"); 
			}
		}
	});
	$('#sucDialog').dialog({
		autoOpen: false,
		width: 400,
		modal: true,
		zIndex: 3999,
		resizable: false,
		buttons: {
			"Ok": function() {
				$(this).dialog("close"); 
			}
		}
	});
})

function stripNonNumeric( str ){
	str += '';
	var rgx = /^\d|\.|-$/;
	var out = '';
	for( var i = 0; i < str.length; i++ ){
		if( rgx.test( str.charAt(i) ) ){
			if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
			( str.charAt(i) == '-' && out.length != 0 ) ) ){
				out += str.charAt(i);
			}
		}
	}
	return out;
}

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;
}
function LoanCalc(){
	var Amount = new Number(stripNonNumeric(document.getElementById("amt").value));
	var Rate = new Number(document.getElementById("rate").value);
	var Term = new Number(document.getElementById("period").value); 
	var Mrate = ( Rate / 100 ) / 12 ;
	var Mterm = Term * 12 ;
	var Pay = Amount * Mrate / (1 - Math.pow((1 + Mrate),-Mterm) ) ;

	document.getElementById("amt").value = addCommas(Amount);
	document.getElementById("monthly").value = addCommas(Math.round(Pay));
}
LoanCalc();