/**
 * Product Options javascript
 *
 * @category CMS
 * @package Shout
 * @subpackage Store
 * @copyright ?
 * @license ?
 * @author Chris Glass <chris@mediashaker.com>
 * @since Thurs, Sept 9, 2004
 * @version $Id: productoptions.js 3946 2009-11-09 23:09:10Z jstraszynski $
 */

var options = new Array();
var curOptionId = 0;
var curValueId = 0;
var curInternal = 0;
var totalMoved = 0;
var inc = 1;

/**
* @var References to the active product option link
*/
var activeProductOption = null;

/**
* @var Array of product options
*/
var optionList 				= window.optionList = new Array();

/**
* @var Array of options that were removed
*/
var removedOptionList 		= window.removedOptionList = new Array();

/**
* @var Array of items that were removed
*/
var removedOptionItemList 	= window.removedOptionItemList = new Array();

/**
* ProductOption
* @param string name
* @param int type
*/
function ProductOption(name,type)
{
	this.id 	  = inc;
	this.name 	  = name;
	this.values   = new Array();
	this.active   = true;
	this.dbId 	  = 0;
	this.type 	  = type;
	this.value 	  = "";
	this.added 	  = false;
	this.required = true;

	inc++;


}

/**
* ProductOptionTypeDescriptor
* @param string name
* @param string image
*/
function ProductOptionTypeDescriptor(name, image )
{
	this.name  = name;

	this.image = image;


}



ProductOption.TypeDescriptors = new Object();

/**
* Product Option Types
*/
ProductOption.TypeDescriptors.OPTION_TYPE_DROPDOWN = 3;
ProductOption.TypeDescriptors.OPTION_TYPE_SHORTTEXT = 0;
ProductOption.TypeDescriptors.OPTION_TYPE_LONGTEXT = 1;
ProductOption.TypeDescriptors.OPTION_TYPE_PRICE = 10;
ProductOption.TypeDescriptors.OPTION_TYPE_CALENDAR = 11;

/**
* Product Option Descriptions
*/
ProductOption.TypeDescriptors[ ProductOption.TypeDescriptors.OPTION_TYPE_DROPDOWN ]  = new ProductOptionTypeDescriptor("Drop Down With Menu Choices", "list.gif");
ProductOption.TypeDescriptors[ ProductOption.TypeDescriptors.OPTION_TYPE_SHORTTEXT ] = new ProductOptionTypeDescriptor("Short Textbox, Viewers Can Type in", "text.gif");
ProductOption.TypeDescriptors[ ProductOption.TypeDescriptors.OPTION_TYPE_LONGTEXT ]  = new ProductOptionTypeDescriptor("Long Textbox, Viewers Can Type in", "textarea.gif");
ProductOption.TypeDescriptors[ ProductOption.TypeDescriptors.OPTION_TYPE_PRICE ]     = new ProductOptionTypeDescriptor("Price Field, Can Enter a Value", "price.jpg");
ProductOption.TypeDescriptors[ ProductOption.TypeDescriptors.OPTION_TYPE_CALENDAR ]  = new ProductOptionTypeDescriptor("Calendar Field, Can Enter a Date", "calendar.gif");

/**
* OptionValue
* @param string name
* @param float int
* @param float price
*/
function OptionValue(name,price_mod,price)
{

	this.name = name;

	this.price = price;
	this.price_mod = price_mod;
	this.active = true;
	this.dbId = 0;
}

/**
* addValue
*
* @param string name
* @param float price
* @param float price_mod
* @param float id
*/
ProductOption.prototype.addValue = function(name, price, price_mod, id)
{

	back = this.values.length  + 1;

	c_id =   this.id + "." + back;
	tValue = new OptionValue(name, price, price_mod );

	if( id )
	{
		tValue.dbId = id;

	}

	this.values[this.values.length] = tValue;

	return tValue;


}

/**
* addProductOption_Cart
*
* @param int name
* @param string name
* @param type type
*/
function addProductOption_Cart(id, name, type, required)
{
	i = options.length;



	options[i] = new ProductOption( name,type );
	options[i].required = required;

	options[i].dbId = id;
}


/**
* addExistingProductOption
*
* @param Object optionObj
*/
function addExistingProductOption( optionObj )
{
	optionList[ dragProductOptions.curId ] = optionObj;


	addProductOption( optionObj.name, optionObj.type, optionObj.required, optionObj.values );


}

/**
* addProductOption
*
* @param string name
* @param int type
* @param required bool
* @param options Array
*/
function addProductOption( name, type, required, options )
{
	var productOptionImgLookup = new Object();




	var optionIndex = dragProductOptions.curId;
	var optionsList = document.createElement("ul");
	optionsList.id = 'productOptionMenuItems' + optionIndex;

	optionList[ optionIndex ].name 		= name;
	optionList[ optionIndex ].type 		= type;
	optionList[ optionIndex ].added 	= true;
	optionList[ optionIndex ].required 	= required;

	var heightChange = 75;

	if( options )
	{

		for( var i = 0; i < options.length; i++ )
		{
			if( options[i].removed )
			{
				continue;
			}

			var optionListItem = document.createElement("li");

			optionListItem.innerHTML = options[i].name + " " + options[i].price_mod + " " +  formatCurrency( options[i].price );


			optionsList.appendChild( optionListItem );

			heightChange += 25;

		}
	}






	var editLink = "<a href = 'javascript:onOptionNameClick(this," + optionIndex + ");'   id = 'productOptionLink" + optionIndex + "'>" + name + "</a>";



	var requiredText = required ? "This Field is Required" : "";

	dragProductOptions.addItem("<div><div class = \"product-option-name\" style = \"float: left;\">" + editLink + "</div>" +
							   "<div style = \"float: right;\"><img src = \"image.php?pic=" + ProductOption.TypeDescriptors[ type ].image + "\" id = 'productOptionIcon" + optionIndex + "'><span>&uarr;&darr;</span></div>" +
							   "<div style = \"clear:both;\"></div>" +
							   "<div id = 'productOptionType" + optionIndex + "'>" + ProductOption.TypeDescriptors[ type ].name + "</div>" +
							   "<div id = 'productOptionRequired" + optionIndex + "'>" + requiredText + "</div>" +
							   "<ul class = \"product-option-options\" id = 'productMenuItems" + optionIndex + "'>" + optionsList.innerHTML + "</ul></div>", optionIndex );

	dragProductOptions.updateList();



	onOptionNameClick( document.getElementById( "productOptionLink-" + optionIndex ), optionIndex );


}

/**
* onOptionNameClick
*
* @param Object link
* @param int index
*/
function onOptionNameClick( linkObj, index )
{
	var txtName 	= document.getElementById('productOptionName');
	var lbType 		= document.getElementById('productOptionType');
	var txtIndex 	= document.getElementById('productOptionIndex');

	var rbRequiredYes 	= document.getElementById('productOptionRequiredYes');
	var rbRequiredNo 	= document.getElementById('productOptionRequiredNo');

	txtName.value = optionList[ index ].name;

	rbRequiredYes.checked = optionList[ index ].required;
	rbRequiredNo.checked = !optionList[ index ].required;

	txtIndex.value = index;

	for( var i = 0; i < lbType.options.length; i++ )
	{


		if( lbType.options[i].value == optionList[ index ].type )
		{
			lbType.selectedIndex = i;

		}

	}

	document.getElementById('menu-items-container').style.display = optionList[ index ].type == ProductOption.TypeDescriptors.OPTION_TYPE_DROPDOWN ? "block" : "none";


	dragMenuOptions.removeAllItems();

	for( var i = 0; i < optionList[ txtIndex.value ].values.length; i++ )
	{

		addProductOptionMenuItem( optionList[ txtIndex.value ].values[i].name, optionList[ txtIndex.value ].values[i].price_mod , optionList[ txtIndex.value ].values[i].price, optionList[ txtIndex.value ].values[i].dbId  );



	}


	document.getElementById("btnAddProductOption").style.display = "none";

	document.getElementById("btnUpdateProductOption").style.display = "inline";
	document.getElementById("btnRemoveProductOption").style.display = "inline";

	document.getElementById("productOptionMessage").innerHTML = "";

	if( linkObj )
	{
		setActiveProductOption( document.getElementById("productOptionLink" + index ).parentNode.parentNode );

	}



}

/**
* Add a new option button clicked
*/
function onAddOptionClick()
{
	var txtName 		= document.getElementById('productOptionName');
	var lbType 			= document.getElementById('productOptionType');
	var rbRequried 		= document.getElementById('productOptionRequiredYes');

	var optArr = new Array();

	var errors = false;

	if( txtName.value == "" )
	{
		showError( txtName );

		errors = true;


	} else {
		hideError( txtName );

	}



	if( errors )
	{
		return;
	}

	addProductOption( txtName.value, lbType.options[ lbType.selectedIndex ].value, rbRequried.checked, optionList[ dragProductOptions.curId ].values );



	document.getElementById("btnAddProductOption").style.display = "none";

	document.getElementById("btnUpdateProductOption").style.display = "inline";
	document.getElementById("btnRemoveProductOption").style.display = "inline";



	document.getElementById("productOptionMessage").innerHTML = "Product option was added successfully";



}

/**
* Create new option button clicked
*/
function onCreateOptionClick()
{
	var txtName 	= document.getElementById('productOptionName');
	var lbType 		= document.getElementById('productOptionType');
	var txtIndex 	= document.getElementById('productOptionIndex');
	var rbRequried 	= document.getElementById('productOptionRequiredYes');


	txtName.value 			= "";
	lbType.selectedIndex	= 0;


	document.getElementById("btnAddProductOption").style.display = "inline";

	document.getElementById("btnUpdateProductOption").style.display = "none";
	document.getElementById("btnRemoveProductOption").style.display = "none";

	if( document.getElementById("product-option-selected") )
	{
		document.getElementById("product-option-selected").id = "";
	}

	document.getElementById("productOptionMessage").innerHTML = "";



	if( !optionList[ dragProductOptions.curId ] || optionList[ dragProductOptions.curId ].added )
	{

		optionList[ dragProductOptions.curId ] = new ProductOption();
	}

	rbRequried.checked = true;

	document.getElementById("menu-items-container").style.display = "block";

	txtIndex.value 			=  dragProductOptions.curId;

	dragMenuOptions.removeAllItems();


}

/**
* Update option button clicked
*/
function onUpdateOptionClick()
{
	var productOptionImgLookup = new Object();

	var txtName 	= document.getElementById('productOptionName');
	var lbType 		= document.getElementById('productOptionType');
	var txtIndex 	= document.getElementById('productOptionIndex');
	var imgIcon 	= document.getElementById('productOptionIcon');
	var rbRequired 	= document.getElementById('productOptionRequiredYes');


	var reduceHeightBy = 0;
	var increaseHeightBy = 0;

	document.getElementById("productOptionMessage").innerHTML = "Product option was updated successfully";


	optionList[ txtIndex.value ].name 		= txtName.value;
	optionList[ txtIndex.value ].type 		= lbType.options[ lbType.selectedIndex ].value;
	optionList[ txtIndex.value ].required 	= rbRequired.checked;

	var type = optionList[ txtIndex.value ].type;


	document.getElementById( "productOptionLink" + txtIndex.value ).innerHTML 		= txtName.value;
	document.getElementById( "productOptionIcon" + txtIndex.value ).src 			= "image.php?pic=" + ProductOption.TypeDescriptors[ type ].image;
	document.getElementById( "productOptionType" + txtIndex.value ).innerHTML 		= ProductOption.TypeDescriptors[ type ].name;
	document.getElementById( "productOptionRequired" + txtIndex.value ).innerHTML 	= optionList[ txtIndex.value ].required ? "This Field is Required" : "";

	// Recreate our menu items:

	var ulMenuItem = document.getElementById( "productMenuItems" + txtIndex.value );
	ulMenuItem.innerHTML = "";

	reduceHeightBy = optionList[ txtIndex.value ].values.length;

	optionList[ txtIndex.value ].values = new Array();



	if( optionList[ txtIndex.value ].type == ProductOption.TypeDescriptors.OPTION_TYPE_DROPDOWN )
	{




		var menuItems = dragMenuOptions.getItems();



		for( var i = 0; i < menuItems.length; i++ )
		{


			var itemIndex = menuItems[i];

			var liItem 			= document.createElement("li");
			var curOption 		= optionList[ txtIndex.value ].values[i];

			var itemName 		= document.getElementById("menu-item-name-" + itemIndex ).value;
			var itemModIndex 	= document.getElementById("menu-item-modifier-" + itemIndex ).selectedIndex;
			var itemMod 		= document.getElementById("menu-item-modifier-" + itemIndex ).options[ itemModIndex ].value;
			var itemPrice 		= document.getElementById("menu-item-value-" + itemIndex ).value;
			var itemId 			= document.getElementById("menu-item-id-" + itemIndex ).value;

			optionList[ txtIndex.value ].addValue( itemName, itemModIndex, itemPrice, itemId );

			liItem.innerHTML = itemName + " " + itemMod + " " + itemPrice;
			ulMenuItem.appendChild( liItem );

		}

		increaseHeightBy = menuItems.length;

	}

	var heightChange = (increaseHeightBy  - reduceHeightBy )  * 25;

	var dvProductOptTree = document.getElementById("productOptTree");
	//dvProductOptTree.style.height = ( parseInt(dvProductOptTree.style.height) + heightChange) + "px";

}

/**
* Remove option clicked
*/
function onRemoveOptionClick()
{
	var index 	= document.getElementById('productOptionIndex').value;
	var optionId = optionList[ index ].dbId;

	if( optionId > 0 )
	{
		removedOptionList.push( optionId );
	}

	dragProductOptions.removeItem( index  );

	dragProductOptions.updateList();

	onCreateOptionClick();

	document.getElementById("productOptionMessage").innerHTML = "Product option was d successfully";

}

/**
* Add menu item option clicked
*/
function onAddMenuItemClick()
{
	var txtName 	= document.getElementById('menuItemName');
	var lbModifier 	= document.getElementById('menuItemModifier');
	var txtCost 	= document.getElementById('menuItemCost');

	var errors = false;


	if( txtName.value == "" )
	{
	//	showError( txtName );
		errors = true;
	} else {
		//hideError( txtName );
	}
/*
	if( txtCost.value == "" )
	{
		//showError( txtCost );
		errors = true;
	} else {
		//hideError( txtCost );
	}
*/

	if( txtCost.value == "" )
	{
		txtCost.value = 0;
	}

	if( errors )
	{
		return;

	}




	addProductOptionMenuItem(txtName.value, lbModifier.selectedIndex , txtCost.value,'');

	var txtIndex 	= document.getElementById('productOptionIndex');

	optionList[ txtIndex.value ].addValue( txtName.value, lbModifier.options[ lbModifier.selectedIndex ].value, txtCost.value );

	txtName.value = "";
	lbModifier.selectedIndex = 0;
	txtCost.value = "";


}

var currentProductOption = new ProductOption();

/**
* Add a product option menu item
*
* @param string name
* @param int price
* @param float value
* @param int dbId
*/
function addProductOptionMenuItem(name, modifier, value, dbId )
{
	var containerDiv 			= document.createElement("div");
	var index 					= dragMenuOptions.curId;

	var handleSpan 				= document.createElement("span");
	handleSpan.innerHTML =		 "&uarr;&darr;";

	var txtName = document.createElement("input");
	txtName.type = "text";
	txtName.className = "product-option-menu-item-name";
	txtName.id = "menu-item-name-" + index;


	var lbPriceMod = document.createElement("select");
	lbPriceMod.id = "menu-item-modifier-" + index;
	lbPriceMod.className = "product-option-menu-item-modifier";

	var optPriceModAdd = new Option();
	optPriceModAdd.text = "+";
	optPriceModAdd.value = "+";

	var optPriceModSub = new Option();
	optPriceModSub.text = "-";
	optPriceModSub.value = "-";


	lbPriceMod.appendChild( optPriceModAdd );
	lbPriceMod.appendChild( optPriceModSub );

	var spDollar = document.createElement("span");
	spDollar.innerHTML = "$";

	var txtValue = document.createElement("input");
	txtValue.type = "text";
	txtValue.id = "menu-item-value-" + index;
	txtValue.className = "product-option-menu-item-value";

	var btnRemove = document.createElement("input");
	btnRemove.value = "Remove";
	btnRemove.type = "button";
	btnRemove.className = "product-option-menu-item-button";
	btnRemove.id = "menu-item-remove-" + index;

	var txtId = document.createElement("input");
	txtId.type = "hidden";
	txtId.id = "menu-item-id-" + index;



	containerDiv.appendChild(handleSpan);
	containerDiv.appendChild(txtName);
	containerDiv.appendChild(lbPriceMod);
	containerDiv.appendChild(spDollar);
	containerDiv.appendChild(txtValue);
	containerDiv.appendChild(btnRemove);
	containerDiv.appendChild(txtId);


	dragMenuOptions.addItem(containerDiv.innerHTML, index );
	dragMenuOptions.updateList();

	document.getElementById( "menu-item-name-" + index ).value = name;
	document.getElementById( "menu-item-value-" + index ).value = value;
	document.getElementById( "menu-item-modifier-" + index ).selectedIndex = modifier;
	document.getElementById( "menu-item-id-" + index ).value = dbId;


	document.getElementById( "menu-item-remove-" + index ).onclick = function() {



			if( dbId > 0 )
			{
				removedOptionItemList.push( dbId );
			}

		dragMenuOptions.removeItem(index);
		dragMenuOptions.updateList();
	};


}

/**
* Remove a product option
*/
function removeProductOption()
{

	totalMoved -= 28;
	toMove = 0;

	if( totalMoved >= 250 )
		toMove = -28;





	for(i = 0; i < options[curOptionId-1].values.length; i++ )
	{
		if( options[curOptionId-1].values[i].active )
		{

			totalMoved -= 28;

			if( totalMoved >= 250 )
				toMove -= 28;
			options[curOptionId-1].values[i].active = false;
		}

	}

	productOptions.aNodes[curInternal].pid = 0;
	options[curOptionId-1].active = false;

	document.getElementById('editOption').style.display = 'none';
	document.getElementById('default_msg').style.display = 'block';
	document.getElementById('productOptTree').innerHTML =  productOptions.toString();

}

/**
* Remove an option value
*/
function removeOptionValue()
{



	productOptions.aNodes[curInternal].pid = 0;
	options[curOptionId-1].values[curValueId].active = false;

	document.getElementById('editValue').style.display = 'none';
	document.getElementById('default_msg').style.display = 'block';
	document.getElementById('productOptTree').innerHTML =  productOptions.toString();

}

/**
* When a product option type changes
*
* @param int type
*/
function onProductOptionTypeChange( type )
{
	document.getElementById('menu-items-container').style.display = type == ProductOption.OPTION_TYPE_DROPDOWN ? 'block' : 'none';
}

/**
* Set the active product option class
* @param Object obj
*/
function setActiveProductOption( obj )
{


	if( activeProductOption  )
	{
		activeProductOption.className = "";
	}

	if( obj )
	{
		obj.className = "active-product-option";
	}

	activeProductOption = obj;


}

/**
* Save the product options
*
* @param Object form
*/
function saveProductOptions( form )
{
	var formToAttach = form;

	if( !form )
	{
		formToAttach = document.getElementsByTagName("form");
		formToAttach = formToAttach[0];


	}
	var optionOrder = Sortable.sequence('dragProductOptions');

	var fixedOrder = {};

	optionOrder.each(function(r,i){
		fixedOrder[r-1] = i;
	});

	var orderIndex = 0;

	optionList.each(function(r,i)
	{

		if(r && r.name && r.active)
		{
			var optionItem = r;

			var baseName 		= "productOptions[active][" + i + "]";

			var txtName 		= document.createElement("input");
			txtName.name		= baseName + "[name]";
			txtName.value		= optionItem.name;
			txtName.type 		= "hidden";

			var txtType	 		= document.createElement("input");
			txtType.name		= baseName + "[type]";
			txtType.value		= optionItem.type;
			txtType.type 		= "hidden";

			var chkRequired 	= document.createElement("input");
			chkRequired.type	= "checkbox";
			chkRequired.name	= baseName + "[required]";
			chkRequired.checked = optionItem.required;
			chkRequired.style.display = "none";

			var txtDbId			= document.createElement("input");
			txtDbId.name		= baseName + "[id]";
			txtDbId.value		= optionItem.dbId;
			txtDbId.type 		= "hidden";

			var txtOrder		= document.createElement("input");
			txtOrder.name		= baseName + "[rank]";
			txtOrder.value		= fixedOrder[orderIndex++];
			txtOrder.type 		= "hidden";

			formToAttach.appendChild( txtName );
			formToAttach.appendChild( txtType );
			formToAttach.appendChild( chkRequired );
			formToAttach.appendChild( txtDbId );
			formToAttach.appendChild( txtOrder );

			if( optionItem.type == ProductOption.TypeDescriptors.OPTION_TYPE_DROPDOWN )
			{

				for( var j = 0; j < optionItem.values.length; j++ )
				{
					var txtItemName 		= document.createElement("input");
					txtItemName.value 		= optionItem.values[j].name;
					txtItemName.name		= baseName + "[items][" + j + "][name]";
					txtItemName.type 		= "hidden";

					var txtItemPrice 		= document.createElement("input");
					txtItemPrice.value		= optionItem.values[j].price_mod == 1 ? -optionItem.values[j].price : optionItem.values[j].price;
					txtItemPrice.name		= baseName + "[items][" + j + "][price]";
					txtItemPrice.type 		= "hidden";

					var txtItemId 			= document.createElement("input");
					txtItemId.value 		= optionItem.values[j].dbId;
					txtItemId.name			= baseName + "[items][" + j + "][id]";
					txtItemId.type 			= "hidden";

					formToAttach.appendChild( txtItemName );
					formToAttach.appendChild( txtItemPrice );
					formToAttach.appendChild( txtItemId );


				}

			}
		}


	});

	if( removedOptionList && removedOptionList.length )
	{
		var lbRemovedLst = document.createElement("select");
		lbRemovedLst.multiple = true;
		lbRemovedLst.name = "productOptions[removed][options][]";
		lbRemovedLst.style.display = "none";

		removedOptionList.each(function(e,i)
		{

			var removedOpt = document.createElement("option");
			removedOpt.text = removedOptionList[i];
			removedOpt.value = removedOptionList[i];
			removedOpt.selected = true;


			lbRemovedLst.add( removedOpt, null );
		});

		formToAttach.appendChild( lbRemovedLst );
	}

	if( removedOptionItemList && removedOptionItemList.length )
	{
		var lbRemovedLst = document.createElement("select");
		lbRemovedLst.multiple = true;
		lbRemovedLst.name = "productOptions[removed][items][]";
		lbRemovedLst.style.display = "none";

		removedOptionItemList.each(function(e,i)
		{
			var removedOpt = document.createElement("option");
			removedOpt.text = removedOptionItemList[i];
			removedOpt.value = removedOptionItemList[i];
			removedOpt.selected = true;


			lbRemovedLst.add( removedOpt, null );
		});

		formToAttach.appendChild( lbRemovedLst );
	}


	return true;
}

window.changeOptionFilters = function changeOptionFilters(triggerElement)
{
	var $container = jQuery(triggerElement).closest('.product_browse');
	// We traverse up from the trigger element to find the clustered group of products we're going to filter.
	var categories = jQuery.map(
		jQuery(triggerElement)
			.closest('.product_browse')
			.find('select[name*=filter_option].product_browse-category_filter')
		,function(element)
		{
			return ".category-"+jQuery(element).val();
		});

	var sort = $container.find('.product_browse-sort').val();

	var browseProducts = $container.find('.product_browse-product').get();

	browseProducts = browseProducts.sort(function(a, b)
	{
		var priceA = jQuery(a).find('input[name=price]').val();
		var priceB = jQuery(b).find('input[name=price]').val();

		return (priceA < priceB) ? -1 : (priceA > priceB) ? 1 : 0;
	});

	if(sort == 'desc')
	{
		browseProducts = browseProducts.reverse();
	}

	var $itemContainer = $container.find('.product_browse-items');

	jQuery.each(browseProducts, function()
	{
		$itemContainer.append(this);
	});

	if(categories.length)
	{
		$container.find('.product_browse-product').hide();

		// An and style query via the way we're joining the classes above (no spaces so we're saying show
		// only categories that match .category-665.category-555
		$container.find('.product_browse-product').filter(categories.join('')).show();
	}
}