//Simula import das classes
document.write("<script type='text/javascript' src='source/script/DVComponentsSimple.js'></script>");
document.write("<script type='text/javascript' src='source/script/components/GroupComponents.js'></script>");
document.write("<script type='text/javascript' src='source/script/components/DVQuiz/DVQuiz.js'></script>");
document.write("<script type='text/javascript' src='source/script/components/DVDarkMask/DVDarkMask.js'></script>");
document.write("<script type='text/javascript' src='source/script/components/DVButton/DVButton.js'></script>");
document.write("<script type='text/javascript' src='source/script/components/DVTabPanel/DVTabPanel.js'></script>");
document.write("<script type='text/javascript' src='source/script/components/DVPhotoGalery/DVPhotoGalery.js'></script>");
document.write("<script type='text/javascript' src='source/script/Sprite.js'></script>");

//--------------------------------------------------------------------------------------------------
document.ISGECKO = /gecko/i.test(navigator.userAgent);
document.ISFF3 = /Firefox\/3/i.test(navigator.userAgent);
document.ISMSIE  = /MSIE/.test(navigator.userAgent);
document.ISMSIE6  = /MSIE 6/.test(navigator.userAgent);
document.MH = 475; //nim-height
//document.NOBOX = function(){ return gE('scapevalve')};
document.COLOR = new Color();
util = new Util();
saveFilters.filters = false;
orderNews.orders = [[0,false,'DTNOTICIA'],[1,false,'CATEGORIA'],[2,false,'TITULOPRINCIPAL']];

//--------------------------------------------------------------------------------------------------
function gE(str)
{
	return document.getElementById(str);
}
//--------------------------------------------------------------------------------------------------
function loadNews(id)
{
	var f = (arguments.length > 1) ? 1 : 0;
		
	var a = new Ajax("requests/noticias.php?idn="+id+"&f="+f);
	a.showLoading(gE('ajaxbox'),"carregando notícia, aguarde...");
	a.execInside = function()
	{
		checkMinHeight(gE('ajaxbox'),document.MH);
		var bot = new DVButton(gE('_back'),'Voltar',[1,7],3);
		bot.setTitle("Voltar a página principal");
		bot.obj.onclick = function(){loadPage('home')}

		var bot1 = new DVButton(gE('allnews'),'Ver todas as notícias',[19,2],3);
			bot1.alignTo('right');
			bot1.setTitle("clique para ver todas as notícias");
			bot1.obj.onclick = function(){loadPage('bancodenoticias');}
		window.scrollTo(0,0)
	}
	a.ajaxRetriev(gE('ajaxbox'));
}
//--------------------------------------------------------------------------------------------------
function loadHorarios(nome,id)
{
	var a = new Ajax("requests/horarios.php");
	a.showLoading(gE('ajaxbox'),"carregando horários, aguarde...");
	a.vars.add(['polo',nome]);
	a.vars.add(['poloid',id]);
	a.execInside = function()
	{
		checkMinHeight(gE('ajaxbox'),document.MH);
		var bot = new DVButton(gE('_back'),'Voltar',[1,7],3);
		bot.setTitle("Voltar a página principal");
		bot.obj.onclick = function(){loadPage('home')}
		window.scrollTo(0,0)
	}
	a.ajaxRetriev(gE('ajaxbox'));
}
//--------------------------------------------------------------------------------------------------
function loadInst(pagina)
{
	var a = new Ajax("requests/instituicao/"+pagina+".php");
	a.showLoading(gE('ajaxbox'),"carregando informações, aguarde...");
	a.execInside = function()
	{
		var bot = new DVButton(gE('_back'),'Voltar',[1,7],3);
		bot.setTitle("Voltar a página principal");
		bot.obj.onclick = function(){loadPage('home')}
		window.scrollTo(0,0)
	}
	a.ajaxRetriev(gE('ajaxbox'));
}
//--------------------------------------------------------------------------------------------------

function loadPage(page)
{
	var a = new Ajax("requests/"+page+".php");

	switch(page)
	{
		case 'posgraduacao':
			a.execInside = function()
			{
				posgradPage();
				//checkMinHeight(gE('internalbox'),document.MH);
			}
			break;
		case 'home':
			a.execInside = function()
			{
				//var quiz1 = new DVQuiz(1,gE('quiz1'));
				checkMinHeight(gE('ajaxbox'),document.MH);
				var bot1 = new DVButton(gE('allnews'),'Ver todas as notícias',[19,2],3);
					bot1.alignTo('right');
					bot1.obj.style.marginTop='2px';
					bot1.setTitle("clique para ver todas as notícias");
					bot1.obj.onclick = function(){loadPage('bancodenoticias');}
				
						//var b = new Sprite("images/banners/parceiros.jpg",6,gE('containerparc'));
						//b.speed = 2000;
						//b.showframe = true;
						//b.setPosition(0,0);
						//b.play();
			}
			break;
		case 'bancodenoticias':
			a.execInside = function()
			{
				checkMinHeight(gE('ajaxbox'),document.MH);
				if(saveFilters.filters != false)
					reloadFilters();
				
				filterNews()
				var bot = new DVButton(gE('_back'),'Voltar',[1,7],3);
				bot.setTitle("Voltar a página principal");
				bot.obj.onclick = function(){loadPage('home')}

				var bot2 = new DVButton(gE('fnews'),'Buscar Notícias',[19,2]);
					bot2.alignTo('right');
					bot2.obj.onclick = function(){filterNews()}
			}
			break;
		case 'contato':
			a.execInside = function()
			{
					gE('nome').focus();
					var bot = new DVButton(gE('btsend'),'Enviar Mensagem',[14,8],3);
					bot.alignTo('right');
					bot.obj.onclick = function(){if(checkMail()) sendMail()}
					checkMinHeight(gE('ajaxbox'),document.MH);
			}
			break;
		default:
			a.execInside = function()
			{
				var bot = new DVButton(gE('_back'),'Voltar',[1,7],3);
				bot.setTitle("Voltar a página principal");
				bot.obj.onclick = function(){loadPage('home')}
				checkMinHeight(gE('ajaxbox'),document.MH);
			}
	}
	
	//gE('ajaxbox').innerHTML = "<p id = 'loading'><b><img src = 'intranet/images/loadings/05.gif'/><br />carregando página, aguarde...</b></p>";
	a.execInsideComp = function(){window.scrollTo(0,0)}
	a.showLoading(gE('ajaxbox'),"carregando página, aguarde...");
	a.ajaxRetriev(gE('ajaxbox'));
}
//--------------------------------------------------------------------------------------------------
selectNews.act = 0;
function init()
{
	var x = new ExtendedDate(new Date());
	//gE('barra').firstChild.nodeValue = "Gurupi, "+x.getDayName()+", "+x.d.getDate()+" de "+x.getMonthName()+" de "+x.d.getFullYear();
	loadPage('home');
	var bot = new DVButton(gE('_close'),'fechar',[7,8],2);
	bot.alignTo('right');
	bot.obj.onclick = function(){gE('popup').style.display='none'}
	gE('popup').appendChild(bot.obj);
}
//--------------------------------------------------------------------------------------------------
function antiImageCash()
{
	return "?anticash="+Math.random()+""+Math.random();
}
//--------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------
function selectNews(pos)
{
	if(selectNews.act == pos) 
		return false;
		
	var _li = gE('newsbox').getElementsByTagName('li');

	selectNews.old = selectNews.act;
	selectNews.act = pos;

		_li[selectNews.act].className = 'check';
		_li[selectNews.old].className = '';
	
	gE('_leg').firstChild.nodeValue = _li[selectNews.act].getAttribute('leg');
	gE('_pp').firstChild.nodeValue = _li[selectNews.act].getAttribute('_pp');
	gE('_tp').firstChild.nodeValue = _li[selectNews.act].getAttribute('_tp');
	gE('_cre').firstChild.nodeValue = _li[selectNews.act].getAttribute('_cf');
	gE('_imgnews').src = preCharge.matriz[selectNews.act].src;
}
//--------------------------------------------------------------------------------------------------
function marquee()
{
	/*obj = gE('marq');
	if(obj.firstChild.nodeValue.length)
		obj.firstChild.nodeValue = obj.firstChild.nodeValue.substr(1,obj.firstChild.nodeValue.length);
	else
		obj.firstChild.nodeValue = startMarquee.def;
		*/
}

function startMarquee(obj)
{
	/*startMarquee.def = obj.getElementsByTagName('span')[0].firstChild.nodeValue;
	obj.getElementsByTagName('span')[0].setAttribute('id','marq');
	window.time = setInterval('marquee()',90);*/
}

function orderNews(pos)
{
	//ordena a sequencia de exibição dos filtros do header da tabela, f...
	for(var i = 0; i< 3; i++)
		if(!orderNews.orders[i][0])
			break;

	orderNews.orders[pos][1] = !orderNews.orders[i][1];
	orderNews.orders[i][0] = orderNews.orders[pos][0];
	orderNews.orders[pos][0] = 0;
	filterNews();
}
//--------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------
function saveFilters()
{
	saveFilters.filters = {
					keyword:gE('keyword').value,
					filtertxt:gE('filtertxt').checked,
					expanded:gE('expanded').checked,
					onlyf:gE('onlyf').checked,
					limit:gE('limit').value,
					cat:gE('cat').value,
					order:orderNews.orders
				  }
 }
//--------------------------------------------------------------------------------------------------
function reloadFilters()
{
	gE('keyword').value = saveFilters.filters.keyword;
	gE('filtertxt').checked = saveFilters.filters.filtertxt;
	gE('expanded').checked = saveFilters.filters.expanded;
	gE('onlyf').checked = saveFilters.filters.onlyf;
	gE('limit').value = saveFilters.filters.limit;
	gE('cat').value = saveFilters.filters.cat;
	orderNews.orders = saveFilters.filters.order;
}
//--------------------------------------------------------------------------------------------------
function filterNews()
{
	var a = new Ajax("requests/filternews.php");
	a.execInside = function()
	{
		gridColors(gE('gridnews'));
		checkMinHeight(gE('ajaxbox'),document.MH);
	}
	
	
	var order = [];
	for(var i = 0; i< 3; i++)
	{
		switch(orderNews.orders[i][0])
		{
			case 0:
				order[0] = orderNews.orders[i][2]+(orderNews.orders[i][1] ? ' ASC' : ' DESC');
				break;
			case 1:
				order[1] = orderNews.orders[i][2]+(orderNews.orders[i][1] ? ' ASC' : ' DESC');
				break;
			case 2:
				order[2] = orderNews.orders[i][2]+(orderNews.orders[i][1] ? ' ASC' : ' DESC');
		}
	}
	
	var fdt_opt = gE('fdt').getElementsByTagName('input');
	
	for(var i = 0; i< fdt_opt.length; i++)
		if(fdt_opt[i].checked)
			break;
	a.vars.add(['data',fdt_opt[i].value]);
	a.vars.add(['keyword',gE('keyword').value]);
	a.vars.add(['filtertxt',gE('filtertxt').checked  ? 1 : 0]);
	a.vars.add(['expanded',gE('expanded').checked ? 1 : 0]);
	a.vars.add(['onlyf',gE('onlyf').checked ? 1 : 0]);
	a.vars.add(['limit',gE('limit').value]);
	a.vars.add(['cat',gE('cat').value]);
	a.vars.add(['order',order.join(',')]);

	a.vars.add(['order_dat',orderNews.orders[0][1] ? 1 : 0]);
	a.vars.add(['order_cat',orderNews.orders[1][1] ? 1 : 0]);
	a.vars.add(['order_tit',orderNews.orders[2][1] ? 1 : 0]);

	a.showLoading(gE('boxfilternews'),"carregando notícias, aguarde...");
	a.ajaxRetriev(gE('boxfilternews'));
		
}
//--------------------------------------------------------------------------------------------------
// Faz o pré-carregamento das imagens das notícias
//--------------------------------------------------------------------------------------------------
function preCharge()
{
	var _li = gE('newsbox').getElementsByTagName('li');
	preCharge.matriz = [];
	for(var i = 0; i< 3; i++)
	{
		preCharge.matriz[i] = new Image();
		preCharge.matriz[i].src = 'intranet/source/calls/mods/cads/nots/photos/ok/'+_li[i].getAttribute('idf')+antiImageCash();
	}
}
//--------------------------------------------------------------------------------------------------
// Faz a verificação e o envio dos emails
//--------------------------------------------------------------------------------------------------
function checkMail()
{
	if(gE('nome').value == '')
	{
		alert('campo [nome] não preenchido!');
		gE('nome').focus();
		return false;
	}

	if(gE('mail').value == '')
	{
		alert('campo [email] não preenchido!');
		gE('mail').focus();
		return false;
	}
	
	if(gE('tel').value == '')
	{
		alert('campo [telefone] não preenchido!');
		gE('tel').focus();
		return false;
	}
	if(gE('ass').value == '')
	{
		alert('campo [assunto da mensagem] não preenchido!');
		gE('ass').focus();
		return false;
	}

	if(gE('msg').value == '')
	{
		alert('campo [mensagem] não preenchido!');
		gE('msg').focus();
		return false;
	}
	
	return true;
}
//--------------------------------------------------------------------------------------------------
// Faz a verificação e o envio dos emails
//--------------------------------------------------------------------------------------------------
function sendMail()
{
	var a = new Ajax("requests/sendmail.php");
	createShadow(" ");
	a.vars.add(['nome',gE('nome').value],'nochangecase');
	a.vars.add(['mail',gE('mail').value],'nochangecase');
	a.vars.add(['tel',gE('tel').value]);
	a.vars.add(['ass',gE('ass').value],'nochangecase');
	a.vars.add(['to',gE('to').value],'nochangecase');
	a.vars.add(['msg',gE('msg').value],'nochangecase');
	a.execInside = function()
	{		
		if(parseInt(wr))
		{
			alert('sua mensagem foi encaminhada com sucesso\ne será respondida o mais rápido possível.')
			gE('nome').value = '';
			gE('mail').value = '';
			gE('tel').value = '';
			gE('ass').value = '';
			gE('msg').value = '';
			gE('nome').focus();
		}
		else
		{
			alert('ocorreram problemas, sua mensagem não pode ser enviada, tente novamente em alguns minutos');
			gE('nome').focus();
		}
		
		removeShadow();
	}
	a.ajaxRetriev(document.NOBOX);
	
}
//------------------------------------------------------------------------------------------
	function dfMask(e,l,s,c,f) 
	{
		//110,190,188
		//------------------------------------------------------------------------------------------
		// e = evento / l = array de tamanho dos segmentos / t = tamanho da string
		//s = spacamento, c = caracter do spacamento
		// função retorna true qdo a mascara estiver completamente preenchida
	    // f = fixed tape mode, number or char (N,C)
		m = 0;  //tamanho máximo da entrada
		var t,sta,end;// target // start select // fim select
		var lim = new Array();  
		var exc = new Array(8,9,17,116) // exceções | inicialmente só backspace,tab,ctrl e f5
		if(arguments.length > 5)
			exc = new Array(8,9,17,116,110,190); // forma cachorra, melhorar depois
		c = new Array(s+1).join(c);
		t = (document.ISGECKO) ? e.currentTarget : e.srcElement;
		
		if(document.ISGECKO)
		{
			sta = end = t.selectionStart;
		}
		else
			sta = end = Math.abs(document.selection.createRange().moveStart("character", -1000000));		
		
		if(!t.value.length) // adiciona só no lenght 0, não há necessidade de repetição
		{
			if(document.ISGECKO)
			{
				t.onclick  = function(){t.selectionStart = t.value.length; t.selectionEnd   = t.value.length;}
				t.onselect = function(){t.selectionStart = t.value.length; t.selectionEnd  = t.value.length;}
			}
			else
			{
				t.onclick = function(e){var range = t.createTextRange(); range.moveStart("character", t.value.length); range.moveEnd("character", t.value.length); range.select();}
				t.onselect = function(e){var range = t.createTextRange(); range.moveStart("character", t.value.length); range.moveEnd("character", t.value.length); range.select();}
			}
		}
		for(var i in l){ m+= l[i]; lim[i] = (m+(s*i));}
		
		m = (m + (l.length - 1)*s);
		
        switch(f)
        {
            case 'N':
                var flag = (e.keyCode > 105 || e.keyCode < 48 || (e.keyCode > 57 && e.keyCode < 96)); 
            	break;
            case 'C':
                var flag = !(e.keyCode > 105 || e.keyCode < 48 || (e.keyCode > 57 && e.keyCode < 96)); 
        		break;
        }
        
        if(flag || t.value.length >= m) // apenas números
		{
			for(var i in exc)  // percorre o vetor de exceções
			{
				if(exc[i] == e.keyCode)
				{
					for(var j in lim)
					{
						if(sta == (lim[j]+s+1))
						{
							if(e.keyCode == 8) // inicialmente sem sentido (1 valor apenas)
							{
								t.value = t.value.substr(0,t.value.length-s);
							}
							else
								continue;
						}
					}
					return false;
				}
			}
			
			try{e.preventDefault();}catch(err){e.returnValue = false}
			
			return ((t.value.length+1) >=m) ? true : false;
		}
		else
		{
			for(var i = 0; i< l.length -1; i++) 
				if(t.value.length == lim[i])
					t.value += c;
				
			return ((t.value.length+1) >=m) ? true : false;
		}
	}
//--------------------------------------------------------------------------------------------------
	function showDarkMask(id)
	{
		if(showDarkMask.arguments.length == 2)
		{
			try{document.body.removeChild(document.getElementById(id))}catch(err){}
			return;
		}
		
		var darkmask = 	document.createElement('div'); // container box
		var scr = new getAbsoluteScreenSize();
		
		darkmask.style.position='absolute';
		darkmask.style.left='0';
		darkmask.style.top='0';
		darkmask.style.backgroundColor='#000';
		var o = (showDarkMask.arguments.length == 3) ? showDarkMask.arguments[2] : 0;
		o = document.ISGECKO ? o : (o*100); 
		document.ISGECKO ? darkmask.style.MozOpacity = o : darkmask.style.filter = 'alpha(opacity='+o+')';
        darkmask.style.width= scr.getWidth() + 'px';
        darkmask.style.zIndex = '5';
		darkmask.style.height= scr.getHeight() + 'px';
		darkmask.setAttribute('id',id);
	
		document.body.appendChild(darkmask);
	}
//--------------------------------------------------------------------------------------------------
	createShadow = function(str)
	{
		var selects = document.getElementsByTagName('select');
	      
	    for(var i = 0; i< selects.length; i++)
			if(document.ISMSIE) selects[i].style.visibility='hidden';
		//document.body.style.overflow='hidden';
		showDarkMask('_shadow',0,0.80);
        var sz = new getAbsoluteScreenSize();
		
		gE('_shadow').innerHTML = "<p id = 'loading' style = 'z-index:1; position:absolute; opacity:1;margin:0; padding:0; top:1px; right:1px;'><b><img src = 'intranet/images/loadings/05.gif'/><br />enviando email, aguarde...</b></p>";
	}
//--------------------------------------------------------------------------------------------------
    removeShadow = function()
	{
        var selects = document.getElementsByTagName('select');
        
        for(var i = 0; i< selects.length; i++)
			if(document.ISMSIE) selects[i].style.visibility='visible';

		document.body.removeChild(gE('_shadow'));
	}
//--------------------------------------------------------------------------------------------------
	function getAbsoluteScreenSize()
	{
		var lure = document.body.appendChild(document.createElement('b'));
		lure.style.position='absolute';
		lure.style.fontSize=0;
		lure.style.padding=0;
		lure.style.right=0;
		lure.style.bottom=0;
		
		this.getWidth = function getWidth(){return lure.offsetLeft};
		this.getHeight = function getHeight(){return lure.offsetTop};
	}
//--------------------------------------------------------------------------------------------------
function fotoGalery()
{
	document.PG = new DVPhotoGalery(1);
}
//--------------------------------------------------------------------------------------------------
function loadPos(cont)
{
	var a = new Ajax("requests/posgraduacao/"+cont+".php");
	a.showLoading(gE('internalbox'),"carregando informações, aguarde...");
	
	switch(cont)
	{
		case 'cursos':
			a.execInside = function()
			{
				checkMinHeight(gE('ajaxbox'),document.MH);
			}
			break;
		default:
			a.execInside = function()
			{
				checkMinHeight(gE('ajaxbox'),document.MH);
			}
	}
	a.ajaxRetriev(gE('internalbox'));
}
//--------------------------------------------------------------------------------------------------
function checkMinHeight(box,h)
{
	box.style.height = (box.clientHeight < h) ? h+'px' : 'auto';
}
function loadCurso(cur)
{
	var a = new Ajax("requests/posgraduacao/cursos/"+cur+".php");
	a.showLoading(gE('internalbox'),"carregando curso, aguarde...");
	a.execInside = function()
	{
		var b = new DVButton(gE('internalbox').appendChild(document.createElement('span')),"Voltar",[1,7]);
		b.obj.onclick = function(){loadPos('cursos')}
		gE('internalbox').insertBefore(b.obj,gE('internalbox').getElementsByTagName('h1')[0]);
	}
	a.ajaxRetriev(gE('internalbox'));
}
//--------------------------------------------------------------------------------------------------
function posgradPage()
{
	var grupo = new GroupComponents(1);
	var _cur = new DVButton(gE('cur'),'Cursos',[14,8]);
			_cur.obj.style.marginRight='1px';
/*	var _per = new DVButton(gE('per'),'Perfil profissional',[14,8]);
			_per.obj.style.marginRight='1px';
	var _sel = new DVButton(gE('sel'),'Conteúdos',[14,8]);
			_sel.obj.style.marginRight='1px';
	var _com = new DVButton(gE('com'),'Composição das Turmas',[14,8]);
			_com.obj.style.marginRight='1px';
	var _tcc = new DVButton(gE('tcc'),'TCC Pós',[14,8]);
			_tcc.obj.style.marginRight='1px';
	grupo.addElements(_cur,_per,_sel,_com,_tcc);*/

	grupo.setActive(_cur.obj);
	loadPos('cursos');
	
	//adiciona eventos
	_cur.obj.onclick = function(){loadPos('cursos')}
	//_per.obj.onclick = function(){loadPos('perfil')}
	//_sel.obj.onclick = function(){loadPos('conteudos')}
	//_com.obj.onclick = function(){loadPos('composicao')}
	//_tcc.obj.onclick = function(){loadPos('tcc')}
}














	
	