var $Y = YAHOO.util;
var qTipX = -310;
var qTipY = -290;
var txTooltip = [];
var tooltip = {
  name : "tooltip",
  offsetX : qTipX,
  offsetY : qTipY,
  tip : null,
  over: false
}

/**
 * Init
 */
function clockInit(){
	var _self = this;
	var divData = $Y.Dom.get('boxHeader').getElementsByTagName('h4')[0];
	
	
	this.updateDate = function() {
		var newDate = new Date();
		var dateDay = newDate.getDate()
		var dateMonth = newDate.getMonth();
		var dateYear = newDate.getYear();
		var dateHour = newDate.getHours();
		var dateMin = newDate.getMinutes();
		var dateSec = newDate.getSeconds();
		
		if (dateYear < 1000) dateYear += 1900;
		var fullDate = dateDay +'/'+ parseInt(dateMonth+1) +'/'+dateYear;
		var fullHours = ((dateHour < 10) ? "0" : "") + dateHour +":"+ ((dateMin < 10) ? "0" : "") + dateMin +":"+ ((dateSec < 10) ? "0" : "") + dateSec;
		
		divData.innerHTML = 'Brasil, '+ fullDate +' '+ fullHours;
		setTimeout(updateDate,1000); 
	}
	
	this.updateDate();
	
	
}

function isDef(S){return(eval('typeof('+S+')')!='undefined'&&eval('typeof('+S+')')!='unknown');}

/**
 * FUNÇÃO PARA NÃR DAR O BUG NO IE
 * @param {Object} div
 * @param {Object} w
 * @param {Object} h
 * @param {Object} src
 */
writeFlash = function (div,w,h,src){
	var width = w;
	var height = h;
	var srcFlash = src;
	var divFlash = $Y.Dom.get(div);
	var htm = [];

	htm.push('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'+width+'" height="'+height+'" id="principal" align="middle">');
	htm.push('<param name="allowScriptAccess" value="sameDomain" />')
	htm.push('<param name="movie" value="' + srcFlash + '" />');
	htm.push('<param name="quality" value="high" />');
	htm.push('<param name="scale" value="noscale" /> ');
	htm.push('<param name="menu" value="false" />');
	htm.push('<param name="wmode" value="transparent" />');
	htm.push('<embed src="' + srcFlash + '" quality="high" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="principal" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	htm.push('</object>');
	divFlash.innerHTML = htm.join('');
}

/**
 * Tooltip
 */
tooltip.init = function () {
	var tipNameSpaceURI = "http://www.w3.org/1999/xhtml";
	if(!tipId){ var tipId = "tooltip";}
	var tipContainer = $Y.Dom.get(tipId);

	if(!tipContainer) {
	  	tipContainer = document.createElementNS ? document.createElementNS(tipNameSpaceURI, "div") : document.createElement("div");
		tipContainer.setAttribute("id", tipId);
		var parentTip = $Y.Dom.get('ctdToolTip');
		if(parentTip) parentTip.appendChild(tipContainer);
	}

	this.tip = $Y.Dom.get(this.name);

	$Y.Event.addListener(document,'mousemove',function(e){tooltip.move(e)})
	
	var imgs = $Y.Dom.getElementsByClassName('tooltip','a');
	for (var _i = 0, lImg = imgs.length; _i < lImg; _i++) {
		$Y.Event.addListener(imgs[_i],'mouseover',function(e,_n){tooltip.over = true; tooltip.show(e,_n)},_i)
	}
	
	$Y.Event.addListener(this.tip,'mouseover', function() { tooltip.over = true })
}

tooltip.show = function (e,index) {
	if (!this.tip) return;
	
	var tTip = $Y.Event.getTarget(e);
	$Y.Dom.setStyle(this.tip,'left',tTip.offsetLeft+10 + 'px')
	$Y.Dom.setStyle(this.tip,'top',tTip.offsetTop+30 + 'px')
	
	
	this.tip.innerHTML = txTooltip[index];
	this.tip.style.display = "block";
}

tooltip.move = function(e){
	var targetTip = $Y.Event.getTarget(e);
	var ctd = $Y.Dom.get('conteudoInterna')
	var ctdToolTip = $Y.Dom.get('ctdToolTip')
	if (targetTip.parentNode.parentNode != ctd && targetTip.parentNode.parentNode != ctdToolTip){
		tooltip.hide()
	}
}

tooltip.hide = function () {
	if (!this.tip) return;
	this.tip.innerHTML = "";
	this.tip.style.display = "none";
}

/**
 * Adicionar ao Favoritos
 */
addFav = function(){
    var url = "http://www.viadeacesso.org.br";
    var title = "Instituto Via de Acesso - (11) 3142-8900";
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}

/**
 * Video
 */
writeVideo = function(){
	var htm = []
	htm.push('<object id="videoVia" width="320" height="240" classid="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95" standby="Loading Windows Media Player components..." type="application/x-oleobject" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112">');
	htm.push('<param name="filename" value="/video/institucional.wmv">');
	htm.push('<param name="ShowControls" value="true">')
	htm.push('<param name="ShowStatusBar" value="false">')
	htm.push('<param name="ShowDisplay" value="false">')
	htm.push('<param name="autoStart" value="false">');
	htm.push('<embed type="application/x-mplayer2" src="/video/institucional.wmv" name="videoVia" id="videoVia" width="320" height="240" autoStart="1" ShowControls="1" ShowStatusBar="0" ShowDisplay="0"></embed>');
	htm.push('</object>');
	
	document.write(htm.join(''))
}


/**
 * Show/Hide Div
 * @param {Object} div
 */
showDiv = function(div){
	$Y.Dom.removeClass(div,'off')
	$Y.Dom.addClass(div, 'on')
}

hideDiv = function(div) {
	$Y.Dom.removeClass(div,'on')
	$Y.Dom.addClass(div, 'off')
}

/**
 * Popup
 */
function openPop(url,w,h,s) {
  var top = (screen.height - h) / 2;
  var left = (screen.width - w) / 2;

  window.open(url, w+h+s, 'width=' + w + ',height=' + h + ',scrollbars=' + s + ',toolbar=0,location=0,status=0,menubar=0,resizable=0,left=' + left + ',top=' + top + '');

}

searchBeetwen = function(findIn,match1,match2,start){
	findIn = findIn.toString();
	if(match2==null){
		return findIn.substring(findIn.indexOf(match1)+match1.length+1,findIn.length);
	}
	return findIn.substring(start,findIn.indexOf(match2)).substring(findIn.length-match1.length+1,findIn.length);
}

var formatMonthDade = function(val) {
	switch(val) {
		case '1' :
			return 'Janeiro';
		case '2' :
			return 'Fevereiro';
		case '3' :
			return 'Março';
		case '4' :
			return 'Abril';
		case '5' :
			return 'Maio';
		case '6' :
			return 'Junho';
		case '7' :
			return 'Julho';
		case '8' :
			return 'Agosto';
		case '9' :
			return 'Setembro';
		case '10' :
			return 'Outubro';
		case '11' :
			return 'Novembro';
		case '12' :
			return 'Dezembro';
	}
}

var handleFailure = function(o) {
	if (o.responseText !== undefined) {
		alert('' +
			'Error: ' + 'Transaction id: ' + o.tId + '\n' +
			'HTTP status: ' + o.status + '\n' +
			'Status code message: ' + o.statusText +
		'');
	}
}

/**
	Ajax basico pra buscar o curso selecionado
*/
var _handleSuccessAgenda = function(o) {
		//alert(o.responseText)
		if (o.responseText !== undefined) {
			var agenda = o.responseText.parseJSON();
			var divAgenda = $Y.Dom.get('divAgenda');
			
			var htm = '';
			$Y.Dom.replaceClass(divAgenda,'off','on');
			for (var j=0;j<agenda.meses.length;j++){
				htm += '<strong>' + formatMonthDade(agenda.meses[j].mes) + '</strong><br />';
				htm += '<ul>';
				for (var i=0; i<agenda.meses[j].dataCurso.length;i++){
					htm += '<li>' + agenda.meses[j].dataCurso[i].data + ' das ' +  agenda.meses[j].dataCurso[i].hora +'</li>';
				}
				htm += '</ul><br /><br />';
				
			}
			divAgenda.innerHTML = htm;
			//divAgenda.getElementsByTagName('ul')[0].innerHTML = htm.join('');
			
			$Y.Dom.get('inscrevase').href = 'capacitacao_cadastro.asp?id_Curso=' + $Y.Dom.get('selCurso').value
			$Y.Dom.get('link_capacitacao').href = 'capacitacao_detalhe.asp?id_Curso=' + $Y.Dom.get('selCurso').value
			
			$Y.Dom.replaceClass($Y.Dom.get('inscrevase'),'off','on');
			$Y.Dom.replaceClass($Y.Dom.get('link_capacitacao'),'off','on');
		}
	}

selAgenda = function() {
	var idCurso = $Y.Dom.get('selCurso').value;
	var url = '/action/selAgenda.asp'
	var params = 'id='+ idCurso
	if (idCurso != '0') {
		var request = $Y.Connect.asyncRequest('GET', url +'?'+ params , {success: _handleSuccessAgenda, failure: handleFailure});
	}
}

cadNews = function() {
	var tipo = $Y.Dom.get('selNewsTipo').value;
	var email = $Y.Dom.get('txtNewsEmail').value;
	var url = '/action/cadNews.asp'
	var params = 'tipo='+ tipo + '&email=' + email;
	var request = $Y.Connect.asyncRequest('GET', url +'?'+ params , {success: _handleSuccessNews, failure: handleFailure});
}

var _handleSuccessNews = function(o) {
	alert('Seus dados foram cadastrados com sucesso.');
	$Y.Dom.get('txtNewsEmail').value = '';
	$Y.Dom.get('selNewsTipo').selectedIndex(0);
}

seleciona = function(selectType, capacitacaoEstudante) {
	var request, params = '';
	var url = '/action/selCapacitacao.asp';
	
	var selCurso = $Y.Dom.get('selCurso');
	var selMes = $Y.Dom.get('selMes');
	var selDia = $Y.Dom.get('selDia');
	var selHorario = $Y.Dom.get('selHorario');
	
	switch(selectType){
		case 'curso':
			var total=parseInt(selMes.options.length)+1, i=1;
			if(selCurso.value!='')params += '&idCurso=' + selCurso.value;
			while(i<=total){
				selMes.remove(i);
				i++;
			}
			if(selCurso.value=='')return;
			selDia.value='';
			selHorario.value='';
			//window.open(url + '?selectType=' + selectType + params)
			 request = $Y.Connect.asyncRequest('GET', url + '?selectType=' + selectType + params, {success: _handleSuccessMes, failure: handleFailure});
			break;
		case 'mes':
			var total=parseInt(selDia.options.length)+1, i=1;
			if(selCurso.value!='')params += '&idCurso=' + selCurso.value;
	
			if(selMes.value!='')params += '&idMes=' + selMes.value;
			while(i<=total){
				selDia.remove(i);
				i++;
			}
			selHorario.value='';
			if(selMes.value=='')return;
			//window.open(url + '?selectType=' + selectType + params)
			request = $Y.Connect.asyncRequest('GET', url  + '?selectType=' + selectType + params, {success: _handleSuccessDia, failure: handleFailure});
			break;
		case 'dia':
			var total=parseInt(selHorario.options.length)+1, i=1;
			if(selCurso.value!='')params += '&idCurso=' + selCurso.value;
	
			if(selMes.value!='')params += '&idMes=' + selMes.value;
			
			if(selDia.value!='')params += '&idDia=' + selDia.value;
			while(i<=total){
				selHorario.remove(i);
				i++;
			}
			if(selDia.value=='')return;
			//window.open(url + '?selectType=' + selectType + params)
			request = $Y.Connect.asyncRequest('GET', url + '?selectType=' + selectType + params, {success: _handleSuccessHora, failure: handleFailure});
			break;
	}
}

var _handleSuccessMes = function(o) {
	if (o.responseText !== undefined) {
		var responseJSon = o.responseText.parseJSON();
		var selMes = $Y.Dom.get('selMes');
		var total=parseInt(selMes.options.length)+1, i=1;
		while(i<=total){
			selMes.remove(i);
			i++;
		}
		
		for (var i=0;i<responseJSon.meses.length;i++) {
			optElement = document.createElement('option');
			optElement.value = responseJSon.meses[i].mes;
			optElement.text = formatMonthDade(responseJSon.meses[i].mes);
			try{
				selMes.add(optElement,null)
			}
			catch(ex){
				selMes.add(optElement)
			}
		}
	}
}

var _handleSuccessDia = function(o) {
	if (o.responseText !== undefined) {
		var responseJSon = o.responseText.parseJSON();
		var selDia = $Y.Dom.get('selDia');
		var total=parseInt(selDia.options.length)+1, i=1;
		while(i<=total){
			selDia.remove(i);
			i++;
		}
		
		var optElement = '';
		for (var i=0;i<responseJSon.dias.length;i++) {
			optElement = document.createElement('option')
			optElement.value = responseJSon.dias[i].dia;
			optElement.text = responseJSon.dias[i].dia;
			try{
				selDia.add(optElement,null)
			}
			catch(ex){
				selDia.add(optElement)
			}
		}
	}
}

var _handleSuccessHora = function(o) {
	if (o.responseText !== undefined) {
		var responseJSon = o.responseText.parseJSON();
		var selHorario = $Y.Dom.get('selHorario');
		var total=parseInt(selHorario.options.length)+1, i=1;
		while(i<=total){
			selHorario.remove(i);
			i++;
		}
		var optElement = '';
		for (var i=0;i<responseJSon.horas.length;i++) {
			optElement = document.createElement('option');
			optElement.value = responseJSon.horas[i].hora;
			optElement.text = responseJSon.horas[i].hora;
			try{
				selHorario.add(optElement,null)
			}
			catch(ex){
				selHorario.add(optElement)
			}
		}
	}
}


function resetCapacitacao(idForm) {
	idForm.reset();
	//$Y.Dom.get('ministrante').innerHTML = '';
}

