
function autoFill(inputId,defVal){
	var chosenField = $("input#" + inputId);

	chosenField.focus(function(){
		if(chosenField.attr("value") == defVal){
			chosenField.attr("value","");
		}	
	});

	chosenField.blur(function(){
		if(chosenField.attr("value") == ""){
			chosenField.attr("value",defVal);
		}												 
	});
}

function limitChars(textclass, limit, outputclass){
 var text = $('.'+textclass).val(); 
 var textlength = text.length;
 if(textlength > limit){
		$('.'+outputclass+' span').html('0');
	 $('.'+textclass).val(text.substr(0,limit));
	 return false;
 } else {
	 $('.'+outputclass+' span').html((limit - textlength));
	 return true;
 }
}

$(document).ready(function() {
	
	// Has JS
	$("body").addClass("hasJS");

	autoFill("caseNo","number");
	autoFill("cbName","name");
	autoFill("cbPhone","phone");
	autoFill("cbEmail","email");
	
	$('.limit').keyup(function(){
		limitChars('limit', 1000, 'limitDisplay');
	})
	
	$(".otherHidden").css("display","none"); 
	$("#whereFound").change(function(){
		var selected = $("#whereFound option:selected")
		var selectedVal = selected.val();
		if(selectedVal == "Other"){
			$(".otherHidden").slideDown();	
		}else{
			$(".otherHidden").slideUp(function(){
			});
		}
	});
	if(!$("#rentArrears").is(':checked')){
		$("#rentArrearsSection").css("display","none"); 
		$("#rentDueAmount").removeClass("required");
		$("#rentDueTotal").removeClass("required");
	}
	$("#rentArrears").click(function(){
		if($(this).is(':checked')){
			$("#rentArrearsSection").slideDown();
			$("#rentDueAmount").addClass("required");
			$("#rentDueTotal").addClass("required");
		}else{
			$("#rentArrearsSection").slideUp();
			$("#rentDueAmount").removeClass("required");
			$("#rentDueTotal").removeClass("required");
		}
	});
	
	if(!$("#rentDueMonthly").is(':checked')){
		$(".rentDueDay").css("display","none"); 
	}
	$(".rentDue").click(function(){
		if($("#rentDueMonthly").is(':checked')){
			$(".rentDueDay").slideDown();
		}else{
			$(".rentDueDay").slideUp();
		}
	});
	
	if($("select#notice option:selected").val() == "No"){
		$("#noticeConditional").hide();
		$("#mainInfo").hide();
		$("#noNotice").show();								
	}
	
	$("select#notice").change(function(){
		if($("select#notice option:selected").val() != "Yes"){
			$("#noticeConditional").fadeOut();
			$("#mainInfo").fadeOut(function(){
				$("#noNotice").fadeIn();								
			});
		}else{
			$("#noNotice").fadeOut(function(){
				$("#noticeConditional").fadeIn();
				$("#mainInfo").fadeIn();												
			});	
		}
	});
	
	// Handle rent arrears table
	$("a#addRow").click(function(){
		var numRows = $("table#rentArrears tr").length;
		$("table#rentArrears").append("<tr><td><input name='date-"+numRows+"' class='input' id='date-"+numRows+"' type='text' /></td><td><span>&pound;</span><input name='amount-"+numRows+"' class='input number' id='amount-"+numRows+"' type='text' /></td><td><input name='dateReceived-"+numRows+"' class='input' id='dateReceived-"+numRows+"' type='text' /></td><td><span>&pound;</span><input name='amountReceived-"+numRows+"' class='input number' id='amountReceived-"+numRows+"' type='text' /></td><td><span>&pound;</span><input name='accumulative-"+numRows+"' class='input number' id='accumulative-"+numRows+"' type='text' /></td></tr>");
		return false;
	});
	
	// Handle news excerpts
	/*
	$(".newsContent").excerpt();
	$(".newsEntry p.showMore a").click(function(){
		$(this).parent()												
	});
	*/
	
	// Handle insurance 'Add another property'
	$("form#insuranceProperties a#insureAnother").bind("click", function(evnt){
		evnt.preventDefault();
		var dataString = $("form#insuranceProperties").serialize();
		dataString += "&method=ajax";
		$.ajax({
		 type: "POST",
		 url: "process.php",
		 data: dataString,
		 success: function(data){
			 var result = jQuery.parseJSON(data);
			 if(result.error != undefined){
				 if($("#secondary ul.errors").length < 1){
					 $("form#insuranceProperties").before("<ul class=\"errors\"></ul>")
				 }else{
					 $("#secondary ul.errors").empty();
				 }
				 var errorLength = result.error.length;
				 for(var i=0;i<errorLength;i++){
					$("#secondary ul.errors").append("<li>"+result.error[i]+"</li>");
				 }
			 }else if(result.success != undefined){
				  if($("#secondary ul.errors").length > 0){
						$("#secondary ul.errors").remove();
				 	}
					if($("#right .basket").hasClass("empty")){
						$("#right .basket").removeClass("empty");
				 	}
					var propertyHTML = "<div class=\"basketRow\" data-id=\""+result.success['propertyID']+"\">";
					propertyHTML    += "<div class=\"propertyName\">"+$("input#propertyAddress1").val()+"</div>";
					propertyHTML    += "<div class=\"modifiers\"><a href=\"#\" class=\"editProperty\">Edit</a> | <a href=\"#\" class=\"deleteProperty\">Delete</a></div>";
					propertyHTML    += "</div>";
					if($("#right .basket .basketRow").length < 1){
						$("#right .basket h3").after(propertyHTML);
					}else{
						$("#right .basket .basketRow:last").after(propertyHTML);
					}
					
					$("#right .basket .basketTotal span").html(parseInt(result.success['total']).toFixed(2));
					$("form#insuranceProperties input.input").val("");
					$("form#insuranceProperties input.checkbox").attr("checked",false);
					$("form#insuranceProperties select option").attr("selected",false);
					$("form#insuranceProperties select option:first-child").attr("selected",true);
			 }
		 }
	  });																									 
	});
	
	// Handle insurance 'Delete property'
	$(".basket a.deleteProperty").live("click", function(evnt){
		evnt.preventDefault();
		var propertyID = parseInt($(this).parents(".basketRow").attr("data-id"));
		var dataString = "action=insurancePropertyDelete&method=ajax&propertyID="+propertyID
		$.ajax({
		 type: "POST",
		 url: "process.php",
		 data: dataString,
		 success: function(data){
			 var result = jQuery.parseJSON(data);
			 if(result.success != undefined){
				 $(".basket .basketRow[data-id='"+propertyID+"']").remove();
				 $("#right .basket .basketTotal span").html(parseInt(result.success['total']).toFixed(2));
				 if($(".basket .basketRow").length < 1){
				  $(".basket").addClass("empty");
				 }
			 }else{
				 alert("Something went wrong. Please try again."); 
			 }
		 }
	  });																									 
	});
	
	// Handle insurance 'Edit property'
	$(".basket a.editProperty").live("click", function(evnt){
		evnt.preventDefault();
		var propertyID = parseInt($(this).parents(".basketRow").attr("data-id"));
		var dataString = "action=insurancePropertyEdit&method=ajax&propertyID="+propertyID
		$.ajax({
		 type: "POST",
		 url: "process.php",
		 data: dataString,
		 success: function(data){
			 var result = jQuery.parseJSON(data);
			 if(result.success != undefined){
				 $("form#insuranceProperties input#propertyAddress1").val(result.success['property']['address1']);
				 $("form#insuranceProperties input#propertyAddress2").val(result.success['property']['address2']);
				 $("form#insuranceProperties input#propertyTown").val(result.success['property']['town']);
				 $("form#insuranceProperties input#propertyCounty").val(result.success['property']['county']);
				 $("form#insuranceProperties input#propertyPostcode").val(result.success['property']['postcode']);
				 $("form#insuranceProperties select#propertyType option[value='"+result.success['property']['type']+"']").attr("selected",true);
				 $("form#insuranceProperties input#startDate_day").val(result.success['property']['start_day']);
				 $("form#insuranceProperties input#startDate_month").val(result.success['property']['start_month']);
				 $("form#insuranceProperties input#startDate_year").val(result.success['property']['start_year']);
				 if(result.success['property']['policyReceived'] == 1){
					 $("form#insuranceProperties input#policyReceived").attr("checked",true);
				 }
				 if(result.success['property']['referenceCheck'] == 1){
					 $("form#insuranceProperties input#referenceCheck").attr("checked",true);
				 }
				 
				 $(".basket .basketRow[data-id='"+propertyID+"']").remove();
				 $("#right .basket .basketTotal span").html(parseInt(result.success['total']).toFixed(2));
				 if($(".basket .basketRow").length < 1){
				  $(".basket").addClass("empty");
				 }
			 }else{
				 alert("Something went wrong. Please try again."); 
			 }
		 }
	  });																							 
	});
	
	// Disable submit buttons after click
	/** Clashes with validation plugin..
	$('form').submit(function(){  
  	$(':submit', this).click(function() {  
   		return false;
  	});
  });  
	**/
	
	$("#callbackForm").validate();
	$("#trackcaseForm").validate();
	$("#contactForm").validate();
	$("#councilLogin").validate();
	$("#councilInquiry").validate();
	$("#orderForm").validate();
	$("#step1Form").validate();
	$("#step2Form").validate();
	$("#benefitCampaign").validate();
	$("#LAPack").validate();
	$("#overloadedCampaign").validate();
	
});
