function submenu(itemMenu, elements, link) {
	var target = $('submenu');
	target.innerHTML = '';
	
	if (itemMenu) {
		var ul = Builder.node('ul');
		
		$A(elements).each(function(item, index) {
			var li = Builder.node('li', [
				Builder.node('a', {
					href: link + '?id=' + item.id
				}, item.title)
			]);
			ul.appendChild(li);
		});

		target.appendChild(Builder.node('div', {className: 'topmenu'}));
		target.appendChild(Builder.node('div', {className: 'contentmenu'}, [ul]));
		target.appendChild(Builder.node('div', {className: 'bottommenu'}));
		target.style.left = Position.cumulativeOffset(itemMenu)[0] + 'px';
				
		Element.show(target);
	} else {
		Element.hide(target);
	}
	
}

function newsletterSubscription(form) {
	form.appendChild(createWaitingObject('newsletterWaiting'));

	var ajaxCall = new Ajax.Request(
		form.action,
		{
			method: 'get',
			parameters: 'ajax=1&' + Form.serialize(form),
			onSuccess: function(response) {
				Element.remove('newsletterWaiting');
				var xml = response.responseXML;
				var root = xml.getElementsByTagName("response").item(0);
				alert(root.firstChild.data);
				$('newsletterEmail').value = '';
				$('aS').checked = true;
			},
			onFailure: function(response) {
				Element.remove('newsletterWaiting');
				alert('Houve um erro ao excecutar a consulta:<br/>' + response.responseText);
			}
		}
	);
}

function shopcartCheckout(form) {
	if (!validateShopcartCheckoutForm(form)) {
		return false;
	}
	
	form.appendChild(createWaitingObject('shopcartCheckoutWaiting'));
	Element.scrollTo(form);
	
	var ajaxCall = new Ajax.Request(
		form.action,
		{
			method: 'post',
			parameters: Form.serialize(form) + '&ajax=1',
			onSuccess: function(response) {
				Element.remove('shopcartCheckoutWaiting');
				var xml = response.responseXML;
				var root = xml.getElementsByTagName("response").item(0);
				alert(root.firstChild.data);
				Element.remove('tablecar');
				new Insertion.Before('shopcartCheckoutForm', shopcartNoitems);
				Element.remove('shopcartCheckoutForm');
			},
			onFailure: function(response) {
				Element.remove('shopcartCheckoutWaiting');
				alert('Houve um erro ao excecutar a consulta:<br/>' + response.responseText);
			}
		}
	)
}

	
function contactUs(form) {
	if (!validateContactForm(form)) {
		return false;
	}
	
	form.appendChild(createWaitingObject('contactUsWaiting'));
	Element.scrollTo(form);
	
	var ajaxCall = new Ajax.Request(
		form.action,
		{
			method: 'post',
			parameters: Form.serialize(form) + '&ajax=1',
				onSuccess: function(response) {
				Element.remove('contactUsWaiting');
				var xml = response.responseXML;
				var root = xml.getElementsByTagName("response").item(0);
				alert(root.firstChild.data);
				form.reset();
			},
			onFailure: function(response) {
				Element.remove('contactUsWaiting');
				alert('Houve um erro ao excecutar a consulta:<br/>' + response.responseText);
			}
		}
	)
}

function shopcartRemove(id) {
	$('quantity_' + id).value = 0;
	shopcartUpdate($('shopcartForm'));
}

function shopcartUpdate(form, callback) {
	form.appendChild(createWaitingObject('shopcartWaiting'));
	
	new Ajax.Request(
		form.action,
		{
			method: 'get',
			parameters: 'ajax=1&' + Form.serialize(form),
			onSuccess: function(response) {
				var xml = response.responseXML;
				var root = xml.getElementsByTagName("shopcart").item(0);
				var products = $A(root.getElementsByTagName('product'));
				
				if (products.length == 0) {
					Element.remove('tablecar');
					new Insertion.Before('shopcartForm', shopcartNoitems);
					Element.remove('bntShopcartCheckout');
					return;
				}
				
				var processedRows = [];
				var countItems = 0;
				products.each(function(item, index) {
					var productId = item.getElementsByTagName('productId').item(0).firstChild.data;
					var totalPrice = item.getElementsByTagName('totalPrice').item(0).firstChild.data;
					var quantity = parseInt(item.getElementsByTagName('quantity').item(0).firstChild.data);
					
					if (quantity == 0) {
						Element.remove($('quantity_' + productId).parentNode.parentNode);
					} else {
						$('totalprice_' + productId).innerHTML = 'R$ ' + totalPrice;
						$('quantity_' + productId).value = quantity;
						countItems += quantity;
					}
					processedRows.push(productId);
				});
				
				$A($('tablecar').getElementsByTagName('input')).each(function(item, index) {
					if (item.name == 'id') {
						if (processedRows.indexOf(item.value) < 0) {
							Element.remove(item.parentNode.parentNode);
						}
					}
				});
				
				//update display
				$('shopcartPrice').innerHTML = 'R$ ' + root.getElementsByTagName('shopcartPrice')[0].firstChild.data;
				$('shopcartCountItems').innerHTML = countItems;
				$('shopcartCountMoney').innerHTML = $('shopcartPrice').innerHTML;
				Element.remove('shopcartWaiting');
				
				if (callback) {
					callback();
				}
				
			},
			onFailure: function(response) {
				Element.remove('shopcartWaiting');
				alert('Houve um erro ao excecutar a consulta:<br/>' + response.responseText);
			}
		}
	);
}

function populateCities(args) {
	//cityObj stateParam cityParam
	
	var img = $('citiesLoading');
	Element.show(img);
	
	args.cityObj.options.length = 0;
	args.cityObj.disabled = true;
	
	var ajaxCall = new Ajax.Request(
		'findCities.do',
		{
			method: 'get',
			parameters: 'id=' + args.stateParam, 
			onComplete: function(xmlResponse) {
				var xml = xmlResponse.responseXML;
				var root = xml.getElementsByTagName("list").item(0);
				var cities = $A(root.getElementsByTagName('city'));
				cities.each(function(city) {
					var cityId = city.getElementsByTagName('id').item(0).firstChild.data;
					var cityName = city.getElementsByTagName('name').item(0).firstChild.data;
					args.cityObj.options[args.cityObj.options.length] = new Option(cityName, cityId, cityId == args.cityParam);
				});
				Element.hide(img);
				args.cityObj.disabled = false;
			},
			onFailure: function(xmlResponse) {
				alert('Houve um erro ao executar consulta:<br/>' + xmlResponse.responseText);
				Element.hide(img);
			}
		}
	);
};

function createWaitingObject(id) {
	var m = 'processando, aguarde...';
	return Builder.node('div', {
		id: id,
		className: 'waiting'
	}, [
		Builder.node('img', {
			src: '/pics/loading.gif',
			alt: m
		}),
		document.createTextNode(m)
	]);
}

Event.observe(window, 'load', function(e) {
	//varre os links do site, e adiciona target blank em links externos
	var host = document.location.host;
	$A(document.getElementsByTagName('a')).each(function(link) {
		var href = link.href;
		if (href && href.indexOf(host) < 0 && href.indexOf('http') >= 0) {
			if (link.rel != 'nomask') {
				link.onclick = function(e) {
					window.open('http://www.google.com/url?sa=D&q=' + this.getAttribute("href"));
					return false;
				}
			}
		}
	});

}, false);

window.alert = function(message) {
	try {
		var newMessage = '';
		var messageSplited = message.toString().split('\n');
		messageSplited.each(
			function(msgElement) {
				newMessage += msgElement + '<br/>';
			}
		);
		var win = new Window('alert' + new Date().getTime(), {
			className: 'alphacube', 
			width:350, 
			height:200, 
			title: 'Mensagem do sistema',
			hideEffect: Element.hide
		});
		win.getContent().innerHTML = newMessage;
		win.showCenter(true);
	} catch(e) {
		//pensar em algo pra fazer aqui
		confirm(e);
	}
};

window.onerror = function tellerror(msg, url, lno) {
	var m  = 'Ocorreu um erro:\n';
	    m += 'msg:  ' + msg + '\n';
	    m += 'url:  ' + url + '\n';
	    m += 'line: ' + lno + '\n';
	alert(m);
};


