var savedXml;
var totalsHtml ="";
var totalValue = 0;
var totalGrams = 0;
var removeLink = $("<div class=\"collected\"><a href='javascript:;'>You have collected this action</a></div>");
var addLink = $("<div class=\"addaction\"><a href='javascript:'>Add to My Actions</a></div>");
function ReturnTotalValue()
{
    return     totalValue;
}
function getActionTotal()
{
    return (totalGrams/50);
}
$(document).ready(function(){
    
    
    // Get XML data
    $.ajax({ type:"GET", url: "/common/xml/checklist.xml", dataType: "xml", success: handleResponse });
    
    // Add default links as add to each item
    var linkAdd = $(addLink).clone();
    $(".action-select .action-status").append(linkAdd);
    
    var linkRemove = $(removeLink).clone();
    var cookie = arb.cookie.get("MyCookie");
    
    if (cookie != null && cookie != "")
    {
        var ids = cookie.split(";");
        for(i=0;i<ids.length-1;i++)
        {
            $("#" + ids[i] + " div.addaction ").remove();
            $("#" + ids[i]).append("<div class='collected'><a href='javascript:;'>You have collected this action</a></div>");
        }
    }
    
    // Add function to click event to add to my actions
    //$("ul li a.add-action").click(addHandler);
    $(".action-select .action-status .addaction").click(addHandler);
      
    // Add function to click event to remove from my actions  
    //$("ul li a.remove-action").click(removeHandler);
    $(".action-select .action-status .collected").click(removeHandler);
    
});
function removeHandler() {
        var id = $(this).parents("div.action-select")[0].id;
        RemoveFromCookie("MyCookie", id);
        $("#" + id + " div.collected").remove();
        var link = $(addLink).clone();
        $("#" + id).append(link);
        link.click(addHandler);
       
        BuildMyActions();
}
function addHandler() {
        
        var target = $(".myaction-row")[0];
        $(this).parents("div.action-select").TransferTo({to:target, className:'transferer1', duration: 500});
        
        var id = $(this).parents("div.action-select")[0].id;
        SetCookie("MyCookie", id);
        $("#" + id + " div.addaction").remove();
        var link = $(removeLink).clone();
        $("#" + id).append(link);
        link.click(removeHandler);
            
//      $(this).TransferTo('dfd', 50);
         
        BuildMyActions();
}
      
      
function handleResponse(xml)
{
    savedXml = xml;
    BuildMyActions();
}
        
function BuildMyActions()
{
    $(".myaction-row")[0].innerHTML = "";
    
    totalValue = 0;
    totalGrams = 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++)
        {
            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"));
            if (heading != undefined) {            
            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;
            }
            
        }
    }
    totalsHtml += DivFooter();
    
    $(".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)
{
    // Chaning the link goes here
    $("#" + id + " div.collected").remove();
    $("#" + id).append("<div class=\"addaction\"><a href='javascript:'>Add to My Actions</a></div>");
    $("#" + id + " div.addaction").click(addHandler); 
    
    RemoveFromCookie("MyCookie", id);
    BuildMyActions();
}
function callExternalInterface(str) {
    thisMovie("balloon").sendToFlash(str);
}
function thisMovie(movieName) {
    return document.getElementById(movieName);
}
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!
}