//Ajax object declaration 
var ajaxObj = new XMLHTTP("/ajax/mybic_server.php");

// Ajax debug
ajaxObj.debug=0;

//global declaration
var labels = new Array();
var selected = new Array();
var defaultSelects = new Array();
var valid;
var lastSelected;
var teste;
var id;


/*Returns cost price*/
function catPrices(obj, formName)
{
	disableForm(document.getElementById('form_select'));
	
	reloadSelects(obj);
	
	var postVars = 'action=itemDetailPrices'+ajaxObj.getForm('form_select');
	ajaxObj.call(postVars, respCatPrices);
}

function respCatPrices(resp)
{
	/*Update Price*/
	if(document.getElementById('price') != null)
		document.getElementById('price').innerHTML = resp['price'];
	
	/*Update Retail Price*/
	if(document.getElementById('retailPrice') != null)
		document.getElementById('retailPrice').innerHTML = resp['retailPrice'];

	/*Update Price Savings*/
	if(document.getElementById('priceSavings') != null)
		document.getElementById('priceSavings').innerHTML = resp['yourSavingsPrice'];
	
	/*Update SKU*/
	if(document.getElementById('sku') != null)
		document.getElementById('sku').innerHTML = resp['sku'];
	
	enableForm(document.getElementById('form_select'));	
}

/*returns an addon price*/
function catAddonPrices(obj)
{
	clearMsg()
	disableForm(document.getElementById('form_select'));
	
	var postVars = 'action=itemDetailPrices'+ajaxObj.getForm('form_select');
	ajaxObj.call(postVars, respCatPrices);
}

function respReloadSelects(resp)
{
	var level;
	var arraySelect = new Array();
	var i, j;
	 
	var selects = document.getElementsByName("cost[]")
	
	if (resp.length != 0)
	{
		for (level in resp)
		{	
			selects[level -1].options.length = 0;
			selects[level -1].options[0] = new Option(labels[level -1], "0");
				
			i = 1;
			for (j=0; j < resp[level].length; j++)
			{	
				selects[level -1].options[i] = new Option(resp[level][j]['name'], resp[level][j]['id']);
				
				if (selected[level -1] == resp[level][j]['id'])
					selects[level -1].options[i].selected = true;		
				
				i++;
			}
		}
	}
}

/*Reloads cost Selects with valid options*/
function reloadSelects(obj)
{
	var ids, costIds, i;
	var postVars;

	lastSelected = obj.value;
	
	clearMsg();
	
	costIds = document.getElementsByName("cost[]");
	
	if (labels[0] == null)
	{
		makeLabels();
		makeDefaultSelects();
	}
	teste = obj;
	ids = makeCostsIds(obj);
	
	if (costIds.length == ids.length) {
		isValidOption(ids); }
	else
	{
		postVars = 'action=validCosts&ajaxPost='+ids+'&idItem='+document.getElementsByName("productId")[0].value;
		ajaxObj.call(postVars, respReloadSelects)
	}		
	
}

/*checks if an set of options are valid, if not all cost selects are reloaded
This function prevents a customer to choose a invalid set of options*/
function isValidOption(ids)
{
	var postVars = 'action=isValidOption&ajaxPost='+ids+'&idItem='+document.getElementsByName("productId")[0].value;
	ajaxObj.call(postVars, respIsValidOption)
}

/*make an array of all cost selects labels, like "choose color"*/
function respIsValidOption(resp)
{
	valid = parseInt(resp); 
	ids = makeCostsIds(teste);
	
	if (valid == 0)
		postVars = 'action=validCosts&ajaxPost='+lastSelected+'&idItem='+document.getElementsByName("productId")[0].value; 
	else
	{ 
		respReloadSelects(defaultSelects);
		return 0;
	}
	
	ajaxObj.call(postVars, respReloadSelects);
}


function makeCostsIds(obj)
{
	var costIds;
	var finalArray = new Array(); 
	var i, j;
	
	costIds = document.getElementsByName("cost[]");
	
	j=0;
	for (i=0; i < costIds.length; i++)
	{	
		if (costIds[i].value > 0)
		{
			finalArray[j] = costIds[i].value;
			j++;	
		}
	selected[i] = costIds[i].value;
	}
	
	return finalArray;
	
}


/*make an array of all cost selects labels, like "choose color"*/
function makeLabels()
{
	var selects = document.getElementsByName("cost[]");
	
	for (i=0; i < selects.length; i++)
		labels[i] = selects[i].options[selects[i].length -1].text;
}

/*makes an array of all cost selects*/
function makeDefaultSelects()
{
	var selects = document.getElementsByName("cost[]");
	var i, j, z;
	
	for (i=1; i <= selects.length; i++)
		defaultSelects[i] = new Array();

	for (i=1; i <= selects.length; i++)
		for (j=0; j < selects[i -1].options.length; j++)
		{ 
			if (selects[i -1].options[j].value != 0)
			{
				defaultSelects[i][j] = new Array();
				defaultSelects[i][j]['id'] = selects[i -1].options[j].value;
				defaultSelects[i][j]['name'] = selects[i -1].options[j].text;	
			}
		}
}

/*adds a product to cart*/
function addToCart()
{	
	disableForm(document.getElementById('form_select'));
	
	document.getElementById('msg').innerHTML = "";
	var postVars = 'action=addToCart'+ajaxObj.getForm('form_select');
	ajaxObj.call(postVars, respAddToCart);
	
	/*Cart View call */
	var postVars = 'action=checkCartView';
	ajaxObj.call(postVars, cartView);
}
/*resp add to cart function of ajax*/
function respAddToCart(resp)
{
	if(resp[1] == 1)
	{
		var itemAdded = language['itemAddedRfp'];
		var viewCart = language['viewCartRfp'];
	}
	else
	{
		var itemAdded = language['itemAdded'];
		var viewCart = language['viewCart'];
	}
	
	if(document.getElementById("recommendedItemsPresent").value == 1)
		document.getElementById('msg').innerHTML = itemAdded + '<br />' + '<a href="#recommendedItems">(' + language['recommendedItems'] +'</a> ' + language['or'] + '<a href="/cart.html"> ' + viewCart +')</a>';
	else	
		document.getElementById('msg').innerHTML = itemAdded + '<br />  <a href="/cart.html">(' + viewCart +')</a>';

	enableForm(document.getElementById('form_select'));
}


/*Clears the item message*/
function clearMsg()
{
	document.getElementById('msg').innerHTML = "";
}

/*checks Inventory of a item*/
function checkInventory()
{	
	disableForm(document.getElementById('form_select'));
	
	if (checkBanks(document.getElementById('form_select')) != 0)
	{
		var postVars = 'action=checkInventory'+ajaxObj.getForm('form_select');
		ajaxObj.call(postVars, respCheckInventory);
	}
	else alert( language['chooseAllOptions'] );
	
	enableForm(document.getElementById('form_select'));
}

/*resp check Inventory function of ajax*/
function respCheckInventory(resp)
{
	if (resp == "OFF")
	{
		addToCart();
		return true;
	}
		
	var userQty = document.getElementsByName("productQty");
	
	userQty = parseInt(userQty[0].value);
	resp = parseInt(resp);
	
	if (resp <= 0)
	{
		var but = document.getElementsByName("submit");
		but[0].disabled = true;
		document.getElementById('msg').innerHTML = "This product is unavaiable";
		return true;
	}
	
	if (userQty > resp)
	{
		document.getElementById('msg').innerHTML = "There are only " + resp + " avaiable";
		document.getElementsByName("productQty")[0].value = resp;
	}
	else
		addToCart();
}

function showPicture(id,hide) {
	for(x=1;x<=hide;x++)
		document.getElementById('image'+x).style.display='none';
	
	document.getElementById('image'+id).style.display=''
}

function applyDiscountCoupon()
{
	var postVars = 'action=ajaxDiscount&couponNumber=' + document.getElementById('DiscontCouponField').value + '&idItem=' + document.getElementsByName('productId')[0].value + '&productDefaultPrice=' + document.getElementById('price').innerHTML;
	ajaxObj.call(postVars, respApplyDiscountCoupon);
}

function respApplyDiscountCoupon(resp)
{
	if(resp['msg'].length > 0)
	{
		document.getElementById('msg').innerHTML = resp['msg'];
	}
	else
	{
		document.getElementById('price').innerHTML = '$' + resp['formatedValue'];
		document.getElementById('msg').innerHTML = "";
	}
}
