﻿var ajaxObj;
	
function addtocart (productId, justupdateprice) {

	ajaxObj = new XMLHTTP("/resources/ajax/mybic_server.php");
	ajaxObj.debug=0;
	
	var options = productId;

	option = document.getElementsByName('options' + productId + '[]');

	for (i=0;i<option.length;i++) {
		
		if(!justupdateprice && option[i].value == 'Escolher') {
			
			alert('Você deve escolher as opções.');
			return;
		}
			
		options = options + ':' + option[i].value;
	}

	ajaxObj.call("action=addtocart&itemOptions=" + options + "&justupdateprice=" + justupdateprice + "&productId=" + productId, respHelloWorld);
}


function respHelloWorld (resp) {

	document.getElementById('priceresponse' + resp['productId']).innerHTML 		= resp['priceresponse'];
	document.getElementById('addtocartresponse' + resp['productId']).innerHTML 	= resp['justupdateprice'] == 1 ? '' : resp['addtocartresponse'];
	
	if(resp['combo'] != false && resp['justupdateprice'] == 1)
	{
		for (i=0;i<resp['combo'].length;i++) {
			
			//Check if the option exist
			if(document.getElementById(resp['combo'][i]['optionName'] + resp['productId']) == null) {
				alert('Erro: A Opção "' + resp['combo'][i]['optionName'] + '" não foi encontrada nesta página.');
				break;
			}
			
			document.getElementById(resp['combo'][i]['optionName'] + resp['productId']).innerHTML = resp['combo'][i]['content'];
		}
	}
	window.location = "/carrinho.html";
}


function deletefromcart() {

	productId = document.getElementsByName('productId[]');

	var itemsSelected = new Array();
	var y = 0;
	
	for (i=0;i<productId.length;i++)
	{
		if (productId[i].checked)
		{
			itemsSelected[y] = i;
			y++;
		}
	}
	
	if(itemsSelected.length == 0) {
		
		alert("Selecione pelo menos um item.");
		return;
	}	
			
	ajaxObj = new XMLHTTP("/resources/ajax/mybic_server.php");
	ajaxObj.debug=0;
	ajaxObj.call("action=deletefromcart&positions=" + itemsSelected.join(','), respDeleteFromCart);
}


function respDeleteFromCart (resp) {

	document.location.reload(true);
}


function clearcart () {
	
	ajaxObj = new XMLHTTP("/resources/ajax/mybic_server.php");
	ajaxObj.debug=0;
	ajaxObj.call("action=clearcart", respClearCart);
}


function respClearCart () {
	
	document.location.reload(true);
}
