//
// load estimation javascript obj/functions
// Load profile by Kari Burman

// globals
// load daily schedule, assuming day leads to evening to night, pre-day is night
var midnight = 0;
var initial_hour = 0;
var day_begin = 7;
var day_hours = 11;
var evening_hours = 4;
var night_hours = 9;

function recalcLoadValues( class_name )
{
    var quantity = new Number ( jQuery( "input[name=quantity]."+class_name )[0].value );
    var power = new Number ( 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 ontime = new Number;
    ontime = day_ontime + evening_ontime + night_ontime;
    
    var totalpower = 0;
    var energy = 0;
    var energyKWh = 0;

    if( quantity >= 0 && power >= 0 )  {
        totalpower = quantity * power;
        jQuery( "td[field=totalpower]."+class_name )[0].innerHTML=totalpower ;
        if( ontime >= 0 ) {
        	energy = totalpower * ontime;
            jQuery( "td[field=energy]."+class_name )[0].innerHTML=energy ;
            energyKWh = energy / 1000.0;
            jQuery( "td[field=energyKWh]."+class_name )[0].innerHTML=energyKWh.toFixed(2) ;
        }
    }
    recalcLoadTotals();
}

function recalcLoadTotals( )
{
    var total_totalpower = 0;
    var total_energy = 0;
    var total_energyKWh = 0;
    var flt = 0;
    
 
    jQuery('td[field=totalpower]').each( function() {
        flt = parseFloat(this.innerHTML);
        if( isFinite( flt ) ) total_totalpower += flt;
    } );

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

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

    if( total_totalpower >= 0 ) jQuery('td#totalpower_total')[0].innerHTML = total_totalpower.toFixed(0);
    if( total_energy >= 0 ) jQuery('td#energy_total')[0].innerHTML = total_energy.toFixed(1);
    if( total_energyKWh >= 0 ) jQuery('td#energyKWh_total')[0].innerHTML = total_energyKWh.toFixed(1);
    
    // Warn users of high load and prevent them from running the simulation
    if( total_energyKWh > 30 ) {
  	alert('Warning, your load is: ' + total_energyKWh.toFixed(0) + ' kWh, which is above the 30 kWh limit \n for this tool. Unless you reduce the load the application will not run.');  
    	}
  

}

function createLoadProfile () 
{
    var load_hourly = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );

    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;
        
        //day_ontime = new Number ( jQuery( "input[name=day_ontime]."+class_name )[0].value );
        //evening_ontime = new Number( jQuery( "input[name=evening_ontime]."+class_name )[0].value );
        //night_ontime = new Number( jQuery( "input[name=night_ontime]."+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 hour;

        if( quantity >= 0 && power >= 0 )  {
            totalpower = quantity * power;
            //alert (quantity + ' and ' + power);

            // load daily schedule, assuming day leads to evening to night, pre-day is night
            if( day_ontime >= 0 ) {
            var initial_hour = midnight;
            for( hour = 0; hour < day_hours ; ++hour){
                    load_hourly[initial_hour + hour] += (totalpower*day_ontime)/(1000.0*day_hours);
                 
            }
            }

            if( evening_ontime >= 0 ) {
            initial_hour = (day_hours);
            for( hour = 0; hour < evening_hours ; ++hour  ){
                    load_hourly[initial_hour + hour] += (totalpower*evening_ontime/(1000.0*evening_hours));
            }
            }

            if( night_ontime >= 0 ) {
            initial_hour = (day_hours + evening_hours);
            for( hour = 0; hour < night_hours; ++hour  ){
                    load_hourly[initial_hour + hour] += (totalpower*night_ontime/(1000.0*night_hours));
            }
            }
        }
        //alert( class_name + ' load profile: ' + load_hourly );
    });

    //adjust load profile to start at day_begin
    var tempArr = new Array();
    tempArr = load_hourly.slice(24 - day_begin);
    for( var hour = 0; hour < day_begin; hour++ ) load_hourly.splice(0, 0, tempArr[hour] );
    return( load_hourly );
}


function exportLoadToXML( load_hourly )
{
    var loadXML = "<load_profile>";
    for( hour=0; hour < 24; ++hour  ){
            loadXML += '<load hr=\''+ hour + '\'>' + load_hourly[hour].toFixed(2) + '</load>';
    }
    loadXML += '</load_profile>';
  //  alert( 'load profile ' + loadXML );
    return loadXML;
}





function defaultDeviceValues(defClinic) {
	
	// reset all quantity and ontime values to zero
	jQuery('input[name=quantity]').each( function() {
			this.value = '0';
			
			tmp = jQuery('select[name=day_ontime].'+ this.className +':enabled')
			if (tmp[0]) {
				tmp[0].value = '0';
			}
			tmp = jQuery('select[name=evening_ontime].'+ this.className +':enabled')
			if (tmp[0]) {
				tmp[0].value = '0';
			}
			tmp = jQuery('select[name=night_ontime].'+ this.className +':enabled')
			if (tmp[0]) {
				tmp[0].value = '0';
			}
		} );
	
	
	if (defClinic != '') {
		// load clinic's defaults
		jQuery.each(defClinics[defClinic], function(i, val) {
				jQuery("input[name=quantity]."+i)[0].value = val[0];
				
				if (val[1]) {
					jQuery("select[name=day_ontime]."+i)[0].value = val[1];
				}
				if (val[2]) {
					jQuery("select[name=evening_ontime]."+i)[0].value = val[2];
				}
				if (val[3]) {
					jQuery("select[name=night_ontime]."+i)[0].value = val[3];
				}
			});
	}
	
	
	// recalc all
	jQuery('input[name=quantity]').each( function() {
			recalcLoadValues( this.className );
		});
}


//
// init page and callbacks

var defClinics= ["small", "medium", "large"];
		
defClinics["small"] = { 
							'Refrigerator-Vaccine'		:	[1], 
							'Refrigerator-Non-med'		:	[1], 
							'Centrifuge'				:	[2, 4,0,0], 
							'Microscope'				:	[2, 6,0,0], 
							'Blood_Chemical_Analyzer'	:	[1, 4,0,0], 
							'Hematology_Analyzer'		:	[1, 4,0,0], 
							'CD4_Machine'				:	[1, 4,0,0], 
							'Radio'						:	[1, 2,0,0], 
							'Tube-Fluorescents'			:	[4, 8,0,0], 
							'Desktop_Computer'			:	[1, 4,0,0] 
					};

defClinics["medium"] = { 
							'Refrigerator-Vaccine'		:	[2], 
							'Refrigerator-Non-med'		:	[2], 
							'Centrifuge'				:	[4, 4,0,0], 
							'Microscope'				:	[4, 6,0,0], 
							'Blood_Chemical_Analyzer'	:	[2, 4,0,0], 
							'Hematology_Analyzer'		:	[2, 4,0,0], 
							'CD4_Machine'				:	[2, 4,0,0], 
							'Radio'						:	[2, 2,0,0], 
							'Tube-Fluorescents'			:	[8, 8,0,0], 
							'Desktop_Computer'			:	[1, 4,0,0]
					};

defClinics["large"] = { 
							'Refrigerator-Vaccine'		:	[3], 
							'Refrigerator-Non-med'		:	[2], 
							'Centrifuge'				:	[4, 4,2,0],
							'Hematology-Mixer'			:	[1, 1,0,0],
							'Microscope'				:	[4, 6,0,0], 
							'Blood_Chemical_Analyzer'	:	[2, 4,0,0],
							'Water-Bath'				:	[1, 1,0,0],
							'Water_Purification'		:	[1, 1,0,0],
							'Hematology_Analyzer'		:	[2, 4,0,0], 
							'CD4_Machine'				:	[2, 4,0,0],
							'Sterilization_oven'		:	[1, 1,0,0],
							'Portable_X-ray'			:	[1, 1,0,0],
							'Radio'						:	[2, 2,0,0],
							'Lighting-CFL'				:	[2, 0,2,0],
							'Tube-Fluorescents'			:	[8, 8,2,1], 
							'Desktop_Computer'			:	[1, 4,0,0],
							'Printer'					:	[1, 1,0,0],
							'Air-Conditioner'			:	[1, 1,0,0]
					};




jQuery(document).ready(
    // inits after doc loads
    function() {
        
        jQuery('input[name=quantity]').each( function() {
            recalcLoadValues( this.className );
        });
        jQuery( "#device_form  input").change( function() {

            //recalculate for that class (row)
            recalcLoadValues( this.className );
        });
		jQuery( "#device_form  select").change( function() {

            //recalculate for that class (row)
            recalcLoadValues( this.className );
        });
		
		
    }
);

