
var calculationCanceled = false;

function requestHomerRun() {
	
	calculationCanceled = false;
	
	// *** Need to validate the inputs before sending them to the server


	// Check that the map was clicked


	// Create XML string to be sent to VincentListener process

    var xmlRequest = "<request action='clinic_optimize'>";

    //gather inputs from page
    var load = new Array();
    load = createLoadProfile();
    xmlRequest += exportLoadToXML( load );

    //system components to consider

    // Components(pv, inverter, batteries, generator)
    var pv = document.getElementById( 'pvcost' ).value;
    var battery = document.getElementById( 'batterycost' ).value;
    var batterytype = document.getElementById( 'batterytype' ).value;
    var fueltype = document.getElementById( 'fueltype' ).value;
    
    // Grid
    var grid_start = document.getElementById( 'grid_start_hour' ).value;
    var grid_duration = document.getElementById( 'grid_duration_hours' ).value;
    //var grid_breaker_size = document.getElementById( 'grid_breaker_size' ).value;
    var grid_price = document.getElementById( 'grid_price' ).value;
    
    // Financial
    var interest_rate = document.getElementById( 'interestrate' ).value;
    
    // Solar resource and location
    var hiddenelement = document.getElementById( 'input_hiddenelement' ).value;
    var location = document.getElementById( 'location' ).innerHTML;
    var timezone = document.getElementById( 'time_zone' ).value;
    
    // ongoing costs (o/m, fuel)
    var diesel = document.getElementById( 'dieselcost' ).value;
    
    // Total max power in Watt
    var total_power = document.getElementById( 'totalpower_total').innerHTML;
     
    
    //create xml request
 
    xmlRequest += '<fuel type=\'' + fueltype.toString() + '\'>';
    xmlRequest += '<price>' + diesel.toString() + '</price>';
    xmlRequest += '</fuel>';
    xmlRequest += '<battery><price>' + battery.toString() + '</price>';
    xmlRequest += '<batterytype>' + batterytype.toString() + '</batterytype></battery>';
    xmlRequest += '<pv><price>' + pv.toString() + '</price></pv>';
    xmlRequest += '<grid>';
    xmlRequest += ' <starthour>' + grid_start.toString() + '</starthour>';
    xmlRequest += ' <duration>' + grid_duration.toString() + '</duration>';
    //xmlRequest += ' <breaker_size>' + grid_breaker_size.toString() + '</breaker_size>';
    xmlRequest += ' <grid_price>' + grid_price.toString() + '</grid_price>';
    xmlRequest += '</grid>';
    xmlRequest += '<total_power>' + total_power.toString() + '</total_power>';
    
    
    
    // Interest rate
    //xmlRequest += '<economics>';
    xmlRequest += '<economics><annual_real_interest_rate>' + interest_rate.toString() + '</annual_real_interest_rate></economics>';
    //xmlRequest += '</economics>';
    
    // Location
    xmlRequest += '<location><latlon>' + location.toString() + '</latlon></location>';
    
    // Time Zone
    xmlRequest += '<time_zone>' + timezone.toString() + '</time_zone>';
    
    // Solar radiation data
	//xmlRequest += '<solar_resource><data><monthly><monthly_average_radiation>';
	//xmlRequest += '<float>' + solar_resource.toString() + '</float>';
	//xmlRequest += '</monthly_average_radiation></monthly></solar_resource>';			
        //xmlRequest += solar_resource.toString();
        //alert( 'Solar Resource:' + hiddenelement.toString());
        //alert( 'Solar Resource:' + hiddenelement.valueOf());
        xmlRequest += hiddenelement.valueOf();
        //alert( 'Solar Resource:' + hiddenelement.toString());
    
    
    // insert devices array
    xmlRequest += '<devices>';
    
    jQuery('td[field=appliance]').each( function() {
			var class_name = this.className; 
			var quantity = jQuery( 'input[name=quantity].'+class_name )[0].value;
			var power = jQuery( "input[name=power]."+class_name )[0].value;
			
			var day_ontime = new Number ( jQuery( "select[name=day_ontime]."+class_name )[0].value );
			var evening_ontime = new Number( jQuery( "select[name=evening_ontime]."+class_name )[0].value );
			var night_ontime = new Number( jQuery( "select[name=night_ontime]."+class_name )[0].value );
					
			var total_ontime = day_ontime + evening_ontime + night_ontime;
			
			// only add if quantity, power, and total ontime are all greater than zero
			if( quantity > 0 && power > 0 && total_ontime > 0)  {
			
				var name = jQuery( "input[name=othername]."+class_name );
				if (name[0]) {
					xmlRequest += '<device key=\''+ class_name +'\' name=\''+ name[0].value +'\'>';
				} else {
					xmlRequest += '<device key=\''+ class_name +'\'>';
				}
				
				xmlRequest += '<qty>'+ quantity +'</qty>';
				xmlRequest += '<pwr>'+ power +'</pwr>';
				
				xmlRequest += '<ot_day>'+ day_ontime +'</ot_day>';
				xmlRequest += '<ot_evening>'+ evening_ontime +'</ot_evening>';
				xmlRequest += '<ot_night>'+ night_ontime +'</ot_night>';
				
				xmlRequest += '</device>';
			}
		});
    
    
    xmlRequest += '</devices>';
    
    
    

    //send to server for processing
    //var link = document.getElementById( 'result_display_link' );
    //link.style.display = 'none';
    //link.innerHTML = '';
    //link.href = '#';

    //var msg = document.getElementById( 'result_display_msg' );
    //msg.style.display = 'inline';
    //msg.innerHTML = '<strong>Status: <font color="red">Running HOMER on the server...<IMG SRC="http://nreldev.nrel.gov/poweringhealth/inc/images/wait1.gif">...please be patient, it could take a few minutes.</font></strong>';
    

	// Initialize variables
	var longitude = 0;
		
	// Get the longitude from the web page
	
	longitude = location.toString();
		//alert( longitude );
	longitude_array = longitude.split(",");
		//alert( longitude_array[1] );
	longitude = longitude_array[1];
	
	calc_timezone_offset_hours = longitude / 15;
	//alert('Calculated hours offset (longitude/15): ' + calc_timezone_offset_hours);

	// Get time zone offset from web page
	timezoneoffset = document.getElementById('time_zone').value
	//alert( 'Time zone offset: ' + timezoneoffset);

	//calculatedoffsetdegrees = timezoneoffset * 15;
	//alert( 'Calculated offset degrees: ' + calculatedoffsetdegrees );

	//Calculate difference between longitude and standard meridian implied by time zone on web page
	//degrees_error = calculatedoffsetdegrees - longitude;
	time_offset_error = timezone - calc_timezone_offset_hours;
	//alert('Hours error: ' + time_offset_error);

   
	// Need to include checking for high load and preventing
	// user from running simulation, just like with the missing location check

	var total_energyKWh = 0;

	jQuery('td[field=energyKWh]').each( function() {
			flt = parseFloat(this.innerHTML);
			if( isFinite( flt ) ) total_energyKWh += flt;
		});

	if(total_energyKWh >= 0) {
		jQuery('td#energyKWh_total')[0].innerHTML = total_energyKWh.toFixed(1);
	}
    
    
    xmlRequest += '<total_energy>' + jQuery('td#energyKWh_total')[0].innerHTML + '</total_energy>';
    
    xmlRequest += '</request>';
    
	// Validate inputs before sending request
	// Check that a location is selected
	// Check that load is not > 30 kWh
	
	//alert(hiddenelement.toString());
	
	if (location.toString() == '') {
		// No location found
		alert('No location indicated! \n Please click the map.');
	
	} else if (total_energyKWh <= 0 ) {
      	alert('Warning, your load is zero. Please add some devices \nfor your clinic to create a realistic load profile.');  
	
	} else if (total_energyKWh > 30 ) {
      	alert('Warning, your load is: ' + total_energyKWh.toFixed(0) + ' kWh, which is above the 30 kWh limit \n or this tool. Unless you reduce the load the application will not run.');  
		
	} else if (time_offset_error > 2) {
      	alert('Warning, the timezone error is: ' + time_offset_error + ' hours, which is above the limit \nfor this tool. Please either adjust your longitude or time zone.');  			
	
	} else if (hiddenelement.toString() == 'undefined' || hiddenelement.toString() == '') {
		// No Fridge data found
		alert('No Fridge solar data available for location! \nPlease select another location.');
	
	} else {
		// Location found
		//alert('Location found');
		//alert('The location is :' + location);
		
		// show modal overlay
		openModal();
		
		//msg.innerHTML = '<strong>Status: <font color="red">Running HOMER on the server...<IMG SRC="/inc/images/wait1.gif">...please be patient, it could take a few minutes.</font></strong>';
		sendHomerRequest(xmlRequest);
	}

}

function processHomerResponse(response)  {

    //alert( 'response: ' + response.responseText );

    var type = "unknown";    
    var idx = response.responseText.search(/:/);
    if (idx > 0) {
    	type = response.responseText.slice(0, idx);
    }
    //alert( 'type: ' + type );

    if (type == "http") {
    	location.href = response.responseText;
    
    } else if(type == "Error") {
    	closeModal();
    	alert(response.responseText);
    }
}


function sendHomerRequest(xmlString) {

	var url = "sim/simHomer_clinic.php";
	//alert( 'var url: ' + url ); 
	new Ajax.Request(url, {   
			method:'post',
			parameters:'xml='+encodeURIComponent(xmlString),
			onSuccess: function(request) {
				if (!calculationCanceled) {
					processHomerResponse(request);
				}
			},
			onFailure: function() {
				if (!calculationCanceled) {
					alert('Error: Optimization call to HOMER failed [simJS.sendHomerRequest.onFailure]');
				}
			}
		} );

}



function openModal() {
	var viewport = document.viewport.getDimensions();
	var bodyElm = $('pageContainer');
	if (viewport.height > bodyElm.getHeight()) {
		$('modalBlackOut').setStyle({width: viewport.width + 'px',height: viewport.height + 'px'});
	} else {
		$('modalBlackOut').setStyle({width: viewport.width + 'px',height: bodyElm.getHeight() + 'px'});
	}
	
	//var offset = $('pageContainer').cumulativeScrollOffset();
	var top = 300; //offset.top + 137;
	$('modalOuterContainer').setStyle({top: top + 'px'});
	
	$('modalMain').show();
	$('modalBlackOut').show();
	$('modalOuterContainer').show();
}

function closeModal() {
	calculationCanceled = true;
	
	$('modalMain').hide();
	$('modalBlackOut').hide();
	$('modalOuterContainer').hide();
}
