/**
 * FILENAME: budget.js
 * AUTHOR: Ashley Barrett (ashley.barret@rgroup.co.uk)
 * CREATED: 21/12/2009
 * COMMENTS: A javascript file to for interactive elements of the budget planning tool
 * */

$(function(){
	if($("#formBudget").length > 0){
		//Customer function to add tooltips. Reuseable so we don't have to add the fix and position elements everytime.
		$.fn.showToolTip = function(content){
			return $(this).simpletip({ fixed: true, position: 'top', content: content });
		}
		
		$.fn.removeAnalysisConf = function(){
			$("#analysis #canHaveAnalysisConf").slideUp("slow");
		}
		
		$.fn.addAnalysisConf = function(){
			$("#analysis #canHaveAnalysisConf").slideDown("slow");
		}
		
		//Function to update the summary sentence.
		$.fn.updateSummaryCounter = function(){
			$.ajax({
				url: '/ajax/budgetPlanner/updateSummaryCounter.php',
				type: 'POST',
				cache: false,
				success: function(msg){
					if(msg != ""){
						$(".budgetSummary").fadeOut("slow",function(){
							$(this).find("p").remove();
							$(this).append(msg).fadeIn("slow")
						})
					}
				}
			});
		}
		
		$.fn.canHaveAnalysis = function(){
			$.ajax({
				url: '/ajax/budgetPlanner/canHaveAnalysis.php',
				type: 'POST',
				cache: false,
				success: function(msg){
			
					if(msg == "yes"){
						$.scrollTo("html");
						$(this).getAnalysis();
						/*setTimeout("$(this).addAnalysisConf()",600);
						setTimeout("$(this).removeAnalysisConf()",5000);*/
						showAlert();
					}
				}
			});
		}
		
		$.fn.getAnalysis = function(){
			$.ajax({
				url: '/ajax/budgetPlanner/getAnalysis.php',
				type: 'POST',
				data: 'ajax=1',
				cache: false,
				beforeSend: function(){
					if($("#analysis .section")){
						$("#analysis .section").fadeOut("slow");
					}
				},
				success: function(msg){
					if(msg != ""){
						$(msg).appendTo("#analysis");
					}
					
					$("#analysis #canHaveAnalysisConf p a").click(function(){
						$.scrollTo("#analysis");
						return false;
					})
				}
			});
		}
		
		//Function to show a summary for a section
		$.fn.showSummary = function(id, total){
			
			$.ajax({
				url: '/ajax/budgetPlanner/getSectionStatus.php',
				data: 'key='+id,
				type: 'POST',
				cache: false,
				success: function(msg){
					if(msg != ""){
					
						$('<div class=\'budgetCompleted\'>' + msg).appendTo('.'+id);
					
						$('.budgetCompleted a').click(function(){
							var thisClass = $(this).attr('class');
						
							$('.'+thisClass+' .budgetCompleted').fadeOut('slow',function(){
								$('.'+thisClass+' .budgetCompleted').remove();
								$('.'+thisClass+' .budget').slideDown('slow');
							});
							
							//Remove the cookie so we don't show the closed section next time
							$.cookie(id,null);
							
							return false;
						});
					}
				}
			});
		}
		
		//Gets the total for a section
		$.fn.getSectionTotal = function(id){
		
			var total = 0;
			
			$("."+id+ " input[type=text], ."+ id + " select").each(function(){
				val = $(this).val();
				if(val.length != 0){
					total += parseInt(val);
				}
			});
			
			return total;
		}
		
		
		if("form .formElement"){
			$("form .formElement select.change").each(function(){
				var id = $(this).attr("id");
	
				if($(this).val() == 0){
					$("#"+id+"Show").hide();
				}else{
					$("#"+id+"Show").show();
				}
			});
		
			$("form .formElement select.change").change(function(){
				var id = $(this).attr("id");
			
				if($(this).val() == 1){
					$("#"+id+"Show").show();
				}else{
					$("#"+id+"Show").hide();
				}
				
			});
			
			//Loop through the cookies we have and see if we need to close some sections
			$("form").each(function(){
				if($.cookie($(this).attr("class"))){
					var id = $(this).attr("class");
					var total = $(this).getSectionTotal(id);
					$(this).showSummary(id,total);
					$("."+id+" .budget").hide();
				}	
			});
		}
		
		
		//ToolTip elements, add the toolTip class for javascript users.
		$("form .formElement label span").addClass("toolTip");
		
		//Define tooltips
		$("form .formElement label span.maintenance").showToolTip("This is how much it costs to upkeep your property every year. This includes" +
		" cleaning products, boiler maintenance and household repairs"); 
		
		$("form .formElement label span.tvLicence").showToolTip("For most people this is going to be &pound;12 a month");
		
		$("form .formElement label span.out").showToolTip("This could be anything from family trip and days out to evenings out with friends");
		
		$("form .formElement label span.treatments").showToolTip("This will mainly include cosmetics and beauty treatments");
		
		$("form .formElement label span.e7").showToolTip("Economy 7 is an electricity tariff with different pricing structures according to the time of day. The energy you use during the night costs less, per unit, than energy used during the day with Economy 7");
		
		$("form .formElement label span.dependents").showToolTip("This could be either any children under 18 or a relative that lives with you");
		
		$("#formBudget form .budget .formElement input").keyup(function(event){
			
			var valid = 0;
			//numbers
			if(event.keyCode >= 48 && event.keyCode <= 57){
				valid = 1;
			}
			//numpad numbers
			if(event.keyCode >= 96 && event.keyCode <= 105){
				valid = 1;
			}
			//tab
			if(event.keyCode == 9){
				valid = 1;
			}
			//enter
			if(event.keyCode == 13){
				valid = 1;
			}
			
			if (valid == 0){
				var len = $(this).val().length;
				var newVal = $(this).val().substring(0,(len - 1));
				$(this).val(newVal);			
			}
			
		});
	
		$("form .formElement input.submit").click(function(){
			var url  = '';
	
			var id = $(this).attr("id");
			
			var total = $(this).getSectionTotal(id);
			
			$("."+ id + " input[type=text], ."+ id + " select").each(function(){
				var dilim = '';
				
				if(url.length == 0){
					dilim = '';
				}else{
					dilim = '&';
				}
				
				url += dilim + $(this).attr("name") +'='+$(this).val();	
			});
			
			url += '&ajax=1';
			
			 //Add the img and text
			$.ajax({
				url: '/ajax/budgetPlanner/submitSection.php',
				type: 'POST',
				data: url,
				cache: false,
				beforeSend: function(){
					if($('.'+id).find('.saveHolder')){
						$('.'+id).find('.saveHolder').remove();
					}
					
					$('<div class=\"saveHolder\"><div class=\"ajaxLoaderSmall\"></div><span>Please wait saving...</span></div>').appendTo($('.'+id));
					$('.'+id+' .submit').attr('disabled','true');
				},
				success: function(msg){
					if(msg == "ok"){
						$('.'+id).find('.saveHolder').fadeOut('slow',function(){
							$('.'+id+' .submit').removeAttr('disabled');
							$('.'+id+' .budget').slideUp("slow");
							
							$(this).showSummary(id,total);
				
							//Now update the summary counter
							$(this).updateSummaryCounter();
							
							$(this).canHaveAnalysis();
							
							//Set a cookie for this section
							$.cookie(id,"1");
						});
					}else{
						$('.'+id).find('.saveHolder').fadeOut('slow',function(){
							$('<div class=\"saveHolder\"><span>Save failed, please try again later</span></div>').appendTo($('.'+id));
						});
					}
				},
				error: function(msg){
					$('<div class=\"saveHolder\"><span>Save failed, please try again later</span></div>').appendTo($('.'+id));
				}
			});
			
			return false;
		});
	}	
});
