/* Objeto para controlar a galeria multimia
 * Valdir S. Botingnon
 * 26/03/2009
 */
// LAYOUT DA FORMA DE ARMAZENAMENTO DA GALERIA:
/*
json: [{"tipo":"?","src":"Caminho","legenda":"Legenda"}]
array(
	0 => array(
		"tipo"	=> "?",[imagem|video|audio]
		"src"	=> "Caminho",
		"legenda" => "Legenda",
	)
));
*/
var galMultimida = function (){
	var self		= this;
	
	self.galeria	= [];
	self.galAtual	= 0;
	self.galDiv		= 'galeria_foto_';
	self.galUrlLis	= '../../tools_shared/formcreator/tipocampo/galeria_multimidia/lisImagem.php';
	self.galUrlMan	= '../../tools_shared/formcreator/tipocampo/galeria_multimidia/manImagem.php';
	http_request	= false;
	
	self.setGaleria = function (config){
		var indice				= self.getQtdeGal();
		self.galAtual			= indice;
		
		self.galeria[indice]	= new Array(3);
		self.galeria[indice][0]	= config.editar;
		self.galeria[indice][1]	= config.campo;
		self.galeria[indice][2]	= config.tabela;
	}
	
	self.listarGaleria = function (campo){
		self.selIndice(campo);
		if (self.galeria[self.galAtual][0]){
			self.makeRequest(self.galUrlLis);
		}else{
			var html = "<br /><strong>Aten&ccedil;&atilde;o!</strong>";
			html += "<br /><br />";
			html += "Para inserir fotos em uma galeria, voc&ecirc; deve estar <strong>EDITANDO</strong> um cadastro.";
			html += "<br />";
			html += "No momento, voc&ecirc; est&aacute; inserindo um novo cadastro. ";
			html += "Para criar uma galeria para este registro, ";
			html += "preencha os campos, clique no bot&atilde;o <strong>GRAVAR</strong>, em seguida clique em <strong>VOLTAR</strong> ";
			html += "e selecione o registro que acabou de inserir na lista.<br />";
			
			var div = self.galDiv + self.galeria[self.galAtual][1];
			document.getElementById(div).innerHTML = html;
		}		
	}
	/*
	self.ocultarGaleria = function (campo){
		self.selIndice(campo);
		document.getElementById('bodyGaleria_'+campo).style.display = 'none';
	}
	*/
	
	self.delFoto = function (indice, campo){
		if (confirm("Confirma a exclusão do item da galeria?")){
			self.selIndice(campo);
			self.makeRequest(self.galUrlMan, "acao=delFoto&indice="+indice);
		}
	}
	
	self.alternaLegenda = function (f, i, campo, v, va){
		self.selIndice(campo);
		if (f=="C")  {
			edit 	= document.getElementById('alteralegenda_' + campo + i);
			static	= document.getElementById('legenda_' + campo + i);
			edit.style.display="block";
			static.style.display="none";
			campo	= document.getElementById('leg_' + campo + i);
			campo.focus();
		} else  {
			edit 	= document.getElementById('alteralegenda_' + campo + i);
			static	= document.getElementById('legenda_' + campo + i);
			edit.style.display="none";
			static.style.display="block";
			if (v!=va) {
				self.makeRequest(self.galUrlMan, "acao=editLegenda&txtlegenda="+va+"&indice="+i);
			}
		}
	}
	
	self.alternaOrdem = function (f, i, campo, v, va){
		self.selIndice(campo);
		if (f=="C")  {
			edit 	= document.getElementById('alteraordem_' + campo + i);
			static	= document.getElementById('ordem_' + campo + i);
			edit.style.display="block";
			static.style.display="none";
			campo	= document.getElementById('ord_' + campo + i);
			campo.focus();
		} else  {
			edit 	= document.getElementById('alteraordem_' + campo + i);
			static	= document.getElementById('ordem_' + campo + i);
			edit.style.display="none";
			static.style.display="block";
			if (v!=va) {
				self.makeRequest(self.galUrlMan, "acao=editOrdem&txtordem="+va+"&indice="+i);
			}
		}
	}
	
	self.cadValidaImagem = function(form){
		var video	= form.video.value; 
		var arq		= form.imagem_g.value;
		
		if (arq == ''){
			if (video == ''){
				alert('Informe um vídeo ou arquivo!');
				form.imagem_g.focus();
				return false;
			}
		}else{
			var ext = arq.toLowerCase();
			if (ext.indexOf('jpg') != -1 || ext.indexOf('mp3') != -1){
				return true;
			}else{
				alert('Arquivo inválido, aceito apenas JPG/MP3');
				form.imagem_g.focus();
				return false;
			}
		}
		false;	
	}
	
	self.selIndice = function (campo){
		for (indice = 0; indice < self.getQtdeGal(); indice++){
				if (campo == self.galeria[indice][1]){
				self.galAtual = indice;
				break;
			}
		}
		return;
	}
	
	self.makeRequest = function (destino, parametros) {
		var div		= self.galDiv + self.galeria[self.galAtual][1];
		var galeria = self.galeria[self.galAtual];
		var URLdest	= destino;
		
		if (typeof parametros == 'undefined') parametros = '';
		
		URLdest		+= '?codigo='	+ galeria[0];
		URLdest		+= '&campo='	+ galeria[1];
		URLdest		+= '&tabela='	+ galeria[2];
		URLdest		+= '&r='		+ Math.floor(Math.random() * 99999999999);
		URLdest		+= '&'			+ parametros;
		
		if (typeof document.getElementById(div) != 'object'){
			alert('Elemento ' + div + ' n&atilde;o localizado na p&aacute;gina.');
			return false;
		}
		
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
			http_request = new XMLHttpRequest();
			if (http_request.overrideMimeType) {
				http_request.overrideMimeType('text/xml');
			}
		} else if (window.ActiveXObject) { // IE
			try {
				http_request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					http_request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}	
	
		if (!http_request) {
			document.getElementById(div).innerHTML = 'N&atilde;o pode criar uma inst&acirc;ncia do XMLHTTP.';
			return false;
		}
		
		document.getElementById(div).innerHTML = '';
		document.getElementById(div).innerHTML = 'Aguarde. Carregando...';

		http_request.open('GET', URLdest, true);
		http_request.onreadystatechange = self.MakeRes;
		http_request.send(null);
	}
	
	this.MakeRes = function (){
		var div		= self.galDiv + self.galeria[self.galAtual][1];

		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				var resposta = http_request.responseText;
				document.getElementById(div).innerHTML = resposta;
				self.extraiScript(resposta);
				/*
				var janela = parent.document.getElementById('telaclass');
				var atual = parseInt(janela.style.height.replace("px", ""));
				var total = atual + parseInt(document.getElementById(div).clientHeight);
				janela.style.height = total + "px";
				*/
			} else {
				document.getElementById(div).innerHTML = '[' + http_request.status + '] Houve algum problema com a solicita&ccedil;&atilde;o.';
			}
		}
	};

	self.extraiScript = function (texto){
		var ini, pos_src, fim, codigo;
		var objScript = null;
		var tagIni = "<";
		var tagFim = "/script>";
		var tag = tagIni + tagFim;

		ini = texto.indexOf('<script', 0)
		while (ini!=-1){
			var objScript = document.createElement('script');
			pos_src = texto.indexOf(' src', ini);
			ini = texto.indexOf('>', ini) + 1;
	

			if (pos_src < ini && pos_src >=0){
				ini = pos_src + 4;
				fim = texto.indexOf('.', ini)+4;
				codigo = texto.substring(ini,fim);
				codigo = codigo.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\'","").replace("\'","").replace(">","");
				objScript.src = codigo;
			}else{
				fim = texto.indexOf(tag, ini);
				codigo = texto.substring(ini,fim);
				objScript.text = codigo;
			}
	
			document.body.appendChild(objScript);
			ini = texto.indexOf('<script', fim);
			objScript = null;
		}
	}

	self.setNovoRegistro = function (){
		self.galeria	= [];
		self.galAtual	= 0;
	}
	
	self.getQtdeGal = function(){
		return self.galeria.length;
	}
	
	return self;
}
