/**
* Funcoes para aumentar e diminuir o espaço ocupado pelo menu, de modo a este se sobrepor ao cabecalho
*/
function expandDivMenu(){
	var obj = document.getElementById("menuFlash");
	obj.style.height = "400px";
}
function reduceDivMenu(){
	var obj = document.getElementById("menuFlash");
	obj.style.height = "120px";
}
/**
* Funcao chamada pelo Flash para pesquisas
*/
function pesquisar(query){
	var language;

	if (window.document.location.href.indexOf("/en/") != -1){
		language = "en";
	} else {
		language = "pt";
	}
	window.document.location.href = "/pesquisa/bin/runsearchdb.asp?query="+query+"&language="+language;
}

//mootools initializations:
window.addEvent('domready', function() {
	if ($("submenu") === undefined || $("submenu") == null)
		return;
	//find a collection of every ul within a li (submenus)
	var theSlides = $("submenu").getElements("li.expandivel ul");
	//will hold the Fx.Slide objects
	var slideVars = new Array(theSlides.length);

	//handle the slide event on click
	function slideFunction(event, n){
		var e = new Event(event);
		slideVars[n].toggle();
		e.stop();
	}

	function hideFunction(n){
		slideVars[n].hide();
	}

	for(var i=0; i < theSlides.length; i++){
		//add the slide effect to each sublist element
//		slideVars[i] = new Fx.Slide(theSlides[i].getParent(),{
		slideVars[i] = new Fx.Slide(theSlides[i],{
			'onComplete':
				function(outside) {
					var hidden = outside.getParent().getStyle('height') == '0px' ? true : false;
					outside.getParent().setStyle('height','');
					if(window.ie6 && hidden){outside.getParent().setStyle('height','0px')};
					mudarSeta(outside);
				}
		});

		if(theSlides[i].getElements("li.activo").length == 0 && theSlides[i].className.search(/aberto/i) == -1 && theSlides[i].getElements("li.aberto").length == 0)
			this.fireEvent('hideFunction', hideFunction(i));
		else
			mudarSeta(theSlides[i]);

		//hide the sublists initially

		var toggle = theSlides[i].getParent().getParent().getElement("a");
//		alert(theSlides[i].getParent().getParent().innerHTML);	
		toggle.addEvent('click', slideFunction.bindWithEvent(toggle, i));
	}
//alert($("submenu").innerHTML);
});

function mudarSeta(elem){
	/*var li = elem;
	while(li.nodeName.toLowerCase() != "li")
		li = li.parentNode;*/
		//alert(elem.getParent().getParent().innerHTML);
		var img = elem.getParent().getParent().getElement("img");
		var rexp, newImg;
		if(img.src.indexOf("mais") >= 0){
			rexp = /mais/;
			newImg = "menos"
		}
		else{
			rexp = /menos/;
			newImg = "mais";
		}
			
		img.src = img.src.replace(rexp, newImg);
}

function head(title, menuTitle, metaDescription, metaKeywords, scriptsAndStyles){
   	var temp = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">'
		+ '<html>'
		+ '<head>'
		+ '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">';
	if (metaDescription !== undefined && metaDescription.trim().toUpperCase() != "_HEAD_DESCRIPTION_"){
		temp += '<meta  name="Description" content="';
		temp += (metaDescription !== undefined) ? metaDescription : "";
		temp += '">';
	}
	if (metaKeywords !== undefined && metaKeywords.trim().toUpperCase() != "_HEAD_KEYWORDS_"){
		temp += '<meta  name="Keywords" content="'; 
		temp += (metaKeywords !== undefined) ? metaKeywords : "";
		temp += '">';
	}
	temp += ('<title>' + title + '</title>');
	temp = temp + '<link href="/css/styles.css" rel="stylesheet" type="text/css">';
	temp = temp + '<!--[if lt IE 7]>'
		+ '<link href="css/ie.css" rel="stylesheet" type="text/css" />'
		+ '<![endif]-->'
		+ '<link rel="shortcut icon" type="image/ico" href="/favicon.ico">'
		+ '<script src="/Scripts/AC_RunActiveContent.js" type="text/javascript"></script>'
		+ '<script src="/Scripts/mootools-release-1.11.js" type="text/javascript"></script>'
		+ '<script src="/Scripts/functions.js" type="text/javascript"></script>';
	if (scriptsAndStyles !== undefined && scriptsAndStyles.trim() != "_HEAD_SCRIPTS_STYLES_")
		temp += scriptsAndStyles;
	temp += '</head>';
	return temp;
}

function body(contentTitle){
	var temp = '<body>'
	if (contentTitle === undefined || contentTitle.trim().toUpperCase() == "_CONTENT_TITLE_")
		contentTitle = "";
	temp += content(contentTitle);
	return temp;
}

function content(title){
	var temp = '<div class="destaque">'
		+ '<div class="tituloDestaque">'
		+ '<img src="/images/tit_a.png" width="15" height="40" class="tit_esq" alt="">'
		+ '<h2>' + title + '</h2>'
		+ '<img src="/images/tit_c.png" width="15" height="40" class="tit_dir" alt="">'
		+ '</div>'
		+ '<div class="conteudo">'
  		+ '<dl class="evento">'
  		+ '<dd>';
  	return temp;
}

function footer(){
	var temp = '</dd>'
		+ '</dl>'
		+ '</div>'
		+ '</div>'
		+ '</body>'
		+ '</html>';
	return temp;

}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

function getContactsText(){
	if (getLanguage() == "en")
		return "Contacts";
	else
		return "Contactos";
}

function getGoogleMapsText(){
	if (getLanguage() == "en")
		return "Points of interest";
	else
		return "Pontos de interesse";
}

function getSitemapText(){
	if (getLanguage() == "en")
		return "Sitemap";
	else
		return "Mapa do site";
}

function getLanguage(){
	// by ma	var path = Server.MapPath(".");
	try{
		var path = String(Request.ServerVariables("URL"));
	}catch(e){
		var path = location.href;
	}
	if (path.search(/\/en$|\/en\//i) != -1)
		return "en";
	else
		return "pt"
}

function getDefaultDescription(){
	if (getLanguage() == "en")
		return "The Portuguese Vinho Verde Wine is unique, a smooth mix of scent and lightness that makes it as delicious a natural drink can be. Come and taste it with us. Medium in alcohol, Vinho Verde has great digestive properties due to its freshness and special qualities. The CVRVV site contains extensive marketing information covering Vinho Verde, its Region, Main Producers and Brands, Wine Technology, History and Vinho Verde Route.";
	else
		return "O Vinho Verde é um produto único no mundo, uma mistura de aroma e leveza que o torna numa das mais deliciosas bebidas naturais. A Região Demarcada dos Vinhos Verdes estende-se por todo o Noroeste de Portugal, na zona tradicionalmente conhecida como Entre-Douro-e-Minho.Este site contém informação relativa à Região dos Vinhos Verdes, nomeadamente sobre a Comissão de Viticultura da Região dos Vinhos Verdes, Produtores e Marcas, Tecnologia, História da Região e de uma Garrafa, Estatísticas, Notícias da Região e da Rota do Vinho Verde.";
}

function getDefaultKeywords(){
	if (getLanguage() == "en")
		return "Vinho Verde, Wine, Region, Portuguese Wine, Portugal Wine, VQPRD, Wine technology, Wine route, Vinho Verde Region, Wine producers, Wine brands, Grape varieties, Wine history, Viticulture, Natural drink, Wine tourism, Wine trips, vino blanco, white wine, vin blanc";
	else
		return "Vinho Verde, Vinho, Vinhos de Portugal, Minho, Viticultura, VQPRD, Região do Vinho Verde, Rota do Vinho Verde, Norte de Portugal, Demarcada, Verde, Comissão de Viticultura, CVRVV, Enologia, Agricultura, Castas,Quintas, Produtores, Laboratório, Turismo rural, Vinhos de Qualidade";
}

function currentPathObject(){
	var rootPath = Server.MapPath("/");
	var filePath = Server.MapPath(Request.ServerVariables("PATH_INFO"));
	return {root: rootPath, file: filePath, wanted: filePath.replace(rootPath, "").replace(/\\/g, "/")};
}

function searchXMLAttributes(title, wantedPath, root){
	var temp;
	var parent;
	var tempReturnObject = null
	if (root.getAttribute("titulo") == title && root.getAttribute("url").toLowerCase() == wantedPath.toLowerCase()){
		parent = root;
		while(parent.parentNode != root.ownerDocument.firstChild){
			parent = parent.parentNode;
		}
		return {parent: parent, child: root};
	}
	
	for (var i = 0; i < root.childNodes.length; i++){
		temp = searchXMLAttributes(title, wantedPath, root.childNodes[i])
		if (temp != null)
			return temp;
	}
	return tempReturnObject;
}

function appXMLAttributes(title, wantedPath, root){
	var temp;
	var parent;
	if (root.getAttribute("url") != null && root.getAttribute("url").trim() != ""){
		var menuURL = root.getAttribute("url").toLowerCase();
		var match = menuURL.match(/\//g);
		menuURL = menuURL.substring(0, match.lastIndex);
		match = wantedPath.match(/\//g);
		tempWantedPath = wantedPath.substring(0, match.lastIndex);
		if (tempWantedPath.toLowerCase().trim() == menuURL.toLowerCase().trim()){
			parent = root;
			while(parent.parentNode != root.ownerDocument.firstChild){
				parent = parent.parentNode;
		}
		return {parent: parent, child: root};
		}
	}
	for (var i = 0; i < root.childNodes.length; i++){
		temp = appXMLAttributes(title, wantedPath, root.childNodes[i])
		if (temp != null)
			return temp;
	}
	return null;
}

function buildMenu(title, wantedPath, node, allowHref){
	var start = "";
	var end = "";
	var menu = "";
	if (node.childNodes.length != 0){	
		if (node.getAttribute("titulo") == title && node.getAttribute("url").toLowerCase() == wantedPath.toLowerCase()){
			menu += "<li class=\"expandivel aberto activo\">"+
				"<a href=\"\" class=\"expandivel\"><img src=\"/images/mais.png\" width=\"14\" height=\"14\" align=\"left\" /></a>";
			if (allowHref == true)	
				menu += "<a class=\"defaultLink\" href=\"" + (node.getAttribute("url") == "" ? "javascript://" : node.getAttribute("url")) + "\">" +  (node.getAttribute("titulo") == "" ? "??" : node.getAttribute("titulo")) + "</a>\n";
			else
				menu += "<a class=\"specialActivo\" href=\"" + (node.getAttribute("url") == "" ? "javascript://" : node.getAttribute("url")) + "\">" +  (node.getAttribute("titulo") == "" ? "??" : node.getAttribute("titulo")) + "</a>\n";
			menu += "<ul class=\"aberto\">";
		}else{
			menu += "<li class=\"expandivel\">"+
				"<a href=\"\" class=\"expandivel\"><img src=\"/images/mais.png\" width=\"14\" height=\"14\" align=\"left\" /></a>"+
				"<a href=\"" + (node.getAttribute("url") == "" ? "javascript://" : node.getAttribute("url")) + "\">" +  (node.getAttribute("titulo") == "" ? "??" : node.getAttribute("titulo")) + "</a>\n"
			menu +=	"<ul>";
		}
		end = "</ul>\n</li>";
	}else{
		if (node.getAttribute("titulo") == title && node.getAttribute("url").toLowerCase() == wantedPath.toLowerCase()){
			menu += "<li class=\"activo\">"
			if (allowHref == true)
				menu += "<a class=\"defaultLink\" href=\"" + node.getAttribute("url") + "\">" + (node.getAttribute("titulo") == "" ? "??" : node.getAttribute("titulo")) + "</a>";
			else
				menu += (node.getAttribute("titulo") == "" ? "??" : node.getAttribute("titulo"));
		}else{
			menu += "<li><a href=\"" + (node.getAttribute("url") == "" ? "javascript://" : node.getAttribute("url")) + "\">" +  (node.getAttribute("titulo") == "" ? "??" : node.getAttribute("titulo")) + "</a>";
		}
		end = "</li>\n";
	}
		
	for(var i = 0; i < node.childNodes.length; i++)
		menu += buildMenu(title, wantedPath, node.childNodes[i], allowHref);
	menu += end;
	return menu;
}

// função utilizada nas pesquisas das notas de imprensa
function mudaCriterio(aux) {
	var idx = document.frmCriterio.selCriterio.selectedIndex;
	var criterioStr = document.frmCriterio.selCriterio.options[idx].value;
	var valor = "";
	//alert("criterioStr = " + criterioStr);
	var hoje = new Date();
	var hojeStr;
	var ano = hoje.getFullYear() + "";
	var mes = hoje.getMonth()+1 + "";
	var dia = hoje.getDate() + ""; 
	hojeStr = ano + "-" + mes + "-" + dia;
	//alert("hoje = " + hojeStr);
	if(criterioStr != "publicacao") {
		if(criterioStr == "data") {
			if(aux == 1) {
				var dest = "internacionais.asp?criterio=" + criterioStr + "&valor=" + hojeStr;
			} else {
				var dest = "default.asp?criterio=" + criterioStr + "&valor=" + hojeStr;
			}
		} else {
		    //alert("x");
		    if(aux == 1) {
				var dest = "internacionais.asp?criterio=" + criterioStr + "&valor=escreva aqui palavras para pesquisa";
			} else {
				if(aux == 2) {
					var dest = "default.asp?criterio=" + criterioStr + "&valor=write here words to search";
				} else {
					var dest = "default.asp?criterio=" + criterioStr + "&valor=escreva aqui palavras para pesquisa";
				}
			}
		}
	} else {
		if(aux == 1) {
			var dest = "internacionais.asp";
		} else {
			var dest = "default.asp";
		}
	}
	window.location.href = dest;
}

function mudaValor(aux) {
	var idx = document.frmCriterio.selCriterio.selectedIndex;
	var criterioStr = document.frmCriterio.selCriterio.options[idx].value;
	idx = document.frmValor.selValor.selectedIndex;
	var valorStr = document.frmValor.selValor.options[idx].value;
	if(aux == 1) {
		var dest = "internacionais.asp?criterio=" + criterioStr + "&valor=" + valorStr;
	} else {
		var dest = "default.asp?criterio=" + criterioStr + "&valor=" + valorStr;
	}
	window.location.href = dest;
}

function isValidDate(dateStr, format) {
   if (format == null) { format = "YMD"; }
   format = format.toUpperCase();
   if (format.length != 3) { format = "YMD"; }
   if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || 
      (format.indexOf("Y") == -1) ) { format = "YMD"; }
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
      var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
   } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
   } else { // The year must be third
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
   }
   // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
   if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") { var mm = parts[0]; } else 
      if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; }
   if (format.substring(0, 1) == "D") { var dd = parts[0]; } else 
      if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; }
   if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else 
      if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; }
   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
   return true;
}

function verificaData(aux) {
	//alert("dt = " + document.frmValor.txtData.value);
	if(!isValidDate(document.frmValor.txtData.value, "YMD")) {
		if(aux == 2) {
			alert("The date must be year-month-day.");
		} else {
			alert("A data deve ser inserida no formato ano-mês-dia.");
		}
	} else {
		var idx = document.frmCriterio.selCriterio.selectedIndex;
		var criterioStr = document.frmCriterio.selCriterio.options[idx].value;
		if(aux == 1) {
			var dest = "internacionais.asp?criterio=" + criterioStr + "&valor=" + document.frmValor.txtData.value;
		} else {
			var dest = "default.asp?criterio=" + criterioStr + "&valor=" + document.frmValor.txtData.value;
		}
		window.location.href = dest;
	}
}

function verificaTitulo(aux) {
	var idx = document.frmCriterio.selCriterio.selectedIndex;
	var criterioStr = document.frmCriterio.selCriterio.options[idx].value;
	if(aux == 1) {
		var dest = "internacionais.asp?criterio=" + criterioStr + "&valor=" + document.frmValor.txtTitulo.value;
	} else {
		var dest = "default.asp?criterio=" + criterioStr + "&valor=" + document.frmValor.txtTitulo.value;
	}
	window.location.href = dest;
}

function my_replace(str, procura, substitui) {
	return str.replace(new RegExp(procura, "g"), substitui);
}

function mudaOrigem() {
	//alert("origem recebida: " + document.frmObterIndicacoes.txtOrigem.value);
	var origem = document.frmObterIndicacoes.txtOrigem.value + "";
	origem = my_replace(origem, " ", "+");
	origem = my_replace(origem, "ç", "%C3%A7");
	origem = my_replace(origem, "ã", "%C3%A3");
	origem = my_replace(origem, "õ", "%C3%B5");
	origem = my_replace(origem, "á", "%C3%A1");
	origem = my_replace(origem, "â", "%C3%A2");
	origem = my_replace(origem, "ó", "%C3%B3");
	origem = my_replace(origem, "é", "%C3%A9");
	origem = my_replace(origem, "í", "%C3%AD");
	//alert(origem);
	var dest = "http://maps.google.pt/maps?f=d&source=s_d&saddr=" + origem + "&daddr=Rua+da+Restaura%C3%A7%C3%A3o,+318,+4050-501+Porto+(Comiss%C3%A3o+de+Viticultura+da+Regi%C3%A3o+dos+Vinhos+Verdes+(CVRVV))&hl=pt-PT&geocode=%3BFQrVcwIdLGx8_yGGYhMdo26CTg&mra=ls&sll=41.14561,-8.62306&sspn=0.006948,0.011137&ie=UTF8&t=h&z=15";
	window.open(dest);	
}