function addEvent(obj, evType, fn){
    if (obj.addEventListener)
        obj.addEventListener(evType, fn, true)
    if (obj.attachEvent)
        obj.attachEvent("on"+evType, fn)
}

function addLoadEvent(func) {
  var prevOnload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (prevOnload) {
        prevOnload();
      }
      func();
    }
  }
}
function loadFlash() {
	var so = new SWFObject("/festival/includes/swf/topo_sofumaca.swf", "baner", "780", "250", "6", "");
	so.addParam("wmode", "transparent");
	so.write("banner");
	
	var so = new SWFObject("/festival/includes/swf/xicara_semfumaca.swf", "xicara", "235", "162", "6", "");
	so.addParam("wmode", "transparent");
	so.write("xicara");	
	
	var so = new SWFObject("/festival/includes/swf/rodape.swf", "rodape", "740", "30", "6", "");
	so.addParam("wmode", "transparent");
    so.write("rodape");
}

//gera um fundo transparente
function generateBackGround(status) {
    if(status) {
    	var bg1 = document.body.scrollHeight;
        var bg2 = document.body.offsetHeight;
        var bg3 = document.documentElement.clientHeight;
        var bgHeight = (bg1>bg2)?bg1:bg2;
        bgHeight = (bgHeight>bg3)?bgHeight:bg3;
		
        var div = document.createElement("div");
        div.setAttribute("id", "message-background");
        div.style.height = bgHeight + "px";
        hideSelects(true);
        document.documentElement.scrollTop = 0;
        document.body.appendChild(div);
        return div;

    }  else {
    	if(document.getElementById("message-background"))
			document.body.removeChild($("message-background"));
		hideSelects(false);
		if($("listOfUsers"))
			document.body.removeChild($("listOfUsers"));
    }
}

function hideSelects(status) {
    selects = document.getElementsByTagName("select");
    for(i=0;selects.length>i;i++){
        selects[i].style.visibility=status?"hidden":"visible";
    }
}


/* Eventos carregados no onload */
addLoadEvent(loadFlash)
addLoadEvent(function() {
	getArchive()
	addEvent($("searchYear"), "change", getArchive)
	addEvent($("arquivo"), "submit", submitArchive)
});

function getArchive() {
 	var fldId = $F("searchYear");
	var sCtg = $("searchCategory");
	sCtg.innerHTML="";
	var option = document.createElement("option");
	option.value = "0";
	option.innerHTML = "Aguarde, carregando...";
	sCtg.appendChild(option);
	coreService.getFolders(fldId, null, true, {
		callback:function(dataFromServer) {
		sCtg.innerHTML="";
		var option = document.createElement("option");
		option.value = "0";
		if(dataFromServer.length==0)
			option.innerHTML = "Não há eventos cadastrados";
		else
			option.innerHTML = "Escolha uma categoria";
		sCtg.appendChild(option);
		for(i=0; i<dataFromServer.length; i++) {
			var option = document.createElement("option");
			option.value = dataFromServer[i].alias;
			option.innerHTML = dataFromServer[i].name;
			sCtg.appendChild(option);
		}
		}
	});
}

function submitArchive() {
 	var fldId = $F("searchCategory");
	if(fldId=="0"){
		alert("Escolha uma categoria.");
		return false;
	}
	$("arquivo").action = "/festival/folder/" + $F("searchCategory") +".mmp?yr="+$("searchYear").options[$("searchYear").selectedIndex].innerHTML;
}

function openResource(path, width){
	generateBackGround(true);
	div = document.createElement("div");
	div.setAttribute("id", "popupResource");
	var img = new Image();
	img.setAttribute('src', path)
	if(img.width>720)
		img.width=720;
	div.style.marginLeft= -width/2+"px";
	div.style.width= width+"px";
	img.onload = function() {
		div.appendChild(img)
	}
	//insere botão de fechar
	if(!$("pCloseResource")) {
		var a = document.createElement("a");
		a.setAttribute("id", "pCloseResource");
		a.setAttribute("title", "fechar janela");
		a.setAttribute("href", "#");
		var bt = document.createElement("img");
		bt.setAttribute("src", "/festival/images/bt_gallery_close.gif")
		a.appendChild(bt);
				
		//botão de fechar
		a.onclick = closeResource ;
		div.appendChild(a);
	}
	if($('message-background'))
		$('message-background').onclick = closeResource;
	
	document.documentElement.scrollTop = 0;
	document.body.appendChild(div);
			
}

function closeResource(){
	div = $("popupResource");
	generateBackGround(false);
	document.body.removeChild(div);
	return false;
}

/* Envio de mail */ 
function openMail(type){
	generateBackGround(true);
	div = document.createElement("div");
	div.setAttribute("id", "popupMail");
	document.body.appendChild(div);
	
	if($('message-background'))
		$('message-background').onclick = closeMail;
		
	var url = "/festival/includes/html/"+ type +".html"
	var myAjax = new Ajax.Updater({},url,{ 
		method: 'post',
		evalScripts:true,
		onSuccess: function(request) {
			div.innerHTML = request.responseText;
			document.documentElement.scrollTop = 0;
		}, 
		onFailure: function(request) {
			closeMail();
			generateBackGround(false);
		}	
	});
	if($('message-background'))
		$('message-background').onclick = closeMail;
}
function closeMail(){
	div = $("popupMail");
	generateBackGround(false);
	document.body.removeChild(div);
	return false;
}

function validateForm(type){
	var msg="";
	if($("fromName") && $("fromName").value.replace(/^\s+|\s+$/, "")=="")
		msg+="Campo 'meu nome' é de preenchimento obrigatório.\n"
	if($("fromEmail")){
		if($("fromEmail").value.replace(/^\s+|\s+$/, "")=="")
			msg+="Campo 'meu e-mail' é de preenchimento obrigatório.\n"
		else if($("fromEmail").value.indexOf("@")==-1 || $("fromEmail").value.lastIndexOf(".")==-1 || $("fromEmail").value.indexOf("@")+1 > $("fromEmail").value.lastIndexOf("."))
			msg+="Campo 'meu e-mail' inválido.\n"
	}
	
	if($("toName") && $("toName").value.replace(/^\s+|\s+$/, "")=="")
		msg+="Campo 'amigo' é de preenchimento obrigatório.\n"
	if($("toEmail")){
		if($("toEmail").value.replace(/^\s+|\s+$/, "")=="")
			msg+="Campo 'e-mail' é de preenchimento obrigatório.\n"
		else if($("toEmail").value.indexOf("@")==-1 || $("toEmail").value.lastIndexOf(".")==-1 || $("toEmail").value.indexOf("@")+1 > $("toEmail").value.lastIndexOf("."))
			msg+="Campo 'e-mail' inválido.\n"
	}
	
	if($("message_contact") && $("message_contact").value.replace(/^\s+|\s+$/, "")=="")
		msg+="Campo 'mensagem' é de preenchimento obrigatório.\n"
	
	if(msg.length>0){
		alert(msg);
		return false;
	}
	sendMail(type);
	return false;
}


function sendMail(type) {
	mail.setType(type);
	mail.setAction("/festival/admin.mail.send.action");
	mail.setMessageArea("formMail");
	mail.setLoadingMessage("<p>aguarde, enviando...</p>");
	mail.setLoadingMessageId("loadingMessage");	
	mail.prepareSendMail();
}

var utils = new Utils();
var MailFestival = Class.create();

//estente classe
MailFestival.prototype = Object.extend(new Mail(), {
	//sobreescreve método
   prepareSendMail: function() {
   		var url = this.action;
		var msg = "";
		if(this.type=="invite") {
			var pars= 'to='+ $F("toEmail") + 
					  '&fromEmail=' + $F("fromEmail") + 
					  '&fromName=' + $F("fromName") + 
					  '&toName=' + $F("toName") + 
					  '&message=' + $F("message") +
					  
					  '&subject=' + "Cultura Inglesa Festival - " + $F("fromName") + " lhe enviou um convite." + 
					  '&mailTemplate=' + "festival_invite" +
					  '&pageLink=' + $F("pageLink") +
					  '&pageName=' + $F("pageName") +
  					  '&rnd=' + Math.random()*4; 
		}
		if(this.type=="contact") {
			var pars= 'to=talktous.festival&fromEmail=' + $F("fromEmail") + 
					  '&fromName=' + $F("fromName") + 
					  '&message=' + $F("message_contact") +
					  
					  '&subject=' + "Contato - Cultura Inglesa Festival" + 
					  '&mailTemplate=' + "festival_contact" +
  					  '&rnd=' + Math.random()*4; 
		}
			
		this.setAction(url);
		this.setParams(pars);
		
		//chama método da superclasse
		Mail.prototype.prepareSendMail.call(this);
	}
});
var mail = new MailFestival();