/* Functions used to assist in package selection for purchase.
	Provided by Topspin Media http://www.topspinmedia.com/
	Dependencies:
		YUI Yahoo Global object: <script src="http://yui.yahooapis.com/2.6.0/build/yahoo/yahoo-min.js"></script> 
		YUI DOM object: <script src="http://yui.yahooapis.com/2.6.0/build/dom/dom-min.js"></script>
		YUI Event object: <script src="http://yui.yahooapis.com/2.6.0/build/event/event-min.js"></script>
*/

if (typeof(Topspin) == "undefined" || !Topspin)
{
	Topspin = {};
}
Topspin.BundleHelper = {};

Topspin.BundleHelper.selectContainerName = "selectioncontainer";
Topspin.BundleHelper.continueButtonName = "continueButton";
Topspin.BundleHelper.cancelButtonName = "cancelButton";
Topspin.BundleHelper.shirtSelectName = "sel_size";
Topspin.BundleHelper.shirtTypeName = "sel_type";
Topspin.BundleHelper.fileSelectName = "sel_format";
Topspin.BundleHelper.productContainerClass = "module";

/*
	This function adds the required DOM elements for the 
	Selection container and selection dropdowns.
*/
Topspin.BundleHelper.domInit = function()
{
/*
<div id="selectioncontainer" style="display:none;">
	<div id="selectioninnercont">
		<div id="sizelabel">Choose your shirt size:</div>
		<div>
			<select id="sel_size" name="sel_size">
				<option value="0">Please select a size</option>
				<option value="1">Small</option>
				<option value="2">Medium</option>						
				<option value="3">Large</option>
				<option value="4">Extra Large</option>																											
			</select>
		</div>
		<div>Choose a file format:</div>
		<div>
			<select id="sel_format" name="sel_format">
				<option value="0">Please select a format</option>
				<option value="1">320 Kbps MP3</option>
				<option value="2">FLAC</option>
				<option value="3">Apple Lossless</option>																												
			</select>
		</div>
		<div id="contBtnContainer">
			<a id="cancelButton" href="javascript:void(0);" onclick="YAHOO.util.Dom.setStyle('selectioncontainer', 'display', 'none'); return false;">Cancel</a>
			<a id="continueButton" href="javascript:void(0);" onclick="Topspin.BundleHelper.buyContinue(''); return false;">Continue</a>
		</div>
	</div>
</div>
*/
	// Selection Container
	var elmSelCont = document.createElement("div");
	elmSelCont.setAttribute("id", "selectioncontainer");
	elmSelCont.setAttribute("style", "display:none;");
	
	// Selection Inner Container
	var elmInnerCont = document.createElement("div");
	elmInnerCont.setAttribute("id", "selectioninnercont");
	
	// Size Label
	var elm = document.createElement("div");
	elm.setAttribute("id", "sizelabel");
	var elmText = document.createTextNode("Choose your shirt size:");
	elm.appendChild(elmText);
	elmInnerCont.appendChild(elm);
	
	// Shirt Selector
	elm = document.createElement("div");
	elm.innerHTML = '\
		<select id="sel_size" name="sel_size">\
			<option value="0">Please select a size</option>\
			<option value="1">Small</option>\
			<option value="2">Medium</option>\
			<option value="3">Large</option>\
			<option value="4">Extra Large</option>\
			<option value="5">XX Large</option>\
		</select>\
	';
	elmInnerCont.appendChild(elm);
    
	// File Label
	var elm = document.createElement("div");
	elm.setAttribute("id", "filelabel");
	var elmText = document.createTextNode("Choose a file format:");
	elm.appendChild(elmText);
	elmInnerCont.appendChild(elm);
	
	// Shirt Selector
	elm = document.createElement("div");
	elm.innerHTML = '\
		<select id="sel_format" name="sel_format">\
			<option value="0">Please select a format</option>\
			<option value="1">320 Kbps MP3</option>\
			<option value="2">MP3 + FLAC</option>\
			<option value="3">MP3 + Apple Lossless</option>\
		</select>\
	';
	elmInnerCont.appendChild(elm);
	
	// Button Container
	var elmBtnCont = document.createElement("div");
	elmBtnCont.setAttribute("id", "contBtnContainer");
	
	// Cancel Button
	var elmBtnCancel = document.createElement("a");
	elmBtnCancel.setAttribute("id", "cancelButton");
	elmBtnCancel.setAttribute("href", "javascript:void(0);");
	/*
	elm.onclick = "YAHOO.util.Dom.setStyle('selectioncontainer', 'display', 'none'); return false;";
	elm.setAttribute("onclick", "YAHOO.util.Dom.setStyle('selectioncontainer', 'display', 'none'); return false;");
	*/
	elmText = document.createTextNode("Cancel");
	elmBtnCancel.appendChild(elmText);
	elmBtnCont.appendChild(elmBtnCancel);
	
	// Continue Button
	var elmBtnContinue = document.createElement("a");
	elmBtnContinue.setAttribute("id", "continueButton");
	elmBtnContinue.setAttribute("href", "javascript:void(0);");
	elmText = document.createTextNode("Continue");
	elmBtnContinue.appendChild(elmText);
	elmBtnCont.appendChild(elmBtnContinue);
	
	elmInnerCont.appendChild(elmBtnCont);
	
	elmSelCont.appendChild(elmInnerCont);
	var elmBody = document.body;
	elmBody.appendChild(elmSelCont);
	
	// Attach click event handler to cancel button.
	YAHOO.util.Event.addListener(elmBtnCancel, "click", Topspin.BundleHelper.hideSelections);
	// Attach click event handler to continue button.
	YAHOO.util.Event.addListener(elmBtnContinue, "click", Topspin.BundleHelper.buyContinue);
	
	// Clean up
	elm = null;
	elmText = null;
	elmBtnContinue = null;
	elmBtnCont = null;
	elmInnerCont = null;
	elmSelCont = null;
	elmBody = null;
};

/*	Utility function to get the selected value of a radio button group. 
	Params:
		radioGroup - reference to the radio group form element for which you would like to retrieve the selected value.
	Return: string; the value of the selected radio button, or null, if none selected.
*/
Topspin.BundleHelper.radioValue = function (radioGroup)
{
	if (radioGroup)
	{
		for (var i = 0; i < radioGroup.length; i++)
		{
			if (radioGroup[i].checked)
			{
				var retVal = radioGroup[i].value;
				radioGroup = null;
				return retVal;
			}
		}
	}
	return null;
};

/* 	Determines whether the selection box is currently being displayed or not.
	Returns: true or false.
*/
Topspin.BundleHelper.selectionBoxOpen = function()
{
	var elmContainer = document.getElementById(this.selectContainerName);
	var retVal = false;
	if (elmContainer)
	{
		if ((elmContainer.currentStyle && elmContainer.currentStyle.display != "none")
			|| (elmContainer.style && elmContainer.style.display != "none")
		)
		{
			retVal = true;
		}
		elmContainer = null;
	}
	return retVal;
};

Topspin.BundleHelper.hideSelections = function()
{
	YAHOO.util.Dom.setStyle('selectioncontainer', 'display', 'none');
	return false;
};

/*  Display bundle selection options in the appropriate area. 
	Params:
		buyButton - reference to the html element that the user clicked to launch the purchase process.
		productType - string; unique name of the type of product being purchased. See function body for valid values.
	Return: null
*/
Topspin.BundleHelper.buyClick = function (buyButton, productType, alignment)
{
	if (buyButton && productType && productType.length > 0)
	{
		var bFiles = false;
		var bShirt = false;
		// Determine whether or not to show a shirt size select box.
		switch (productType)
		{
			case "digital":
			case "cd":
			case "2cd":
			case "vinyl":
			case "deluxe":
			{
				bFiles = true;
				break;
			}
		}
		
		var elmContinue = document.getElementById(this.continueButtonName);
		if (elmContinue)
		{
			// Set productType attribute on the Continue button. This will be used in the buyContinue function to determine the type of product being purchased.
			elmContinue.setAttribute("productType", productType);
			elmContinue = null;
		}
		
		// Reset selections.
		var elm = document.getElementById(this.selectContainerName);
		if (elm)
		{		
			var aSelsRaw = elm.getElementsByTagName("select");
			var aSels = new Array();
			if (aSelsRaw && aSelsRaw.length > 0)
			{
				for (var i = 0; i < aSelsRaw.length; i++)
				{
					var elmSelect = aSelsRaw[i];
					elmSelect.value = "0";

					elmSelect = null;
				}

				delete aSelsRaw;
				aSelsRaw = null;
			}
		}
		// Display file select or not?
		YAHOO.util.Dom.setStyle(this.fileSelectName, "visibility", (bFiles ? "visible" : "hidden"));
		YAHOO.util.Dom.setStyle(this.fileSelectName, "display", (bFiles ? "block" : "none"));
		YAHOO.util.Dom.setStyle("filelabel", "display", (bFiles ? "block" : "none"));
		
		// Display t-shirt select or not?
		YAHOO.util.Dom.setStyle(this.shirtSelectName, "visibility", (bShirt ? "visible" : "hidden"));
		YAHOO.util.Dom.setStyle(this.shirtSelectName, "display", (bShirt ? "block" : "none"));
		YAHOO.util.Dom.setStyle("sizelabel", "display", (bShirt ? "block" : "none"));
		
		YAHOO.util.Dom.setStyle(this.shirtTypeName, "visibility", (bShirt ? "visible" : "hidden"));
		YAHOO.util.Dom.setStyle(this.shirtTypeName, "display", (bShirt ? "block" : "none"));
		YAHOO.util.Dom.setStyle("stylelabel", "display", (bShirt ? "block" : "none"));
		
		if (!bFiles && !bShirt)
		{
			// No need for the selection dialogue. Just go to the p-flow.
			this.buyContinue(productType);
			return;
		}
		
		// Show the selection container.  It has to be visible before the calculations below will work.
		YAHOO.util.Dom.setXY(this.selectContainerName, [-500, 0]);
		YAHOO.util.Dom.setStyle(this.selectContainerName, "display", "block");
		
		// Determine where to place selection container.
		
		var elm = buyButton;
		
		// Get the position of the buy button that the user pressed.
		var pos = YAHOO.util.Dom.getXY(elm);
		if (alignment && alignment.indexOf("r") > -1)
		{
			// Align to the right of the button.
			
			// Get the width of the button.
			var modWidth = parseInt(YAHOO.util.Dom.getStyle(elm, "width"));
			// Get the width of the selection container.
			var contWidth = parseInt(YAHOO.util.Dom.getStyle(this.selectContainerName, "width"));
			// Adjust the X value to the left by the amount of the difference in widths.
			pos[0] -= (contWidth - modWidth);
		}
		
		if (alignment && alignment.indexOf("b") > -1)
		{
			// Align to the bottom of the button.
			
			// Get the height of the button.
			var modHeight = parseInt(YAHOO.util.Dom.getStyle(elm, "height"));
			// Get the height of the selection container.
			var contHeight = parseInt(YAHOO.util.Dom.getStyle(this.selectContainerName, "height"));
			// Adjust the Y value down by the amount of the difference in heights.
			pos[1] += (modHeight - contHeight);
		}
		YAHOO.util.Dom.setXY(this.selectContainerName, pos);
	}
};

/* 	Launches the (Flash) purchase flow when the user makes their selections 
	and presses the "Continue" button.
	Params:
		productType - string; unique name of the type of product being purchased. See function body for valid values.
	Return: null
*/
Topspin.BundleHelper.buyContinue = function (productType)
{
	/* 	This function might either be called directly or as an event handler.
		If it is called as an event handler, the first argument will be an object representing the event.
		If that's the case, we want to disregard this object and get the productType attribute 
		  from the calling DOM element (which should be the "continue" button).
	*/
	if (typeof (productType) == "object")
	{
		var prop = this.getAttribute("productType");
		var productType = prop;
	}
	
	var bBypass = false;
	// For some productTypes, there is no need for user selections, so set a flag that we can jump straight to the purchase flow.
	/*
	if (productType == "cd"
		|| productType == "vinyl")
	{
		bBypass = true;
	}
	*/
	
	var elm = document.getElementById(Topspin.BundleHelper.selectContainerName);
	if (elm || bBypass === true)
	{
		// Get all the select boxes which are currently being displayed.
		var aSelsRaw = elm.getElementsByTagName("select");
		var aSels = new Array();
		if (aSelsRaw && aSelsRaw.length > 0)
		{
			var nDimensions = 0;
			for (var i = 0; i < aSelsRaw.length; i++)
			{
				var elmSelect = aSelsRaw[i];
				if (elmSelect && ((elmSelect.currentStyle && elmSelect.currentStyle.display != "none") || (elmSelect.style && elmSelect.style.display != "none")))
				{
					// This one is visible, so add it to the filtered array and add a dimension.
					aSels[aSels.length] = elmSelect;
					nDimensions++;
				}
				elmSelect = null;
			}
			// Clean up a little.
			delete aSelsRaw;
			aSelsRaw = null;
			
			// Define array of actual selected values (as opposed to the previous arrays of select elements).
			var aSelections = new Array(nDimensions);
			var blnValid = true;
			for (var i = 0; i < aSels.length; i++)
			{
				elmSel = aSels[i];
				if (elmSel)
				{
					if (elmSel.value == "0" && bBypass !== true)
					{
						// The user has not selected anything.  Message them to do so.
						alert("Please make a selection.");
						aSelections[i] = null;
						blnValid = false;
						elmSel = null;
						break;
					}
					else
					{
						// Store the selected value in our array.
						aSelections[i] = parseInt(elmSel.value) - 1;
						elmSel = null;
					}
					elmSel = null;
				}
			}
			
			// Ugly-ass hack
			if (bBypass === true)
			{
				nDimensions = 1;
				aSelections[0] = 0;
			}
			if (blnValid === true || bBypass === true)
			{
				// Define bundle array for each of the various product types.
				
				var aBundles = new Array();
				switch (productType)
				{
					case "digital":
					{
						aBundles = [
    						{bundleID:23303,
    						campaignID:10006938,
    						name:"Premium Digital, MP3"},
    						{bundleID:23304,
    						campaignID:10006939,
    						name:"Premium Digital, MP3 + FLAC"},
    						{bundleID:23305,
    						campaignID:10006941,
    						name:"Premium Digital, MP3 + Apple Lossless"}
						];
						break;
					}
					case "cd":
					{
						aBundles = [
							{bundleID:23307,
    						campaignID:10006943,
    						name:"Digital + CD, MP3"},
    						{bundleID:23308,
    						campaignID:10006944,
    						name:"Digital + CD, MP3 + FLAC"},
    						{bundleID:23309,
    						campaignID:10006945,
    						name:"Digital + CD, MP3 + Apple Lossless"}
						];
						break;
					}
					case "2cd":
					{
						aBundles = [
							{bundleID:23681,
    						campaignID:10007214,
    						name:"Digital + 2xCD, MP3"},
    						{bundleID:23682,
    						campaignID:10007215,
    						name:"Digital + 2xCD, MP3 + FLAC"},
    						{bundleID:23683,
    						campaignID:10007216,
    						name:"Digital + 2xCD, MP3 + Apple Lossless"}
						];
						break;
					}
					case "vinyl":
					{
						aBundles = [
							{bundleID:23310,
    						campaignID:10006946,
    						name:"Digital + Vinyl, MP3"},
    						{bundleID:23311,
    						campaignID:10006948,
    						name:"Digital + Vinyl, MP3 + FLAC"},
    						{bundleID:23312,
    						campaignID:10006949,
    						name:"Digital + Vinyl, MP3 + Apple Lossless"}
						];
						break;
					}
					case "deluxe":
					{
					    aBundles = [
							{bundleID:23313,
    						campaignID:10006950,
    						name:"Vinyl + Digital, MP3"},
    						{bundleID:23314,
    						campaignID:10006951,
    						name:"Vinyl + Digital, MP3 + FLAC"},
    						{bundleID:23315,
    						campaignID:10006952,
    						name:"Vinyl + Digital, MP3 + Apple Lossless"} 
    					];   
					    break;
					}
				}
				
				// Get the Bundle object that represents the user's selections.
				var bundle;
				
                function findIntersection(dimensions, selections, array) {
                    // create an array of the selected items
                    var selectStr = new String(selections);
                    var selectionArr = selectStr.split(',');
                    // get the base array of bundles
                    targArray = array;
                    // for each dimension, find the array that corresponds to the index
                    // each step in the following loop drills down into a smaller subset of data (closer to the user's selection)
                    for (var i=0;i<dimensions;i++) {
                        targArray = targArray[selections[i]];
                    }
                    // return the intersection point
                    return targArray;
                }
                
                var bundle = findIntersection(nDimensions, aSelections, aBundles);
                
                // Hide the selection container.
				YAHOO.util.Dom.setStyle(elm, "display", "none");
				
				if (bundle && typeof(bundle) == "object")
				{
					// FOR DEBUGGING ONLY
					//alert(bundle.name + "\n" + Topspin.BundleHelper.artistID + "\n" + bundle.bundleID + "\n" + bundle.campaignID)

					// Launch the purchase flow.
					TSPurchase.load({aId:Topspin.BundleHelper.artistID, bId:bundle.bundleID, cId:bundle.campaignID, persist:true});
				}
				
				// Clean up
				delete aBundles;
				aBundles = null;
			}
		}
		// Clean up
		delete aSels;
		aSels = null;
		elm = null;
	}
	return false;
};

Topspin.BundleHelper.domInit();