var savedXml;
var totalsHtml ="";
var totalValue = 0;
var totalGrams = 0;
var displayType = "money";
$(document).ready(function(){
    // Get XML data
    $.ajax({ type:"GET", url: "/common/xml/checklist.xml", dataType: "xml", success: handleResponse });
    
    // Add checkbox to UL LI
    $(".checklist-selection").append("<input type='checkbox'>");
    
    //arb.functions.collapsible("#today h3");
    //arb.functions.collapsible("#thisweek h3");
    //arb.functions.collapsible("#thisyear h3");
    
    displayType = arb.cookie.get("displaytype"); 
    var selected = $("#display-select");
    if(displayType == "money" || displayType == null)
    {
        selected[0].selectedIndex = 0;
        displayType = "money";
    }
    else if(displayType == "dollar")
    {
      selected[0].selectedIndex = 2;
    }
    else
    {
        selected[0].selectedIndex = 1;
    }
    
    // Add function to click event for the checkboxes
    $("ul.checklist-options li .checklist-selection input[@type=checkbox]").click(function() {
        var id = $(this).parents("li")[0].id;
        if(this.checked)
        {
            // Add to cookie here
            SetCookie("MyCookie", id);
            var target = $(".myaction-row")[0];
            $(this).parents("li").TransferTo({to:target, className:'transferer1', duration: 500});
        }
        else
        {
            // Remove from cookie here
            RemoveFromCookie("MyCookie", id);
        }
        
        BuildMyActions();
    });
    
});
function handleResponse(xml)
{
    savedXml = xml;
    SetPriceGas();
    BuildMyActions();
}
        
function BuildMyActions()
{
    $(".myaction-row")[0].innerHTML = "";
    
    totalValue = 0;
    totalGrams = 0;
    totalMoney = 0;
    totalsHtml = "";
    
    totalsHtml = DivHeader();
    // Get the selected items from cookie and mark them
    var cookie = arb.cookie.get("MyCookie");
    if (cookie != null && cookie != "")
    {
        var ids = cookie.split(";");
        for(i=0;i<ids.length-1;i++)
        {
            $("#" + ids[i] + " .checklist-selection input[@type=checkbox]")[0].checked = true;
            
            var heading = $("item[@id=" + ids[i] + "]", savedXml).attr("heading");
            var price = parseFloat($("item[@id=" + ids[i] + "]", savedXml).attr("price"));
            var grams = parseFloat($("item[@id=" + ids[i] + "]", savedXml).attr("grams"));
        var money = parseFloat($("item[@id=" + ids[i] + "]", savedXml).attr("money"));
            
            if (heading != undefined) {
            if (displayType == "money")
            {
                if(price > 0)
                    totalsHtml += DivItem(heading,FormatNumber(price,0,false,false,true), ids[i]);
                else
                    totalsHtml += DivItem(heading,"", ids[i]);
            }
        else if (displayType == "dollar")
        {
           if(isNaN(parseInt(money))) { money = 0;  };
            
               if(money > 0)
                    totalsHtml += DivItem(heading,"$" +FormatNumber(money,0,false,false,true), ids[i]);
                else
                    totalsHtml += DivItem(heading,"", ids[i]);                
        }
            else
            {
                if(grams > 0)
                   totalsHtml += DivItem(heading,FormatKilo(grams,0,false,false,true)+ " kg", ids[i]);
                else
                 totalsHtml += DivItem(heading,"", ids[i]);
    
            }             
            totalValue += price;
            totalGrams += grams;
        totalMoney += money;
            
            }
        }
    }
    //totalsHtml += DivFooter();
    totalsHtml += DivChecklistFooter(displayType);

    $(".myaction-row").append(totalsHtml);
    
    $(".yousaved-values")[0].innerHTML = "";
    $(".yousaved-values")[0].innerHTML = "<p>" + FormatNumber((totalGrams/50),0,false,false,true) + " balloons and<br />" + FormatKilo(totalGrams,0,false,false,true) + " kilograms of greenhouse gas per year";
    callExternalInterface(Number(FormatNumber((totalGrams/50),0,false,false,false)));
}
function RemoveItem(id)
{
    $("#" + id + " .checklist-selection input[@type=checkbox]")[0].checked = false;
    RemoveFromCookie("MyCookie", id);
    BuildMyActions();
}
function callExternalInterface(str) {
    thisMovie("balloon").sendToFlash(str);
}
function thisMovie(movieName) {
    return document.getElementById(movieName);
}
function ChangeDisplay()
{
    displayType = $("#display-select option:selected").val();
    arb.cookie.set("displaytype", displayType); 
    SetPriceGas();
    BuildMyActions();
    
}
function SetPriceGas()
{
    var nodes = $("ul.checklist-options li");
    var display = "";
    
    for(i=0;i<nodes.length;i++)
    {
        $("#" + nodes[i].id + " div.checklist-value").remove();
        
        if (displayType == "money")
        {    
            if ($("item[@id=" + nodes[i].id + "]", savedXml).attr("price") != 0)
                display = FormatNumber($("item[@id=" + nodes[i].id + "]", savedXml).attr("price"),0,false,false,true) + " balloons";
            else
                display = "";
        }
      else if (displayType == "dollar")
        {    
            if ($("item[@id=" + nodes[i].id + "]", savedXml).attr("money") != 0)
                display = "$" + FormatNumber($("item[@id=" + nodes[i].id + "]", savedXml).attr("money"),0,false,false,true) + "";
            else
                display = "";
        }
        else
        {    
            if ($("item[@id=" + nodes[i].id + "]", savedXml).attr("grams") != 0)
                display = FormatKilo($("item[@id=" + nodes[i].id + "]", savedXml).attr("grams"),0,false,false,true) + " kg";
            else
                display = "";
         }
        
        $("#" + nodes[i].id).append("<div class='checklist-value clearfix'>" + display + "</div>");    
    }
}
function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
    IN:
        NUM - the number to format
        decimalNum - the number of decimal places to format the number to
        bolLeadingZero - true / false - display a leading zero for
                                        numbers between -1 and 1
        bolParens - true / false - use parenthesis around negative numbers
        bolCommas - put commas as number separators.
 
    RETVAL:
        The formatted number!
 **********************************************************************/
{ 
        if (isNaN(parseInt(num))) return "0";
    var tmpNum = num;
    var iSign = num < 0 ? -1 : 1;        // Get sign of number
    
    // Adjust number so only the specified number of numbers after
    // the decimal point are shown.
    tmpNum *= Math.pow(10,decimalNum);
    tmpNum = Math.round(Math.abs(tmpNum))
    tmpNum /= Math.pow(10,decimalNum);
    tmpNum *= iSign;                    // Readjust for sign
    
    
    // Create a string object to do our formatting on
    var tmpNumStr = new String(tmpNum);
    // See if we need to strip out the leading zero or not.
    if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
        if (num > 0)
            tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
        else
            tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
        
    // See if we need to put in the commas
    if (bolCommas && (num >= 1000 || num <= -1000)) {
        var iStart = tmpNumStr.indexOf(".");
        if (iStart < 0)
            iStart = tmpNumStr.length;
        iStart -= 3;
        while (iStart >= 1) {
            tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
            iStart -= 3;
        }        
    }
    // See if we need to use parenthesis
    if (bolParens && num < 0)
        tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";
    return tmpNumStr;        // Return our formatted string!
}
function FormatKilo(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
{ 
        if (isNaN(parseInt(num))) return "0";
    var tmpNum = num;
    var iSign = num < 0 ? -1 : 1;        // Get sign of number
    
    // Adjust number so only the specified number of numbers after
    // the decimal point are shown.
    tmpNum *= Math.pow(10,decimalNum);
    tmpNum = Math.round(Math.abs(tmpNum))
    tmpNum /= Math.pow(10,decimalNum);
    tmpNum *= iSign;                    // Readjust for sign
    
    tmpNum = tmpNum / 1000;
    
    // Create a string object to do our formatting on
    var tmpNumStr = new String(tmpNum);
    // See if we need to strip out the leading zero or not.
    if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
        if (num > 0)
            tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
        else
            tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
        
    // See if we need to put in the commas
    if (bolCommas && (num >= 1000 || num <= -1000)) {
        var iStart = tmpNumStr.indexOf(".");
        if (iStart < 0)
            iStart = tmpNumStr.length;
        iStart -= 3;
        while (iStart >= 1) {
            tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
            iStart -= 3;
        }        
    }
    // See if we need to use parenthesis
    if (bolParens && num < 0)
        tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";
    return tmpNumStr;        // Return our formatted string!
}