// JavaScript Document
$(document).ready(function() {
	
	//change styling of menu item to active page
	menu_id = $('ul.nav a[href="' + document.location.search + '"]');
	if(typeof menu_id != "undefined"){
		menu_id.first().toggleClass("hovered");
	}
	
	
	
	//populate forms with available data
	populateForms();
	
	//for clicks or keyups always save data to session
	$('.sim-form').bind('keyup click', function(e){
				   preConfigureInput();
                   saveData();  
     });

	
	$(".sim-btn").click(function(event) {
		// prevent going to the page right away
		event.preventDefault();
		
		//pre fill some fields based on other values if necessary
		preConfigureInput();
		
		// save data to the current session
		saveData();
		
		// move to the requested page
		url = event.target.getAttribute("href");
		//document.location = window.location.protocol + '//' + window.location.host + window.location.pathname + url;
		document.location = url;
		
	});
	
	//this will pre-fill all form elements using the stored session variables
	function populateForms() {
		
		//return the data in the session
		sessionData = returnSessionData();
		
		if(sessionData != null && sessionData != '' && typeof sessionData != "undefined") {
		
			//loop through form
			$( ".sim-form" ).each(function( ) {
				
				 	formIdValue = $( this ).attr('id'); 
				 	//console.log(formIdValue);
				 	//console.log(sessionData);
					
					//loop through all input elements of form
					
					$( this).find('input').each(function(index) {
					
						//retrieve input name
						nameAttributeValue = $( this ).attr('name');
						//retrieve the session value if it exists and set the dom element value
				
						if(typeof formIdValue !="undefined" && typeof sessionData[formIdValue] != "undefined" && typeof sessionData[formIdValue][nameAttributeValue] != "undefined") {
				
							if(nameAttributeValue == "mixture_ratio") {
								$( "#mixture_ratio" ).slider( "value",sessionData[formIdValue][nameAttributeValue]);
							} else {
								$('[name="' + nameAttributeValue + '"]').val(sessionData[formIdValue][nameAttributeValue]);	
							}
							
							
						}
						
					});//end input loop
					
					//loop through all select elements of form
					$( this).find('select').each(function(index) {
					
						//retrieve input name
						nameAttributeValue = $( this ).attr('name');
						//retrieve the session value if it exists and set the dom element value
				
						if(typeof sessionData[formIdValue][nameAttributeValue] != "undefined") {
							$('[name="' + nameAttributeValue + '"]').val(sessionData[formIdValue][nameAttributeValue]);
						}
						
					});//end input loop
					

			});//end forms loop
		};
		
	}
	
	
	
	// save data to php session 
	function saveData() {

		//console.log('saving');
		$( ".sim-form" ).each(function() {
			
			url = "libs/cooltool/ps/save2session.php"
			formid = $( this ).attr('id'); 
			data = $( this ).serialize();
			isvalid = $( this ).valid(false);
			data += '&form_id=' + formid + '&isvalid=' + isvalid;	
			
			 $.ajax({
        		type: "POST",
        		url : url,
        		async: true,  
        		data: data,
				dataType: 'json',
        		success: function(data){
        			//console.log(data);
            		
        	}
    		});
		
			
			//Send the data using post 
  			var posting = $.post( url, data );
  			posting.success(function(data) {
  				//console.log(data);
             	
  			});
			posting.done(function(data) {
				//console.log(data);
             	
  			});
  			
			
		});
		
		
	}//End function saveData
	

	// function to return sim data from the session
	function returnSessionData() {
		
		url = "libs/cooltool/ps/getfromsession.php";
		var sessionData;
		//retrieve data from session
	    $.ajax({
        	type: "POST",
        	url : url,
        	async: false,  
        	data: {'nada' : ''},
			dataType: 'json',
        	success: function(data){
            	sessionData = data;
            	//console.log(sessionData);
        	}
    	});
		
		return sessionData;
		
		
	}
	
	
	function preConfigureInput() {
		
		//console.log('preconfigure');
	
		//check if these elements exist and if so set the hidden values
		if ($("#fin_width").length > 0) {
			//Set the channel width = fin width
			$("#channel_width").val($("#fin_width").val());
		}
		if ($("#material_heater").length > 0) {
			//Set the heater material = cold plate material
			$("#material_heater").val($("#material_cold_plate").val());	
		}
		if ( $("#heat_power").length > 0) {
			//this one requires special care since it is based on other form values.
			//to set it properly we will retrieve the heated_width and heated_length from the session data
			var sessionData = returnSessionData();

			//console.log(sessionData);
			if(typeof sessionData !="undefined" && sessionData != '' && sessionData.hasOwnProperty('geom') && sessionData.geom.hasOwnProperty('heated_width') &&
				sessionData.geom.hasOwnProperty('heated_length')) {
				if(sessionData.geom.heated_width.length > 0 && sessionData.geom.heated_length.length > 0 ) {
					//Calculate the heat footprint value in W/cm^2 from heat power and cold plate area
					var heat_intensity = $("#heat_power").val()/( 0.1*0.1*sessionData.geom.heated_width*sessionData.geom.heated_length );
					$("#bc_val_heat_footprint").val(heat_intensity);
				}
			}
		}
		
		
		
		
	}
	

	
	
});