﻿function AddToBasketPanel(id, buybuttonclassname)
{
	this.container = $('#' + id);
	this.buyButton = $(buybuttonclassname, this.container)
	
	//find the quickbuy container 
	this.quickbuycontainer = $('.divFiveQuickBuy', this.container);
	this.quickbuylink = $('.quickbuylink', this.quickbuycontainer);
	this.quickbuyitem = $('*:hidden', this.quickbuycontainer);
	
	if (this.quickbuylink)
		this.quickbuylink.click(this.quickbuylinkclicked.bind(this));
		
	this.itemId = $('.buyButton', this.container);
	
	if (this.buyButton)
		this.buyButton.click(this.buyButtonClicked.bind(this, false));
		
}


AddToBasketPanel.prototype = {

	quickbuylinkclicked: function()
	{
		var SelectedFormats = this.getSelectedFormats();
		
		if (SelectedFormats != null)
		{
			$.ajax({
			  type: "POST",
			  url: Url.format("~/Handlers/AddToBasket.ashx"),
			  data: { formats: SelectedFormats },
			  success: this.quickbuySuccess.bind(this),
			  error: this.buyFailure.bind(this),
			  evalScripts: true
			});
		}
		return false;
	},

	buyButtonClicked: function(quickBuy)
	{
		var SelectedFormats = this.getSelectedFormats();
		
		if (SelectedFormats != null)
		{
			$.ajax({
			  type: "POST",
			  url: Url.format("~/Handlers/AddToBasket.ashx"),
			  data: { formats: SelectedFormats },
			  success: this.buySuccess.bind(this, SelectedFormats),
			  error: this.buyFailure.bind(this),
			  evalScripts: true
			});
		}
		return false;
	},

	getSelectedFormats: function()
	{
		var sel = [];
		
		if ($("label.checkbox-on").length > 0)
		{
			CheckBoxSelectedId = $("label.checkbox-on", this.container).attr("for");
			if (('#' + CheckBoxSelectedId).length > 0) sel.push($('#' + CheckBoxSelectedId).val());
		}
			
		if ($("label.radio-on", this.container).length > 0)
		{
			RadioButtonSelectedId = $("label.radio-on", this.container).attr("for");
			if (('#' + RadioButtonSelectedId).length > 0) sel.push($('#' + RadioButtonSelectedId).val());
		}

		if ($("label.radioown-on", this.container).length > 0)
		{
			RadioButtonSelectedId = $("label.radioown-on", this.container).attr("for");
			if (('#' + RadioButtonSelectedId).length > 0) sel.push($('#' + RadioButtonSelectedId).val());
		}

		//var sel = $("input:checked", this.container);

		if (sel.length <= 0) sel = $("input.radiobutton", this.container);
		return sel;
	},
	
	quickbuySuccess : function()
	{
		document.location = Url.format("~/QuickbuyConfirmOrderWithCard.aspx");
		return false;
	},
	
	buySuccess: function(Items)
	{
		$("#DivError").hide();
		if (Header.instance) Header.instance.showBasketOverlay(Items);
	},
	
	buyFailure: function()
	{
		//assumes a div tag called diverror
		$("#DivError").html(arguments[0].responseText);
		$("#DivError").show();
	}
}