/// <reference path="../css/jquery-vsdoc.js" />

$(function ()
{
    $("#pnlReleases a").click(LoadSongs);
    $("#btnCheckout").click(CheckInput);
    $("#btnDownload").click(CheckDownload);
    $("#btnAdd").click(AddToCart);
    $("#lnkRemoveAllSongs").click(RemoveAllSongs);
    $("#lnkToggleSongs").click(ToggleSongs);
    $("#ShoppingCardContent span img").live("click",RemoveFromCart);
});

function LoadSongs()
{

    var releaseID = $(this).attr("data-relid");

    // use jQuery to load HTML from a separate page listing the correct songs
    // Parameter 1: the url of the rest service
    // Parameter 2: The form fields, name: value
    // Parameter 3: The callback function

    $.getJSON("/shop/songs.aspx", { releaseid: releaseID, json: 1 }, SongsJsonLoaded);
             
    return false;
}

function SongsJsonLoaded(data)
{

    var songs = "";

    if (data.Songs.length > 0)
    {

        // loop through the Json objects and build html
        for (var i = 0; i < data.Songs.length; i++)
        {
            songs += "<div class='StandAlone' >"
            songs += "<input type='checkbox' name='" + data.Songs[i].Price + "' value='" + data.Songs[i].ProductID + "' />";
            songs += "<span id='title" + data.Songs[i].ProductID + "'>";
            songs += " " + data.Songs[i].theBand;
            songs += " - " + data.Songs[i].theSong;
            songs += " (&cent;" + data.Songs[i].Price + ")";
            songs += "</span></div>";
        }

        $("#SongList").html(songs);
        $("#pnlSongs").show();
    }
    else
    {
        $("#pnlSongs").hide();
        alert("No songs found for the specified release");
    }
}

function ToggleSongs()
{

    // if more than half, uncheck all, otherwise check all
    if ($("#songs input:checked").length > ($("#songs input").length / 2))
    {
        $("#songs input").each(function() { this.checked = false; });
    }
    else
    {
        $("#songs input").each(function() { this.checked = true; });
    }

    return false;
}

function AddToCart()
{
    var cardItems = $("#hdShoppingCart")[0].value;
    var total = $("#hdTotalPrice")[0];
    var Cart = $("#ShoppingCardContent")[0];
    var compareItems = "," + cardItems + ",";
    var newCosts = 0;

    // get all checked checkboxes within the container with ID songs
    $("#songs input:checkbox:checked").each(function()
    {
        if (compareItems.indexOf("," + this.value + ",") == -1)
        {
            Cart.innerHTML += "<span id=\"item" + this.value + "\">"
		                + "<img src=\"../pix/ShopRemove.gif\" title=\"Remove song\" alt=\"Remove\" data-id='" + this.value + "' data-price='" + this.name + "' />" + document.getElementById("title" + this.value).innerHTML + "<br /></span> ";

            cardItems += "," + this.value;

            // get the price, stored in the name field
            newCosts = newCosts + Math.abs(this.name);
            this.checked = false;
        }
    }
    );

    total.value = Math.abs(total.value) + Math.abs(newCosts);
    document.getElementById("lblTotalPrice").innerHTML = CurrencyFormatted(total.value);
    $("#hdShoppingCart")[0].value = FixIDs(cardItems);
}

function RemoveAllSongs()
{
    $("#ShoppingCardContent").html("");
    $("#hdTotalPrice")[0].value = 0;
    $("#lblTotalPrice").html(CurrencyFormatted(0));
    $("#hdShoppingCart")[0].value = "";

    return false;
}
    
    function RemoveFromCart()
    {
        var productID = $(this).attr("data-id");
        var price = $(this).attr("data-price");

        // remove from display
        $("#item" + productID).remove();

        var total = document.getElementById("hdTotalPrice");
                               
        // display from hidden field
        var shoppingCart = document.getElementById("hdShoppingCart");
        var compareItems = "," + shoppingCart.value + ",";
        shoppingCart.value = FixIDs(compareItems.replace("," + productID + ",",","));
        
        total.value = Math.abs(total.value) - Math.abs(price);
        document.getElementById("lblTotalPrice").innerHTML = CurrencyFormatted(total.value);
                
        return false;
    }
    
    function FixIDs(theIDs)
    {
       
        theIDs = theIDs.replace(",,",",");
        if (theIDs.substring(0,1) == ",")
        {
            theIDs = theIDs.substr(1);
        }

 
        if (theIDs.substr(theIDs.length-1,1) == ",")
        {
            theIDs = theIDs.substr(0,theIDs.length-1);
        }
        
        return theIDs;
    }
    
    function CheckDownload()
    {
        var code = document.getElementById("txtOrderCode").value;
                
        // integer, hash and guid 
        var re = new RegExp("^\\d+\\#[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}$","ig");
        
        if (re.test(code))
        {
            return true;
        }                
        else
        {                
            alert("The code is not valid");
            return false;
        }           
    }
    
    function CheckInput()
    {
        var message = "";
                               
        // check email
        var email = document.getElementById("txtEmail").value;
        if (email == "")
        {
            message = "Please provide an email address.\n" 
        }
        else
        {        
            if (!IsValidEmail(email))
            {
                message = "The email address is not valid.\n";
            }
        }

        // check items
        var items = document.getElementById("hdShoppingCart").value;
        if (items == "")
        {
            message += "No songs selected." 
        }
        else
        {
            if (!IsValidIDList(items))
            {
                message += "Problem with your shopping Cart, please start over.\n";
            }
        }

        if (message == "")
        {
            // ask user to confirm
            if (window.confirm("Do you want to checkout?"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            alert(message);
            return false;
        }
    }
    
    function IsValidEmail(email)
    {
        var re = new RegExp("[-a-z0-9\\._&]+@[-a-z0-9\\._]{2,}\\.[a-z]{2,10}","ig");
        return re.test(email);
    }
    
    function IsValidIDList(valueList)
    {
      
        // only digits and commas
        var re = new RegExp("^[\\d]+(,\\d+)*$","g");
        return re.test(valueList);
       
        // we should test for duplicates as well.

    }
    
    function CurrencyFormatted(amount)
    {
	    var i = parseFloat(amount);
	    if(isNaN(i)) { i = 0.00; }
	    
	    // devide by 100 because we deal with cents
	    i = i / 100;
	    
	    var minus = '';
	    if(i < 0) { minus = '-'; }
	    i = Math.abs(i);
	    i = parseInt((i + .005) * 100);
	    i = i / 100;
	    s = new String(i);
	    if(s.indexOf('.') < 0) { s += '.00'; }
	    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	    s = minus + s;
	    return s;
    }

function ToggleHelp() {

	var divSection = document.getElementById("pnlHelp");
	
	if (divSection != null) { 
	
		if (divSection.style.display == 'none') 
		{
			divSection.style.display = 'block';
		} 
		else 
		{
			divSection.style.display = 'none';
		}
	}
	
	return false;
}
