var IsR,IsB,Mu,Mb,BC,Tr,Di,E1,E2,S105,S120,S125,S115,S108,FBR1,FBR2,B1S,PDIFF,KWC

var mochaPath = '/Images/calculator/icon_coffee.gif';
var pizzaPath = '/Images/calculator/icon_pizza.gif';
var treeLgPath = '/Images/calculator/icon_lg_tree.gif';
var treeMedPath = '/Images/calculator/icon_med_tree.gif';
var treeSmPath = '/Images/calculator/icon_sm_tree.gif';

var mochaCost = 3.00;           //Cost for a latte
var mochaMax = 8;               //Max amount of lattes to display
var pizzaCost = 1.50;           //Cost for a slice of pizza
var pizzaMax = 8;               //Max amount of pizza slices to display
var lgTreeMax = 8;              //Max number of large tree display 
var lgTreeNu = 1000;            //Number of trees represented to large tree graphic
var medTreeNu = 100;            //Number of trees represented to small medium graphic
var smTreeNu = 10;              //Number of trees represented to small tree graphic 
var distanceToNY = 2896;        //Driving distance from Portland to New York
var MuMin = 1;                  //Monthly usage must be greater than or equal to this number
var MbMin = 10.87;              //Monthly bill must be greater than this number
// NOTE: PGE Supplys "monthly" usuage for 1 kWh in spreadsheet.  Make sure to multiple that by 12 to get annual number for GreenSource
var GSC02 = 10.824;             //CO2 offset for green source, old value: 13.596
var GSMD = 12.024;              //Miles driven for green source, old value: 15.108
var GSTP = 0.648;               //Trees planted for green source, old value: 0.816
// END NOTE
var CWC02 = 2164.8;             //CO2 offset for clean wind, old value: 2719.2
var CWMD = 2405.33;            //Miles driven for clean wind, old value: 3021.333
var CWTP = 130.018;             //Trees planted for clean wind, old value: 163.315
var HABITATSUPPORTCOST = 2.5    //Habitat support cost
var CWUKW = 200;                //Amount of KwH for 1 unit of clean wind

     
//Register the cluetip
$(document).ready( function() { $('a.hoverlink').cluetip({splitTitle: '|', arrows: false, cluetipClass: 'jtip'}); } );

//Used to add commas to the number
function formatNumber(number)
{
    number = number + '';    
    var np = number.split('.');
    n = np[0] + '';
    newnumber = '';
    count = 1;    
    for (var i = (n.length); i > 0; i--)
    {            
        newnumber = n.charAt(i - 1) + newnumber;        
        if (count%3 == 0 && count != n.length)
        {
            newnumber = ',' + newnumber;
        }
        count++;
    }
    if (np.length == 2)
        newnumber += '.' + np[1];
        
    return newnumber
}

//Initialize the global variables
function InitializeVariables()
{
    BC = (IsR * 10) + (IsB * 12);           //Basic Charge 1 phase
    Tr = (IsR * 0.212) + (IsB * 0.171);     //Transmission
    Di = (IsR * 2.897) + (IsB * 6.404);     //Distribution/Energy
    E1 = (IsR * 5.124) + (IsB * 2.744);     //Distribution/Energy Block 1
    E2 = (IsR * 6.899) + (IsB * 0.571);     //Distribution/Energy Block 2
    PPCLIA = 0.0344;                        //Estimated PPC & LIA amounts (Business only)
    S102 = (IsR * -0.625)                   //Schedule 102 (Residential only)
    S105 = (IsR * -0.007) + (IsB * -0.006); //Schedule 105
    S108 = (IsR * 0.03) + (IsB * 0.03);     //Schedule 108
    S109 = (IsR * 0.097) + (IsB * 0.093);   //Schedule 109
    S110 = (IsR * 0.003) + (IsB * 0.003);   //Schedule 110
    S111 = (IsR * 0.121) + (IsB * 0.138);   //Schedule 111
    S115 = (IsR * 0.50)  + (IsB * 0.050);   //Schedule 115
    S120 = (IsR * 0.000) + (IsB * 0.000);   //Schedule 120
    S123 = 0;                               //Schedule 123 (Placeholder?)
    S125 = (IsR * 0.000) + (IsB * -0.000);  //Schedule 125
    S126 = (IsR * -0.110) + (IsB * -0.110); //Schedule 126
    S140 = (IsR * -0.119) + (IsB * -0.119); //Scheudle 140
    FBR1 = (Tr + Di + E1 + S102 + S105 + S109 + S110 + S111 + S120 + S123 + S125 + S126 + S140); //First block energy rate
    FBR2 = (Tr + Di + E2 + S102 + S105 + S109 + S110 + S111 + S120 + S123 + S125 + S126 + S140); //Second block energy rate
    B1S = (IsR * 250) + (IsB * 5000);       //Block 1 size
    KWC = (IsR * 3.50) + (IsB * 3.50);      //Clean wind cost
}

//Used to calculating monthly bill and usage    
function Calculate(item)
{
    IsR = document.getElementById('rdoTypeResidential').checked;
    IsB = document.getElementById('rdoTypeBusiness').checked;
    
    InitializeVariables(); 
                             
    switch(item.id.toLowerCase())
    {                   
        case 'txtmonthlybill':
            CalculateMu();
            break; 
        case 'rdotyperesidential':
        case 'rdotypebusiness':             
            if ((Mb + '') != 'undefined')           
                CalculateMb(true);
            break;
        default:
            CalculateMb();
            break;
    }        
}

//Calculation of estimated Mu, user provide Mb
function CalculateMu()
{       
    var changeValue = document.getElementById('txtMonthlyBill').value; 
          
    if (changeValue == '' || Mb == changeValue) 
        return;    
    else
    {
        Mb = changeValue;
    }

    var H7 = Mb;
    var H8 = (H7 - (IsR * S115));
    var H8a = (IsR * S108) + (IsB * PPCLIA);
    var H9 = H8 - (H8 / (1 + H8a) * H8a);
    var H10 = H9 - BC;
    var H11 = FBR1 / 100 * B1S;
    var H12 = ((H10 - H11) > 0) * (H10-H11);
    var H13 = ((H11 > H10) * (H10 / FBR1 * 100)) + ((H11 <= H10) * B1S);
    var H14 = (H12 != 0) * Math.round(H12 / FBR2 * 100);
    var H15 = H13 + H14;
    
    Mu = H15;
    
    
    document.getElementById('txtMonthlyUsage').value = Math.round(Mu, 0);   
}

//Calculation of estimated Mb, user provide Mu
function CalculateMb(force)
{
    var changeValue = document.getElementById('txtMonthlyUsage').value;      
     
    if (!force && (changeValue == '' || Mu == changeValue)) 
        return;     
    else
    {
        Mu = changeValue;
    }
   
    Mb = RetreiveMb(Mu);
    document.getElementById('txtMonthlyBill').value = Mb.toFixed(2);    
}

//Retreive monthly billing value
function RetreiveMb(monthlyUsage)
{
    var TrC = monthlyUsage * Tr / 100;
    var DiC = monthlyUsage * Di / 100;
    var E1C = ((monthlyUsage <=  B1S) * (monthlyUsage * E1 / 100)) + ((monthlyUsage > B1S) * (B1S * E1 / 100));
    var E2C = ((monthlyUsage > B1S) * ((monthlyUsage - B1S) * E2 / 100));
    var S102C = monthlyUsage * S102 / 100;
    var S105C = monthlyUsage * S105 / 100;
    var S109C = monthlyUsage * S109 / 100;
    var S110C = monthlyUsage * S110 / 100;
    var S111C = monthlyUsage * S111 / 100;
    var S120C = monthlyUsage * S120 / 100;
    var S123C = monthlyUsage * S123 / 100;
    var S125C = monthlyUsage * S125 / 100;
    var S126C = monthlyUsage * S126 / 100;
    var S140C = monthlyUsage * S140 / 100;
    var MbST = BC + TrC + DiC + E1C + E2C + S102C + S105C + S109C + S110C + S111C + S120C + S123C + S125C + S126C + S140C;
    //var S108C = MbST * S108;
    var S108C = (MbST - S109C) * S108;

    return MbST + ((IsB * monthlyUsage * S115 / 100) + (IsR * S115)) + S108C;
}

//Validate monthly usage and billing
function IsValid()
{
    if (Mu < MuMin)
    {
        alert('Please enter a value greater than ' + MuMin + ' form Monthly Usage');
        return false;
    }
    if (Mb < MbMin)
    {
        alert('Please enter a value greater than ' +  MbMin + ' for Monthly Bill');
        return false;
    }
    return true;
}

//Populate result columns
function RunGreenCalculation()
{
    if (!IsValid()) return;
    
    var GSC = 0,CWC = 0,HSC = 0,TGC = 0, C02 = 0, MD = 0, TP = 0;
    var greenSource = document.getElementById('rdoGreenSourceYes').checked;
    var cleanWind = document.getElementById('txtCleanWindUnits').value;
    var habitatSupport = document.getElementById('rdoHabitatSupportYes').checked;
    var greenChoice = '';
    
    //Calculation of GreenSource Cost
    if (greenSource)
    {
        GSC = (Mu * 1.2 / 100) + (Mu * 1.2 / 100 * 0.03);    
        greenChoice += 'Green Source';
        C02 = Mu * GSC02; 
        MD = Mu * GSMD; 
        TP = Mu * GSTP; 
    }
            

    //Calculations of HabitatSource Cost
    if (habitatSupport)
    {
        HSC = HABITATSUPPORTCOST;
        if (habitatSupport)
            greenChoice += ' + ';
        greenChoice += 'Habitat Support';
    }
    
    //Calculations of Clean Wind Cost
    if (cleanWind != "" && cleanWind != "undefined" && cleanWind != '0')
    {                                    
        CWC = parseInt(cleanWind) * KWC;
        if (greenChoice.length > 0)
            greenChoice += ' + ';
        greenChoice += 'Clean Wind';
        
        C02 += parseInt(cleanWind) * CWC02;
        MD += parseInt(cleanWind) * CWMD;
        TP += parseInt(cleanWind) * CWTP;
    }   
    
    TP = Math.round(TP);    
    TGC = GSC + CWC + HSC; //Calculations of total Costs for Green options
    var offset = ((GSC > 0) * 100) + (((parseInt(cleanWind) > 0) * (CWUKW * cleanWind))/Mu * 100);    
    var monthlyBill = (parseFloat(Mb) + TGC); 
                
    document.getElementById('greenChoices').innerHTML = greenChoice;           
    document.getElementById('energyOffset').innerHTML = parseInt(offset) + '%';
    document.getElementById('monthlyBill').innerHTML = '$' + formatNumber(monthlyBill.toFixed(2));
    document.getElementById('co2').innerHTML = formatNumber(C02.toFixed(2));
    document.getElementById('milesDriven').innerHTML = formatNumber(MD.toFixed(2));
    document.getElementById('milesDriven2').innerHTML = formatNumber(MD.toFixed(2));
    document.getElementById('treesPlanted').innerHTML = formatNumber(TP);
    document.getElementById('treesPlanted2').innerHTML = formatNumber(TP);
    
     

    d = MD/distanceToNY;
    document.getElementById('amountSpent').innerHTML = '$' + formatNumber(TGC.toFixed(2));        
    document.getElementById('buyIcons').innerHTML = GetAmountSpentGraphics(TGC);
    document.getElementById('treeIcons').innerHTML = GetTreeGraphics(TP);                    
    document.getElementById('dNumber').innerHTML = d.toFixed(1);    
    document.getElementById('calc_2').style.visibility = 'visible';
    document.getElementById('calc_3').style.visibility = 'visible';
}

//Get display graphics for amount spent
function GetAmountSpentGraphics(TGC)
{   
    var mochaAmount = 0,pizzaAmount = 0;
    buyiconimages = '';
    if (TGC > mochaCost)
    {
        var mochaAmount = Math.round(TGC/mochaCost);        
        if (mochaAmount > mochaMax)
        {
            pizzaAmount = Math.round((mochaAmount - mochaMax)/pizzaCost); 
            mochaAmount = mochaMax;
            if (pizzaAmount > pizzaMax)
                buyiconimages = 'Too much spent to display graphical representation.';                                 
        }       
    }
    else 
        buyiconimages = 'Too little spent to display graphical representation.';
        
    if (buyiconimages == '')
    {
        for(var i = 0; i < mochaAmount; i++)
            buyiconimages += '<img src="' + mochaPath + '" style="position: absolute;top:0px;left: ' + i*17 + 'px;" />';    
        for(var i = 0; i < pizzaAmount; i++)    
            buyiconimages += '<img src="' + pizzaPath + '" style="position:absolute;top:65px;left: ' + i*15 + 'px;" />';
    } 
    return buyiconimages;
}

//Get disply graphics for trees planted
function GetTreeGraphics(TP)
{
    var treeiconimages = '';    
    
    lgTreeCount = 0, medTreeCount = 0, smTreeCount = 0;
    lgTreeCount = parseInt(TP/lgTreeNu);
    if (lgTreeCount > lgTreeMax)
    {
        lgTreeCount = lgTreeMax;
        treeiconimages = 'Too many trees planted to display graphical representation.';
    }    
    else
    {
        medTreeCount = Math.round(TP%lgTreeNu/medTreeNu);
        smTreeCount = Math.round(TP%medTreeNu/smTreeNu);    
    }
                  
    if (treeiconimages == '')
    {        
        for (var i = 0; i < lgTreeCount; i++)
            treeiconimages += '<img src="' + treeLgPath + '" style="float:left;padding:0px 5px;" />'; 
            treeiconimages += (treeiconimages != '' ? '<div style="clear:left"></div>' : '');       
        for (var i = 0; i < medTreeCount; i++)
            treeiconimages += '<img src="' + treeMedPath + '" style="float:left;padding:0px;" />';    
            treeiconimages += (treeiconimages != '' ? '<div style="clear:left"></div>' : '');       
        for (var i = 0; i < smTreeCount; i++)
            treeiconimages += '<img src="' + treeSmPath + '" style="float:left;padding:0px;" />';
    }
    
    if (treeiconimages == '')
        treeiconimages = 'Too few trees saved to display graphical representation.';
     
    return treeiconimages;
}

