var stateOfBody="edit";



function FechaPopupDiv(popupdiv){


	var oDiv = document.getElementById(popupdiv);

	document.body.removeChild(oDiv);

}



function openModule(url, name, width, height)

			{ var winWidth = width;

  			  var winHeight = height;

			  var winTop = parseInt((screen.availHeight - winHeight) / 2);

			  var winLeft = parseInt((screen.availWidth - winWidth) / 2);



			  popupWin = window.open(url,name,"width=" + winWidth + ",height=" + winHeight + ",top=" + winTop + ",left=" + winLeft + ",resizable=no,scrollbars=yes,statusbar=yes");

			  if (popupWin.opener == null) popupWin.opener = self;

			}

function openWindow(url, name)

			{ var winWidth = 420;

  			  var winHeight = 500;

			  var winTop = parseInt((screen.availHeight - winHeight) / 2);

			  var winLeft = parseInt((screen.availWidth - winWidth) / 2);



			  popupWin = window.open(url,name,"width=" + winWidth + ",height=" + winHeight + ",top=" + winTop + ",left=" + winLeft + ",resizable=no,scrollbars=yes,statusbar=yes");

			  if (popupWin.opener == null) popupWin.opener = self;

			}



function openPopup(url)

			{ var winWidth = 430;

  			  var winHeight = 500;

			  var winTop = parseInt((screen.availHeight - winHeight) / 2);

			  var winLeft = parseInt((screen.availWidth - winWidth) / 2);



			  popupWin = window.open(url,'ModuloEspecial',"width=" + winWidth + ",height=" + winHeight + ",top=" + winTop + ",left=" + winLeft + ",resizable=no,scrollbars=yes,statusbar=yes");

			  if (popupWin.opener == null) popupWin.opener = self;

			}



function redirecionaAssistente(){

	window.open('assistente.cgi?op=assistente&passo=1', 'assistente');
	window.close();

}





function criarNovaPagina(opcao){

if (idStatusEdicao==0){

	var winTop = parseInt((screen.availHeight - 100) / 2);
	var winLeft = parseInt((screen.availWidth - 300) / 2);

	var maindiv = document.createElement('DIV');

	maindiv.id = "alerta";

    	maindiv.style.width = "300px"

    	maindiv.style.height = "100px";

  	maindiv.style.border= "solid 1px #CFE2F1";

    	maindiv.style.background= "#ffffff";

    	maindiv.style.top= winTop + "px";

    	maindiv.style.left= winLeft + "px";

    	maindiv.style.position= "absolute";

    	maindiv.style.display= "block";

	salvaHtml = '<p style="color:#3182C2;">Salve sua página atual antes de criar uma nova página.<br>Caso não tenha salvo, o conteúdo não salvo será perdido.<br>Deseja continuar?</p>';

	if (opcao=='fechar'){
	
		salvaHtml += '<input type="button" name="btn_sim" value="Sim" onclick="window.close();" />&nbsp;&nbsp;&nbsp;';
		
	}else{	
		salvaHtml += '<input type="button" name="btn_sim" value="Sim" onclick="redirecionaAssistente();" />&nbsp;&nbsp;&nbsp;';

	}

	salvaHtml += '<input type="button" name="btn_nao" value="Não" onclick="document.body.removeChild('
	
	salvaHtml += "document.getElementById('alerta'));";

	salvaHtml += '">';

	maindiv.innerHTML = salvaHtml;

	divBody = document.body;

	divBody.appendChild(maindiv);	
}else{
	if (opcao=='fechar'){
		window.close();
	}else{
		redirecionaAssistente();
	}
}

}



function adicionaModulo(Template){

	if (numeroColunas>1){

            createAModule('',2,false,0,0,0,5, Template, false, 0)	;

        }else{

            createAModule('',1,false,0,0,0,5, Template, false, 0)	;

        }

            conteudoBox = document.getElementById('dragableBoxContent' + TotalModulos).innerHTML;

            conteudoBox = conteudoBox.replace(/\/master/g, '/' + CssName);



            document.getElementById('dragableBoxContent' + TotalModulos).innerHTML = conteudoBox;
            
            temMudanca=1;


        }

        

function adicionaModuloEspecial(Template, Tipo){

	if (numeroColunas>1){

            createAModule('',2,false,0,0,0,5, Template,false,Tipo);

        }else{

            createAModule('',1,false,0,0,0,5, Template,false,Tipo);

        }

            if (Tipo==1) {

            	document.getElementById('dragableBoxContent' + TotalModulos).innerHTML = '<img src="http://image.ig.com.br/hpg/images/' + tipo_contador + '.png">';
            	
            }
	
	temMudanca=1;
	
        }

        

function adicionaInclude(url, especial, tipo){
	var altura;
	if (especial==5){
		altura=200;
	}else{
		altura=150;
	}

	adicionaModuloEspecial('<iframe width="100%" id="' + tipo + '" name="' + tipo + '" height="' + altura + '" src="' + url + '?css=' + CssName + '_edicao" scrolling="no" border="0" allowtransparency="true"></iframe>', especial);

}



function mudaCSSBligFotolog(css){

	if (ModulosEspeciais[4]==1) {

		document.getElementById("blig").src = siteusuario + '/ultimablig.html?css=' + css + '_edicao';

	}

	if (ModulosEspeciais[5]==1) {

		document.getElementById("fotolog").src = siteusuario  + '/ultimafotolog.html?css=' + css + '_edicao';

	}

	

}



function editOrVisualize(){

 if(stateOfBody=="visualize"){

    mudarPerspectiva('E');

    stateOfBody="edit";

    document.getElementById("visualizar").innerHTML = 'Visualizar'

    document.getElementById("li_visualizar").className = 'visualizar';

 }else{

    mudarPerspectiva('V');

    stateOfBody="visualize";

    FecharEdicao();

    document.getElementById("visualizar").innerHTML = 'Voltar a Edição';

    document.getElementById("li_visualizar").className = 'view_all';

 }

}





function FecharEdicao(){

	//FAZER FOR PARA VERIFICAÇÃO DE EDIÇÃO.

    if (ElementosPosicao!=0){

    xElementos = ElementosPosicao;

    for (i=0;i<xElementos;i++){

    	  	salvaAlteracaoElement(ElementosEdicao[i]);

    	}

    }

    if (BoxesPosicao!=0){

    xBoxes = BoxesPosicao;

    		for (j=0;j<xBoxes;j++){

		   	salvaAlteracao(BoxesEdicao[j]);

    	}

    }

    for (i=1;i<TotalModulos+1;i++){

	    	  	salvaBox(i);

    	}

}



function mudarPerspectiva(indice){

    if(indice=='V'){

        esconderBoxHeader();

    }else{

        mostrarBoxHeader();

    }



}





function validaNome(nomePagina){

	var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

	var checkStr = nomePagina;

	var validado = true;

		for (i = 0;  i < checkStr.length;  i++){

			ch = checkStr.charAt(i);

			for (j = 0;  j < checkOK.length;  j++)

			if (ch == checkOK.charAt(j))

			break;

			if (j == checkOK.length){

				validado = false;

				break;

			}

		}

	if (!validado){

		alert("Espaço, acentuação e caracteres especiais não podem ser usados. Utilize apenas letras e números para nomear sua página.");

		frm_nome.f.focus();

		return (false);

	}else{
		abreSubmitPopup('','formpopup');

		ExibeConteudoDiv('floatingBoxParentContainer', nomePagina + '.html');

		return (true);

	}

}

function validaNomeAjax(nomePagina){
	var er = RegExp(/\W/);
       if(nomePagina == ''){
          return false;
       }else if(er.test(nomePagina) == false){
          return true;
       }else if(er.test(nomePagina) == true){
          return false;
       }

}



function NomeiaArquivo(parentDiv){



		var maindiv = document.createElement('DIV');

		maindiv.id = "salva";

	if (NomeArquivo==''){

	    	maindiv.style.width = "300px"

	    	maindiv.style.height = "100";

	    	maindiv.style.border= "solid 1px #CFE2F1";

	    	maindiv.style.background= "#ffffff";

	    	maindiv.style.top= "250px";

	    	maindiv.style.left= "300px";

	    	maindiv.style.position= "absolute";

	    	maindiv.style.display= "block";

		salvaHtml = '<a style="color:#3182C2; href="#" onclick="FechaPopupDiv(';

		salvaHtml += "'salva');";

		salvaHtml += '"><b>[X]Fechar</b></a>';

		salvaHtml += '<form name="frm_nome" method="post" onsubmit="return validaNome(document.frm_nome.f.value);" />';

		salvaHtml += '<p style="color:#3182C2;">Dê um nome para a sua nova página:<br/>';

		salvaHtml += '<input type="text" name="f" value="" maxlength="20" />.html&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>';

		salvaHtml += '<input type="button" name="btn_nomear" value="OK" onclick="validaNome(document.frm_nome.f.value);"></form>';

		maindiv.innerHTML = salvaHtml;

		divBody = document.body;

		divBody.appendChild(maindiv);

		document.frm_nome.f.focus();

	}else{

		divBody = document.body;

		divBody.appendChild(maindiv);
		
		abreSubmitPopup('','formpopup');

		ExibeConteudoDiv('floatingBoxParentContainer', NomeArquivo);

		

	}

}



function ExibeConteudoDiv(parentDiv, nomeArq){



	

		if (nomeArq=='.html'){

			alert('Por favor dê um nome para o seu arquivo');

		}else{

		NomeArquivo = nomeArq ;

		FecharEdicao();

		esconderBoxHeader();



		pagetitle = document.getElementById("titulo").value;



		var HtmlInicio = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><meta http-equiv=content-type content=text/html;charset=iso-8859-1><title>' + document.getElementById("titulo").value + '</title>';

			HtmlInicio += '<meta name="description" content="' + pagedescription + '"><meta name="keywords" content="' + pagekeywords + '"><link rel=stylesheet href=css/' + CssName + '.css></head><body>';

			var HtmlFim = "</body></html>";

		    var pDiv = document.getElementById(parentDiv);

		    var xHtml = HtmlInicio + pDiv.innerHTML + HtmlFim;



		    var CodigoHtml = CriarHTML();

			CodigoHtml = CodigoHtml.replace(/\"/g, "##");



		    var postdiv = document.getElementById('salva');
			

			salvaHtml = '<form id="frm" name="frm" action="/cgi-bin/gerenciador.cgi" method="post" target="formpopup">';

			salvaHtml += '<input type="hidden" name="op" value="ftp_online">';

			salvaHtml += '<input type="hidden" name="origem" value="' + Origem + '">';

			salvaHtml += '<input type="hidden" name="area" value="grava_html_editor">';

			salvaHtml += '<input type="hidden" name="f" value="' + NomeArquivo + '">';

			salvaHtml += '<input type="hidden" name="dir_atual" value="' + DiretorioArquivo + '">';

			salvaHtml += '<input type="hidden" name="html" value="' + CodigoHtml + '"></form>';



			postdiv.innerHTML = salvaHtml;



			
			
			document.getElementById('frm').submit();

			FechaPopupDiv('salva');







		mostrarBoxHeader();



		}

	

}


function abreSubmitPopup(theURL,winName) { 
	var winWidth = 270;
	var winHeight = 128;
	var winTop = parseInt((screen.availHeight - winHeight) / 2);
	var winLeft = parseInt((screen.availWidth - winWidth) / 2);
  	window.open(theURL,winName,'width=' + winWidth + ', height=' + winHeight + ', top=' + winTop + ', left=' + winLeft);
}


function Left(str, n){

	if (n <= 0)

	    return "";

	else if (n > String(str).length)

	    return str;

	else

	    return String(str).substring(0,n);

}

function Right(str, n){

    if (n <= 0)

       return "";

    else if (n > String(str).length)

       return str;

    else {

       var iLen = String(str).length;

       return String(str).substring(iLen, iLen - n);

    }

}

function closeWindow(){
	window.close();
}


// Início - Melhorias 1ª fase 

//ADICIONA O MÓDULO ESPECIAL NA LISTAGEM DE MÓDULOS ATIVOS
function adicionandoModuloEspecial(codigo){
	var MEObj = ModulosEspeciais;
	MEObj[codigo]=1;
}

//VERIFICA A EXISTÊNCIA DO MÓDULO ESPECIAL REPRESENTADO PELO CODIGO
function verificaModuloEspecial(codigo){
	var MEObj = ModulosEspeciais;
	if (MEObj[codigo]==0){
		return true;
	}else{
	
	var winTop = parseInt((screen.availHeight - 180) / 2);
	var winLeft = parseInt((screen.availWidth - 100) / 2);
	
		var msgErro = '<table style="color:#3182C2;"><tr><td width="65%">&nbsp;</td><td align="right" width="35%" valign="top"><a style="color:#3182C2;" href="javascript:FechaPopupDiv(';
		msgErro += "'seleciona');";
		msgErro += '"><b>[X]Fechar</b></a></td></tr>';
		msgErro += '<tr><td colspan="2" align="center"><p>&nbsp;</p>Sua página já possui<br>este tipo de módulo!</td></tr></table>';
							
		var oDiv = document.getElementById('seleciona');
		if (!oDiv){
			var maindiv = document.createElement('DIV');
			maindiv.style.width = "180px";
			maindiv.style.height = "100px";
			maindiv.style.border= "solid 1px #CFE2F1";
			maindiv.style.background= "#ffffff";
			maindiv.style.top= winTop + "px";
			maindiv.style.left= winLeft + "px";
			maindiv.style.position= "absolute";
			maindiv.id = "seleciona";
			maindiv.innerHTML = msgErro;
			divModulos = document.getElementById('mainContainer');
			divModulos.appendChild(maindiv);
		}else{
			oDiv.style.width = "180px";
			oDiv.style.height = "100px";
			oDiv.style.top= winTop + "px";
			oDiv.style.left= winLeft + "px";
			oDiv.innerHTML = msgErro;
			oDiv.style.display = "inline";
			return false;
		}
	}
}

//CRIA JANELA DE PREENCHIMENTO DO BLIG
function selecionaBlig(){
	//MÓDULO ESPECIAL 4 - BLIG
	var isOk = verificaModuloEspecial(4);
	if (isOk){
		var selecaoBlig = '<form name="form_blig" method=post action="/cgi-bin/blig.cgi" target="_blank"><table style="color:#3182C2;"><tr><td width="70%"><img src="http://images.ig.com.br/feed_rss/blig_logo.gif"></td><td align="right" width="30%" valign="top"><a style="color:#3182C2;" href="javascript:FechaPopupDiv(';
		selecaoBlig += "'seleciona');";
		selecaoBlig += '"><b>[X]Fechar</b></a></td></tr>';
		selecaoBlig += '<tr><td colspan="2" align="center">Digite o nome do seu Blig<br>para inseri-lo em seu site</td>';
		selecaoBlig += '<tr><td width="70%" align="right"><input type="textbox" name="txtBlig" maxlength="160"></td>';
		selecaoBlig += '<td width="30%" align="left">.blig.ig.com.br</td></tr>';
		selecaoBlig += '<input type="hidden" name="txtCss" value="' + CssEdicao + '">';
		selecaoBlig += '<tr><td colspan="2" align="center" nowrap><input type="submit" name="ok" value="Ok" style="width:100px;"></td></tr>';
		selecaoBlig += '<tr><td colspan="2" align="center">&nbsp;<br><a style="color:#3182C2;" href="http://blig.ig.com.br/cadastro_usuario.php" target="_blank">Você ainda não tem o seu Blig?<br>Clique aqui para fazer o seu.</a></td></tr></table></form>';
			
		var oDiv = document.getElementById('seleciona');
		if (!oDiv){
			var maindiv = document.createElement('DIV');
			maindiv.style.width = "300px"
			maindiv.style.height = "200px";
			maindiv.style.border= "solid 1px #CFE2F1";
			maindiv.style.background= "#ffffff";
			maindiv.style.top= "200px";
			maindiv.style.left= "35px";
			maindiv.style.position= "absolute";
			maindiv.id = "seleciona";
			maindiv.innerHTML = selecaoBlig;
			divModulos = document.getElementById('mainContainer');
			divModulos.appendChild(maindiv);
		}else{
			oDiv.style.width = "300px";
			oDiv.style.height = "200px";
			oDiv.style.top= "200px";
			oDiv.style.left= "35px";
			oDiv.innerHTML = selecaoBlig;
			oDiv.style.display = "inline";
		}			
	}
}

//ADICIONA MÓDULO BLIG
function adicionaBlig(url, css){
	var isOk = verificaModuloEspecial(4);
	if (isOk){
		
		adicionaInclude(url,4, 'blig');
		adicionandoModuloEspecial(4);
		
	}
}

//FECHA JANELAS DOS MÓDULOS ESPECIAIS
function FechaPopupDiv(popupdiv){
	var oDiv = document.getElementById(popupdiv);
	oDiv.style.display = "none";
}

//VERIFICA SE A PÁGINA JÁ FOI SALVA E EXIBE O STATUS DE EDIÇÃO
function statusEdicao(){
	if (NomeArquivo==''){
		document.getElementById("statusEdicao").innerHTML = 'Você ainda não salvou esta página';
		idStatusEdicao=0;
	}else{
		document.getElementById("statusEdicao").innerHTML = 'Você está editando a página: <a target="blank" href="' + siteusuario + '/' + NomeArquivo + '" style="color:#FF9C00;font-weight:bold;">' + NomeArquivo + '</a>';
		idStatusEdicao=1;
		temMudanca=0;
	}
}

//TRAZ A ORIGEM DO ARQUIVO (SE ASSISTENTE OU GERENCIADOR)
function checaOrigem(){
	return Origem;
}

//VERIFICA SE JÁ EXISTE MÓDULO CLICKLIG
function verificaClickLig(){
	if(verificaModuloEspecial(6)){
		openWindow('/popups/adicionar_clicklig.html', 'popup');
	}
}

//VERIFICA SE JÁ EXISTE MÓDULO BLIG
function verificaBlig(){
	if(verificaModuloEspecial(4)){
		openModule('/popups/adicionar_blig.html', 'popup', 300, 220);
	}
}

//Correções
function popAlteraModelo(){
	FecharEdicao();
	openWindow('/popups/alterar_modelo.html', 'popup');
}

function popAlteraEstrutura(){
	FecharEdicao();
	openWindow('/popups/alterar_estrutura.html', 'popup');
}

var xmlhttp = getXmlHttpRequest();

	function getXmlHttpRequest(){
		if(window.XMLHttpRequest){
			return new XMLHttpRequest();
		}else if(window.ActiveXObject){
			return new ActiveXObject("Microsoft.XMLHTTP")
		}
	}



	function salvaPaginaAjax(div){
		
		//para criar o html da página corretamente
		var HtmlInicio = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><meta http-equiv=content-type content=text/html charset=iso-8859-1><title>' + document.getElementById("titulo").value + '</title>';
		HtmlInicio += '<meta name="description" content="' + pagedescription + '"><meta name="keywords" content="' + pagekeywords + '"><link rel=stylesheet href=css/' + CssName + '.css></head><body>';
		var HtmlFim = "</body></html>";
		var pDiv = document.getElementById(div);
	    	var xHtml = HtmlInicio + pDiv.innerHTML + HtmlFim;
		var CodigoHtml = CriarHTML();
		CodigoHtml = CodigoHtml.replace(/;/g, "|%|%");
		CodigoHtml = CodigoHtml.replace(/&/g, "|@|@");
		    
		parametros = "op=ftp_online&origem=" + Origem + "&area=grava_html_editor&dir_atual=" + DiretorioArquivo + "&html=" + CodigoHtml + "&f=" +NomeArquivo
		
		xmlhttp.open("post", "/cgi-bin/gerenciador.cgi", false);
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
		xmlhttp.setRequestHeader("Content-length", parametros.length);
		xmlhttp.onreadystatechange = function() {
			
			if (xmlhttp.readyState==4){
				if (xmlhttp.status=='200'){
					
				}
			}
		}
		xmlhttp.send(parametros);

		
	}

function fechaOuContinua(){
	if (idStatusEdicao==0||temMudanca==1){
		var mantem = window.confirm('Deseja salvar as alterações em sua página?');
		if (mantem){
			if (NomeArquivo==''){
				var versao = navigator.userAgent;
				versao = versao.split(";");
				versao = versao[1];
				if (versao!=' MSIE 7.0'){
					while(!validaNomeAjax(NomeArquivo)){
						if (NomeArquivo!='') alert("Espaço, acentuação e caracteres especiais não podem ser usados. Utilize apenas letras e números para nomear sua página.");
						NomeArquivo = prompt("Escolha um nome para a sua página","");
					}
					NomeArquivo += ".html";
				}else{
					NomeArquivo = 'semnome.html'
				}
			}
			salvaPaginaAjax('floatingBoxParentContainer');
			statusEdicao();
			if (versao==' MSIE 7.0') {
				alert('Página salva como semnome.html.\nPara renomeá-la, use o Gerenciador Avançado.');
			}else{
				alert('Página ' + NomeArquivo + ' salva com sucesso');
			}
		}
	}	
	window.opener.location.reload(true);
}
