/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



$(document).ready(function(){
	
	// Print
	$("#print_results").click(function () {
		window.print();
	});
	
	
    /**
	 * Author: http://www.netlobo.com/url_query_string_javascript.html
	 * Description: Retrieves variable from URL
	 * @param {Object} name
	 */
    //variable declarations
    //calculatorField is the main object
    //this object has different sub-objects which could be obtained by a literal string
    //each object has four variables
    // name: same as the id field of TextBox on front end
    // val: default value given by the client
    // text: will be set
    // attributes: decides what kind of data formatting for a textbox
    // tag: just for debugging
    var calculatorField = {
        //B5
        'distance_travelled_per_truck' : {
            name: 'distance_travelled_per_truck',
            val: "",
            text: "",
            attributes:  ["int","comma"],
            tag: 'B5'
        },
        //B6
        'number_of_trucks_in_fleet' : {
            name: 'number_of_trucks_in_fleet',
            val: "",
            text: "",
            attributes: ["int","none"],
            tag: 'B6'
        },
        //B7
        'price_of_diesel': {
            name: 'price_of_diesel',
            val: "",
            text: "",
            attributes : ["float","dollar"],
            tag: 'B7'
        },
        //B8
        'annual_fuel_increase': {
            name: 'annual_fuel_increase',
            val: "",
            text: "",
            attributes : ["int","percentage"],
            tag: 'B8'
        },
        //B9
        'def_price': {
            name: 'def_price',
            val: "",
            text: "",
            attributes : ["float","dollar"],
            tag: 'B9'
        },

        //B13
        'fuel_economy_2007': {
            name: 'fuel_economy_2007',
            val: "",
            text: "",
            attributes : ["float"],
            tag: 'B13'
        },
        //D13
        'fuel_economy_2010' : {
            name: 'fuel_economy_2010',
            val: "",
            text: "",
            attributes : ["float"],
            tag: 'D13',
            DOMElementType: 'span'
        },
        //D14
        'fuel_economy_improvement' : {
            name: 'fuel_economy_improvement',
            val: "",
            text: "",
            attributes : ["int","percentage"],
            tag: 'D14'
        },
        //B16
        'def_consumption_rate_2007' : {
            name: 'def_consumption_rate_2007',
            val: "",
            text: "",
            attributes : ["float","percentage"],
            tag: 'B16',
            DOMElementType: 'span'
        },
        //D16
        'def_consumption_rate_2010' : {
            name: 'def_consumption_rate_2010',
            val: "",
            text: "",
            attributes : ["float","percentage"],
            tag: 'D16',
            DOMElementType: 'span'
        },
        //B19
        'diesel_usage_2007' : {
            name: 'diesel_usage_2007',
            val: "",
            text: "",
            attributes : ["int","comma"],
            tag: 'B19',
            DOMElementType: 'span'
        },
        //D19
        'diesel_usage_2010' : {
            name: 'diesel_usage_2010',
            val: "",
            text: "",
            attributes : ["int","comma"],
            tag: 'D19',
            DOMElementType: 'span'
        },
        //B20
        'diesel_cost_2007' : {
            name: 'diesel_cost_2007',
            val: "",
            text: "",
            attributes : ["int","comma","dollar"],
            tag: 'B20',
            DOMElementType: 'span'
        },
        //D20
        'diesel_cost_2010' : {
            name: 'diesel_cost_2010',
            val: "",
            text: "",
            attributes : ["int","comma","dollar"],
            tag: 'D20',
            DOMElementType: 'span'
        },
        //B21
        'diesel_cost_total_2007' : {
            name: 'diesel_cost_total_2007',
            val: "",
            text: "",
            attributes : ["int","comma","dollar"],
            tag: 'B21',
            DOMElementType: 'span'
        },
        //D21
        'diesel_cost_total_2010' : {
            name: 'diesel_cost_total_2010',
            val: "",
            text: "",
            attributes : ["int","comma","dollar"],
            tag: 'D21',
            DOMElementType: 'span'
        },
        //B23
        'def_usage_2007' : {
            name: 'def_usage_2007',
            val: "",
            text: "",
            attributes : ["int"],
            tag: 'B23',
            DOMElementType: 'span'
        },
        //D23
        'def_usage_2010' : {
            name: 'def_usage_2010',
            val: "",
            text: "",
            attributes : ["int"],
            tag: 'D23',
            DOMElementType: 'span'
        },
        //B24
        'def_cost_2007' : {
            name: 'def_cost_2007',
            val: "",
            text: "",
            attributes : ["int","dollar"],
            tag: 'B24',
            DOMElementType: 'span'
        },
        //D24
        'def_cost_2010' : {
            name: 'def_cost_2010',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'D24',
            DOMElementType: 'span'
        },
        //B25
        'def_cost_total_2007' : {
            name: 'def_cost_total_2007',
            val: "",
            text: "",
            attributes : ["int","dollar"],
            tag: 'B25',
            DOMElementType: 'span'
        },
        //D25
        'def_cost_total_2010' : {
            name: 'def_cost_total_2010',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'D25',
            DOMElementType: 'span'
        },
        //B28
        'fuel_and_def_cost_2007' : {
            name: 'fuel_and_def_cost_2007',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'B28',
            DOMElementType: 'span'
        },
        //D28
        'fuel_and_def_cost_2010' : {
            name: 'fuel_and_def_cost_2010',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'D28',
            DOMElementType: 'span'
        },
        //B29
        'fuel_and_def_cost_total_2007' : {
            name: 'fuel_and_def_cost_total_2007',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'B29',
            DOMElementType: 'span'
        },
        //D29
        'fuel_and_def_cost_total_2010' : {
            name: 'fuel_and_def_cost_total_2010',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'D29',
            DOMElementType: 'span'
        },

        //B35
        'savings_first_single' : {
            name: 'savings_first_single',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'B35',
            DOMElementType: 'span'
        },
        //B37
        'savings_first_total' : {
            name: 'savings_first_total',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'B37',
            DOMElementType: 'span'
        },
        //C35
        'savings_second_single' : {
            name: 'savings_second_single',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'C35',
            DOMElementType: 'span'
        },
        //C37
        'savings_second_total' : {
            name: 'savings_second_total',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'C37',
            DOMElementType: 'span'
        },
        //D35
        'savings_third_single' : {
            name: 'savings_third_single',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'D35',
            DOMElementType: 'span'
        },
        //D37
        'savings_third_total' : {
            name: 'savings_third_total',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'D37',
            DOMElementType: 'span'
        },
        //E35
        'savings_fourth_single' : {
            name: 'savings_fourth_single',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'E35',
            DOMElementType: 'span'
        },
        //E37
        'savings_fourth_total' : {
            name: 'savings_fourth_total',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'E37',
            DOMElementType: 'span'
        },
        //F35
        'savings_fifth_single' : {
            name: 'savings_fifth_single',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'F35',
            DOMElementType: 'span'
        },
        //F37
        'savings_fifth_total' : {
            name: 'savings_fifth_total',
            val: "",
            text: "",
            attributes : ["int","dollar","comma"],
            tag: 'F37',
            DOMElementType: 'span'
        }
    };

    function setValues(obj){
        var i = 0;
        obj.val = obj.text;
        for(i=0; i<obj.attributes.length; i++){
            if(obj.attributes[i] == 'dollar')
                obj.val = stripDollar(obj.val);
            else if(obj.attributes[i] == 'comma')
                obj.val = stripComma(obj.val);
            else if(obj.attributes[i] == 'percentage')
                obj.val = stripPercentage(obj.val);
        }
    }

    //strips dollar sign from the string
    function stripDollar(str){
        var temp = str.split("$");
        if(temp.length>1)
            return temp[1];
        else
            return temp[0];
    }

    //strips comma from the string
    function stripComma(str){
        var temp = str.split(",");
        str = '';
        for(i=0;i<temp.length;i++)
            str += temp[i];
        return str;
    }

    //removes percentage from string
    function stripPercentage(str){
		return str.replace("%",'');
    }

    function setText(obj){
        var i = 0;
        obj.text = obj.val;
        for(i=0; i<obj.attributes.length; i++){
            if(obj.attributes[i] == 'dollar')
                obj.text = getDollar(obj.text);
            else if(obj.attributes[i] == 'comma')
                obj.text = getComma(obj.text);
            else if(obj.attributes[i] == 'percentage')
                obj.text = getPercentage(obj.text);
            else if(obj.attributes[i] == 'int')
                obj.text = getInt(obj.text);
            else if(obj.attributes[i] == 'float')
                obj.text = setDecimalPlace(obj.text);
        }
    }


    function getDollar(str){
        return '$' + str;
    }

    function getComma(str) {
        str = str.toString();
        var decimal = str.split(".");
        var returnStr = "";
        var i;
        var count = 0;
		var isCurrency = decimal[0].indexOf('$') !== -1;
		if(isCurrency)
			decimal[0] = decimal[0].replace('$', '');

        if(decimal[0].length > 3) {
            str = decimal[0].split("");
            for(i=str.length-1; i>-1; i--) {
                if(count > 2) {
                    count = 0;
                    returnStr =  ',' + returnStr;
                }
                returnStr = str[i] + returnStr;
                count++;
            }
            if(decimal.length > 1)
				returnStr += '.' + decimal[1];
            if(isCurrency)
				returnStr = '$' + returnStr;
			return returnStr;
        }
        else {
			return str;
		}
    }

    function getPercentage(str){
        return str = str + '%';
    }

    function getInt(str){
        return parseInt(str);
    }
		
    function setDecimalPlace(num){
        num = num.toString()
        if( num.indexOf('.') != -1 )
            return Number(num).toFixed(2);
        else
            return Number( num.toString() + ".00" );
    }
	
    //updates text variable of objects from val variable of that object
    function updateTextFromValForAll(){
        for(field in calculatorField){
            setText(calculatorField[field]);
        }
    }

    //grabs front end text field values and sets as object variables text and val
    //we take care of data stripping here
    function setFieldsForAll(){
        for(field in calculatorField){
            //row set up of text == the following line just takes whatever you type in the text box
            if( calculatorField[field].DOMElementType == 'span' ){
                calculatorField[field].text = $("span#"+calculatorField[field].name).html();
                //console.log('DOMElement: span ' +  'tag: ' + calculatorField[field].tag + ' text: ' + calculatorField[field].text );
            }
            else{
                calculatorField[field].text = $("input#"+calculatorField[field].name).val();
                //console.log('DOMElement: text ' +  'tag: ' + calculatorField[field].tag + ' text: ' + calculatorField[field].text );
            }
            //strips of the text and makes it a proper value
            setValues(calculatorField[field]);
            //formats the value into a specific text
            setText(calculatorField[field]);
            //console.log('tag: ' + calculatorField[field].tag + ' text: ' + calculatorField[field].text + ' val:' + calculatorField[field].val + '\n');
        }
    }

        
    //gets object field values like val and text and sets them on the front end text boxes
    function updateFrontEnd(){
        for(field in calculatorField){
            if( calculatorField[field].DOMElementType == 'span' )
                $("span#"+calculatorField[field].name).html(calculatorField[field].text);
            else
                $("input#"+calculatorField[field].name).val(calculatorField[field].text);
        }
    }

    //prints all the object field values in case of debugging
        function printAllFields(){
            var print = ' ';
            for(field in calculatorField){
                print = print +  'tag: ' + calculatorField[field].tag + ' text: ' + calculatorField[field].text + ' val:' + calculatorField[field].val + '\n';
            }
            //console.log(print);
            alert(print);
        }

    function performOperations(){
        // D13
		calculatorField['fuel_economy_2010'].val = Number(calculatorField['fuel_economy_2007'].val) + (calculatorField['fuel_economy_2007'].val * (calculatorField['fuel_economy_improvement'].val / 100));
		// B19
		calculatorField['diesel_usage_2007'].val = calculatorField['distance_travelled_per_truck'].val / calculatorField['fuel_economy_2007'].val;
		// D19
		calculatorField['diesel_usage_2010'].val = calculatorField['distance_travelled_per_truck'].val / calculatorField['fuel_economy_2010'].val;
		
		// B20
		calculatorField['diesel_cost_2007'].val = Math.round(calculatorField['diesel_usage_2007'].val * calculatorField['price_of_diesel'].val);
		// D20
		calculatorField['diesel_cost_2010'].val = Math.round(calculatorField['diesel_usage_2010'].val * calculatorField['price_of_diesel'].val);
		// B21
		calculatorField['diesel_cost_total_2007'].val = calculatorField['diesel_cost_2007'].val * calculatorField['number_of_trucks_in_fleet'].val;
		// D21
		calculatorField['diesel_cost_total_2010'].val = calculatorField['diesel_cost_2010'].val * calculatorField['number_of_trucks_in_fleet'].val;

		// B23
		calculatorField['def_usage_2007'].val = calculatorField['diesel_usage_2007'].val * calculatorField['def_consumption_rate_2007'].val;
		// D23
		calculatorField['def_usage_2010'].val = Math.round( calculatorField['diesel_usage_2010'].val * (calculatorField['def_consumption_rate_2010'].val / 100) );
		
		// B24
		calculatorField['def_cost_2007'].val = calculatorField['def_usage_2007'].val * calculatorField['def_price'].val;
		// D24
		calculatorField['def_cost_2010'].val = Math.ceil( calculatorField['def_usage_2010'].val * calculatorField['def_price'].val );
		// D24
		calculatorField['def_cost_total_2010'].val = calculatorField['def_cost_2010'].val * calculatorField['number_of_trucks_in_fleet'].val;

		// B28
		calculatorField['fuel_and_def_cost_2007'].val = calculatorField['diesel_cost_2007'].val + calculatorField['def_cost_2007'].val;
		// D28
		calculatorField['fuel_and_def_cost_2010'].val = calculatorField['diesel_cost_2010'].val + calculatorField['def_cost_2010'].val;
		// B29
		calculatorField['fuel_and_def_cost_total_2007'].val = calculatorField['diesel_cost_total_2007'].val + Number(calculatorField['def_cost_total_2007'].val);
		// D29
		calculatorField['fuel_and_def_cost_total_2010'].val = calculatorField['diesel_cost_total_2010'].val + calculatorField['def_cost_total_2010'].val;

		var fuelRatePrc = (calculatorField['annual_fuel_increase'].val / 100),
			price_diesel_1 = calculatorField['price_of_diesel'].val, 
			price_diesel_2 = Number(price_diesel_1) + Number((price_diesel_1 * fuelRatePrc) ), 
			price_diesel_3 = Number(price_diesel_2) + Number((price_diesel_2 * fuelRatePrc) ), 
			price_diesel_4 = Number(price_diesel_3) + Number((price_diesel_3 * fuelRatePrc) ), 
			price_diesel_5 = Number(price_diesel_4) + Number((price_diesel_4 * fuelRatePrc) ),
			price_scr_1 = (calculatorField['diesel_usage_2010'].val * price_diesel_1 + calculatorField['def_usage_2010'].val * calculatorField['def_price'].val) * calculatorField['number_of_trucks_in_fleet'].val,
			price_epa_1 = (calculatorField['diesel_usage_2007'].val * price_diesel_1 + calculatorField['def_usage_2007'].val * calculatorField['def_price'].val) * calculatorField['number_of_trucks_in_fleet'].val,
			price_scr_2 = (calculatorField['diesel_usage_2010'].val * price_diesel_2 + calculatorField['def_usage_2010'].val * calculatorField['def_price'].val) * calculatorField['number_of_trucks_in_fleet'].val,
			price_epa_2 = (calculatorField['diesel_usage_2007'].val * price_diesel_2 + calculatorField['def_usage_2007'].val * calculatorField['def_price'].val) * calculatorField['number_of_trucks_in_fleet'].val,
			price_scr_3 = (calculatorField['diesel_usage_2010'].val * price_diesel_3 + calculatorField['def_usage_2010'].val * calculatorField['def_price'].val) * calculatorField['number_of_trucks_in_fleet'].val,
			price_epa_3 = (calculatorField['diesel_usage_2007'].val * price_diesel_3 + calculatorField['def_usage_2007'].val * calculatorField['def_price'].val) * calculatorField['number_of_trucks_in_fleet'].val,
			price_scr_4 = (calculatorField['diesel_usage_2010'].val * price_diesel_4 + calculatorField['def_usage_2010'].val * calculatorField['def_price'].val) * calculatorField['number_of_trucks_in_fleet'].val,
			price_epa_4 = (calculatorField['diesel_usage_2007'].val * price_diesel_4 + calculatorField['def_usage_2007'].val * calculatorField['def_price'].val) * calculatorField['number_of_trucks_in_fleet'].val,
			price_scr_5 = (calculatorField['diesel_usage_2010'].val * price_diesel_5 + calculatorField['def_usage_2010'].val * calculatorField['def_price'].val) * calculatorField['number_of_trucks_in_fleet'].val,
			price_epa_5 = (calculatorField['diesel_usage_2007'].val * price_diesel_5 + calculatorField['def_usage_2007'].val * calculatorField['def_price'].val) * calculatorField['number_of_trucks_in_fleet'].val;

		calculatorField['savings_first_single'].val = price_epa_1 - price_scr_1;
		calculatorField['savings_first_total'].val = calculatorField['savings_first_single'].val;
		calculatorField['savings_second_single'].val = Math.round(price_epa_2 - price_scr_2);
		calculatorField['savings_second_total'].val = calculatorField['savings_first_total'].val + calculatorField['savings_second_single'].val;
		calculatorField['savings_third_single'].val = price_epa_3 - price_scr_3;
		calculatorField['savings_third_total'].val = calculatorField['savings_second_total'].val + calculatorField['savings_third_single'].val;
		calculatorField['savings_fourth_single'].val = price_epa_4 - price_scr_4;
		calculatorField['savings_fourth_total'].val = calculatorField['savings_third_total'].val + calculatorField['savings_fourth_single'].val;
		calculatorField['savings_fifth_single'].val = price_epa_5 - price_scr_5;
		calculatorField['savings_fifth_total'].val = calculatorField['savings_fourth_total'].val + calculatorField['savings_fifth_single'].val;
		
        updateTextFromValForAll();
    }

    $('#fuel_calculator form input[type=text]:enabled').change(setAllFields);
    $('#calculate_results').click(setAllFields);
	
    function setAllFields () {
        //printAllFields();
        //console.log('setting all fields');
        setFieldsForAll(); //sets all the text and value fields for all the objects
        //console.log('printing all fields');
        //printAllFields();
        //console.log('performing operations');
        performOperations(); //performs the calculations
        //printAllFields();
        //console.log('updating front end');
        updateFrontEnd(); //updates the front end text fields
    }
	
    setAllFields();
});
