// JavaScript Document

if(typeof(BlockAPI) == 'undefined'){
	//var BlockAPI = (BlockAPI != null)?BlockAPI:{};
	function BlockAPIClass(){
		
		this.replaceAll = function(str, r, w){
			if(str)
				return str.replace('/'+r+'/g', w);
			else
				return str;
		};
		
		this.containerInstances = new Array();

		this.addContainer = function(id, cont){
			this.containerInstances[id] = cont;
		};
		
		this.getContainer = function(contId){
			if(this.containerInstances[contId])
				return this.containerInstances[contId];
			else
				return null;
		};
		
		this.getContainerByKey = function(key){
			var res = new Array();
			for(var c in this.containerInstances)
				if(this.containerInstances[c].block.getKey() == key)
					res.push(this.containerInstances[c]);
			return res;
		};
		
		this.callbacks = new Array();
		this.loaded = false;
		this.loading_jquery = false;
		this.loading_boxy = false;
		this.host = '';
		
		this.isLoaded = function(){
			return this.loaded;
		};
		
		this.init = function(callback){
			
			if(callback)
				this.callbacks.push(callback);

			if(!this.loaded){
				
				if(document.getElementById('css_embed') == null){
					document.write('<link id="css_embed" href="http://smallpages.com.ar/css/embed2.css" rel="stylesheet" type="text/css" />');
				}
				var self = this;
				if(typeof(jQuery) == 'undefined' && !this.loading_jquery){
					this.loading_jquery = true;
					this.loadScript('http://smallpages.com.ar/js/jquery.js', function(){ 
						this.loading_jquery = false;
						self.init(null);
					});
					return;
				}
				/*else if(typeof(Boxy) == 'undefined' && !this.loading_boxy){
					this.loading_boxy = true;
					this.loadScript('js/boxy/javascripts/jquery.boxy.js', function(){ 
						this.loading_boxy = false;
						self.init(null);
					});
					return;
				}*/
			}
			
			if(!this.loaded && /*typeof(Boxy) != 'undefined' &&*/ typeof(jQuery) != 'undefined'){
				this.loaded = true;
				for(var n = 0; n < this.callbacks.length; n++)
					this.callbacks[n]();
				this.callbacks = new Array();
			}
		};
		
		this.loadScript = function(url, callback){
			var script = document.createElement("script");
			script.type = "text/javascript";
			if (script.readyState){  //IE
				  script.onreadystatechange = function(){
					if(script.readyState == "loaded" || script.readyState == "complete"){
						script.onreadystatechange = null;
						callback();
					}
				};
			} else {  //Others
				script.onload = function(){
					callback();
				};
			}
			script.src = url;
			document.getElementsByTagName('head')[0].appendChild(script);
		};
	}	
}

var BlockAPI = (BlockAPI != null)?BlockAPI:new BlockAPIClass();

if(typeof(Block) == 'undefined'){
	
	//Clase que representa a un bloque, a traves de esta clase se puede obtener el contenido del bloque
	/*
		Tiene los siguientes métodos públicos:
			- bind(event, function) : Adjunta una función a un evento. La función es llamada cada vez que ocurre el evento
			- refresh() : Actualiza el contenido del bloque. Cuando se termina de cargar se ejecuta el evento "load"
			- login(username, password, remember_me) : Intenta loguear al usuario. Cuando se termina de loguear se ejecuta el evento "login"
			- last() : Carga la ultima versión del bloque. Se ejecuta el evento "load" al terminar de cargar.
			- prev() : Carga la versión previa del bloque. Se ejecuta el evento "load" al terminar de cargar.
			- next() : Carga la versión posterior del bloque. Se ejecuta el evento "load" al terminar de cargar.
	*/
	function Block(key, version, options, host){

		//Configuracion para obtener los datos del bloque
		this.host = host;
		this.key = key;
		this.version = version;
		this.original_css = 0;
		
		//Propiedades del bloque
		this.content = ''; //Contenido del bloque
		this.date = ''; //Fecha de creacion del bloque completa
		this.dateDistance = '';//Fecha de creacion del bloque relativa
		this.blockOptions = {}; //Opciones del bloque
		this.owner_id = '';
		this.max_version = 1;
		
		//Opciones establecidas para esta instancia
		this.options = (options==null)?{}:options;
		
		//Opciones finales
		this.realOptions = {};
		
		//Propiedades del usuario
		this.logged_in = false;
		this.is_admin = false;
		this.id_usuario = 0;
		
		//Variables internas de la clase
		this.ajaxCall = null; //Variable de la llamada ajax
		this.refreshInterval = false;
		this.logging_in = false;
		
		//Estado interno
		this.errors = new Array();
		this.errors[0] = 'ajaxError';
		this.errors[1] = 'inexistentBlock';
		this.errors[2] = 'inexistentVersion';
		
		//Estados posibles del bloque
		this.statuses = new Array();
		this.statuses[0] = 'initializing', //Inicializando la clase
		this.statuses[1] = 'ready'; //Clase lista para cargar una página
		this.statuses[2] = 'loading'; //Ejecutando el llamado ajax para cargar una página
		this.statuses[3] = 'unknown'; //Estado desconocido
	
		this.status = this.statuses[0];

		
		//Manejo de propiedades de la conexion
		this.getHost = function(){ return this.host; };
		this.setHost = function(host){ this.host = host; };
		
		//Manejo de propiedades del bloque
		this.getKey = function(){ return this.key; };
		this.getVersion = function(){ return this.version; };
		this.getMaxVersion = function(){ return this.max_version; };
		this.setContent = function(c){ this.content = c; };
		this.getContent = function(){ return this.content; };
		this.getOptions = function(){ return this.realOptions; };
		this.setOption = function(n, v){ if(this.options) this.options[n] = v; };
		this.getDate = function(){ return this.date; };
		this.getDateDistance = function(){ return this.dateDistance; };
		this.userId = function(){ return this.id_usuario; };
		this.getOriginalCss = function(){ return this.original_css; };
		this.setOriginalCss = function(v){ this.original_css = parseInt(v); };
		
		
		//Manejo de propiedades del usuario
		this.loggedIn = function(){ return this.logged_in; };
		this.isOwner = function(){ return this.isAdmin() || this.userId() != '' && this.userId() == this.owner_id; };
		this.isAdmin = function(){ return this.is_admin; };
		
		//Manejo de eventos
		this.bindings = new Array(); //Lista de eventos
		this.bind = function(evt, fn){ 
			if(evt != ''){
				if(!this.bindings[evt])
					this.bindings[evt] = new Array();
				this.bindings[evt].push(fn);
			}
		};
		//Dispara el evento a todos los que lo estan recibiendo, siempre se pasa como parametro el objeto Block
		this.fireEvent = function(evt, param){
			if(evt != '' && this.bindings[evt]){
				for(var n = 0; n < this.bindings[evt].length; n++)
					this.bindings[evt][n](this, param);
			}
		};
		
		//Manejo del estado del bloque
		this.getStatus = function(){
			return this.status;
		};
		
		this.setStatus = function(n){
			n = parseInt(n);
			if(n >= this.statuses.length)
				n = this.statuses.length-1;
			if(this.statuses[n] != this.status){
				this.status = this.statuses[n];
				this.fireEvent('status_change', this.status);
			}
		};
		
		//Carga el contenido del bloque en la clase
		this.load = function(key, version, options, host){
			this.stopRefresh();
			this.key = key;
			this.version = version;
			if(options)
				for(var opt in options)
					this.setOption(opt, options[opt]);
			if(host != null)
				this.host = host;
			this.refresh();
		};
		
		this.stopRefresh = function(){
			if(this.ajaxCall)
				this.ajaxCall.abort();
		};
		
		this.refresh = function(){
			this.setStatus(2);
			var self = this;
			
			this.stopRefresh();
			this.ajaxCall = $.getJSON(this.getHost()+"Host/getJSON?k="+this.key+"&v="+this.version+"&r="+Math.random()+"&original_css="+this.getOriginalCss()+"&callback=?", null, function(data){
				self.refreshCallback(data);
			});
		};

		this.refreshCallback = function(data){
			
			if(this.getKey() != data['block']['id'] || this.getVersion() != parseInt(data['version'])) //No es el bloque esperado
				return;

			var c = data['block_content']['Contenido'];
			c = BlockAPI.replaceAll(c, '&lt;', '<');
			c = BlockAPI.replaceAll(c, '&gt;', '>');

			this.date = data['block']['Fecha_creacion'];
			this.dateDistance = data['actualizado'];
			this.version = parseInt(data['version']);
			this.max_version = parseInt(data['max_version']);
			this.owner_id = data['block']['Usuario'];
			this.setContent(c);
			this.blockOptions = data['block']['Opciones'];
			var oldInterval = parseInt(this.getOptions()['AutoRefresh']);
			
			this.realOptions = this.options;

			for(var opt in this.blockOptions){
				if(typeof(this.realOptions[opt]) == 'undefined'){
					this.realOptions[opt] = this.blockOptions[opt];
				}
			}

			if(!this.logging_in){
				this.id_usuario = data['id_usuario'];
				this.logged_in = data['logged_in'];
				this.is_admin = data['is_admin'];
			}

			
			var self = this;
			if(this.getOptions()['AutoRefresh'])
				var ar = parseInt(this.getOptions()['AutoRefresh']);
			else
				var ar = 0;
			if(ar >= 15 && ar != oldInterval){
				if(this.refreshInterval)
					clearInterval(this.refreshInterval);
				this.refreshInterval = setInterval(function(){ self.refresh(); }, ar*1000);
			}
			this.setStatus(1);
			this.fireEvent('load', c);
		};
		
		//Carga la ultima version del bloque
		this.last = function(){
			this.load(this.getKey(), 1);
		};
		
		//Carga la version anterior a la actual
		this.prev = function(){
			if(this.getVersion() == this.getMaxVersion()){
				return false;
			}else{
				this.load(this.getKey(), this.getVersion()+1);
				return true;
			}
		};
		
		//Carga la version posterior a la actual
		this.next = function(){
			if(this.getVersion() == 1){
				return false;
			}else{
				this.load(this.getKey(), this.getVersion()-1);
				return true;
			}
		};
		
		this.login = function(username, password, remember_me){
			this.logging_in = true;
			var self = this;
			$.getJSON(this.getHost()+"Host/getJSON?action=login&username="+username+"&password="+password+"&remember_me="+remember_me+"&r="+Math.random()+"&callback=?", null,
				function(data){
					self.loginCallback(data);
				});	
		};
		
		this.loginCallback = function(data){
			this.logged_in = data['logged_in'];
			this.id_usuario = data['id_usuario'];
			this.is_admin = data['is_admin'];
			this.logging_in = false;
			this.fireEvent('login', data['resultado']);
		};
		
		this.init = function(){
			this.setStatus(1);
		};

		this.init();
	}
	
	function BlockContainer(key, version, host, contId, options, readyCallback){
		this.block = null;
		this.contId = contId;
		this.onReady = readyCallback;
		this.popup = null;
		this.disable_status = false;
		
		this.key = key;
		this.version = version;
		this.host = host;
		this.options = (options==null)?{}:options;

		this.defaultOptions = {'OcultarInfo':0,
							   'OcultarMasOpciones':0,
							   'Bordes':1,
							   'OcultarHistorial':0,
							   'OcultarActualizar':0};
		this.loadBlock = function(key, version, options, host){
			BlockAPI.host = host;
			var self = this;

			this.block = new Block(key, version, options, host);
			//El bloque esta listo, le hago el bind del cambio de status y de bloque cargado

			this.block.bind('status_change', function(block, txt){
				self.changeStatus(txt);
			});

			this.block.bind('load', function(block, content){
				self.updateContent(content);
			});

			this.block.bind('login', function(block, result){
				self.loginCallback(result);
			});
				
			this.block.refresh();
		};
		
		this.updateContent = function(c){

			var cont_sel = '#'+this.contId;
			var self = this;
			
			this.setupContainer();
			
			$(cont_sel).html(c);
			
			/*$(cont_sel+' .block-white-layer').css('width', $(cont_sel).width()+'px');
			$(cont_sel+' .block-white-layer').css('height', $(cont_sel).height()+'px');
			
			if($(cont_sel+' .block-white-layer').is(':hidden'))
				$(cont_sel+' .block-white-layer').show();
			$(cont_sel+' .block-white-layer').fadeIn('fast', function(){*/
				/*$(cont_sel+' .block-white-layer').fadeOut('fast', function(){ $(cont_sel+' .block-white-layer').hide(); });
			});*/
			
			if(this.block.getVersion() == 1)
				this.setStatus('Hace '+this.block.getDateDistance()+' - Última versión');
			else
				this.setStatus('Hace '+this.block.getDateDistance()+' - Versión '+this.block.getVersion()+'/'+this.block.getMaxVersion());
			this.updateLinks();
			
			if($(cont_sel).is(':hidden'))
				$(cont_sel).show();
			
		};
		
		this.changeStatus = function(txt){
			switch(txt){
				case 'initializing':
					if(this.block)
						this.setStatus('<img src="'+this.block.getHost()+'img/indicator.gif" align="absmiddle" />');
					else
						this.setStatus('Cargando..');
				break;
				case 'ready':
					this.setStatus('');
				break;
				case 'loading':
					if(this.block)
						this.setStatus('<img src="'+this.block.getHost()+'img/indicator.gif" align="absmiddle" /> Cargando..');
					else
						this.setStatus('Cargando..');
				break;
				case 'unknown':
					//this.setStatus('');
				break;
			}
		};
		
		this.setStatus = function(txt){
			if(this.disable_status)
				return;
			var menu_sel = '#'+this.contId+'-menu';
			/*if($(menu_sel+' .block-status').is(':hidden'))
				$(menu_sel+' .block-status').fadeIn('fast');
			$(menu_sel+' .block-status').html(txt);
			this.hideStatus();*/
			$(menu_sel+' .block-refresh').attr('title', txt);
		};
		
		this.hideStatus = function(){
			setTimeout(function(){ $('#'+this.contId+'-menu .block-status').fadeOut('fast'); }, 3000);
		};
	
		this.last = function(){
			if(this.block)
				this.block.last();
		};
		
		this.prev = function(){
			if(this.block)
				this.block.prev();
		};
		
		this.next = function(){
			if(this.block)
				this.block.next();
		};
		
		this.refresh = function(){
			if(this.block)
				this.block.refresh();
		};
		
		this.edit = function(){
			if(this.block){
				window.open(this.block.getHost()+'Block/edit?id='+this.block.getKey(), '', 'status=no,scrollbars=no,width=650,height=500');
				
				/*if(!this.block.loggedIn()){
					var self = this;
					this.login();
					return;
				}else{
					if(this.block.isOwner()){
						openEditor(this.block.getKey(), this.block.getHost());
					}else
						alert("No estas autorizado para editar este bloque");
				}*/
			}
		};
		
		this.login = function(){
			//Abre el dialogo para iniciar sesion
			var content = '<div class="block-login">\
			<form method="get">\
				<div class="row titular"><a href="'+this.block.getHost()+'"><img border="0" src="'+this.block.getHost()+'img/logo2_small.png" /></a></div>\
				<div class="row"><div class="label">Usuario:</div><div class="input"><input name="username" class="text-input" value="" /></div></div>\
				<div class="row"><div class="label">Contraseña:</div> <div class="input"><input name="password" class="text-input" type="password" value="" /></div></div>\
				<div class="row remember"><label><input type="checkbox" value="1" name="remember_me"/> Permanecer registrado</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>\
				<div class="row centrado">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Iniciar sesi&oacute;n" /></div>\
			</form>\
		</div>';
			
			this.popup = new Boxy(content, {title: "Iniciar sesi&oacute;n", modal:true});
			
			var form = this.popup.getContent().find('form');
			var self = this;
			form.submit(function(){
				self.loginSubmit();
				return false;
			});
			
			this.popup.show();
			this.popup.center('x');
			this.popup.center('y');
		};
		
		this.loginSubmit = function(){
			if(this.popup.getContent().find('form').size() == 0){
				return;
			}
			var form = this.popup.getContent().find('form')[0];
			var self = this;
			this.block.login(form.username.value, form.password.value, form.remember_me.checked);
			
		};
		
		this.loginCallback = function(result){
			if(!this.block.loggedIn())
				alert(result);
			else{
				this.popup.hide();
				this.edit();
			}
		};
		
		this.updateLinks = function(){
			var cont_sel = '#'+this.contId;
			var menu_sel = '#'+this.contId+'-menu';
			var post = $(menu_sel+' .block-post');
			var prev = $(menu_sel+' .block-prev');
			if(!post || !prev)
				return;
			if(!this.block){
				post.addClass('block-post_disabled');
				prev.addClass('block-prev_disabled');
				return;
			}else if(this.block.getVersion() == 1){
				if(this.block.getMaxVersion() > 1)
					prev.removeClass('block-prev_disabled');
				else
					prev.addClass('block-prev_disabled');
				post.addClass('block-post_disabled');
			}else if(this.block.getVersion() < this.block.getMaxVersion()){
				post.removeClass('block-post_disabled');
				prev.removeClass('block-prev_disabled');
			}else{
				post.removeClass('block-post_disabled');
				prev.addClass('block-prev_disabled');
			}
		};
		
		this.setupContainer = function(){
			//Crea todo el html necesario para msotrar el bloque
			
			var cont_sel = '#'+this.contId;
			var menu_sel = '#'+this.contId+'-menu';
			$(cont_sel).addClass('block-container');
			$(cont_sel).addClass('block-container-'+this.block.getKey());

			if($(menu_sel).size() == 0){
				//Es la primera vez que se hace el setup
				
				//Oculto el menu y el contenido
				$(menu_sel).hide();
				$(cont_sel).hide();

				//Agrega la estructura de la botonera
				$(cont_sel).before('<div id="'+this.contId+'-menu" class="block-menu">\
						<a href="javascript:;" class="block-prev" title="Versi&oacute;n previa"></a>\
						<a href="javascript:;" class="block-post" title="Versi&oacute;n posterior"></a>\
						<a href="javascript:;" class="block-refresh" title="Actualizar"></a>\
						<a href="javascript:;" class="block-more" title="M&aacute;s opciones"></a>\
						<a href="javascript:;" class="block-edit" title="Editar contenido"></a>\
						<div class="block-status" class="status"></div>\
					</div>');

				var self = this;
				$(cont_sel).bind('mouseenter', function(){
					if($(menu_sel).is(':hidden'))
						$(menu_sel).fadeIn('fast');
					var off = $(cont_sel).offset();
					$(menu_sel).css('left', (off.left+($(cont_sel).width()-$(menu_sel).width()))+'px');
					$(menu_sel).css('top', (off.top+3)+'px');
				});
				$(cont_sel).bind('mouseleave', function(e){
					var off = $(cont_sel).offset();
					if(e.pageX < off.left || e.pageX > off.left+$(cont_sel).width() || e.pageY < off.top || e.pageY > off.top+$(cont_sel).height()){
						$(menu_sel).fadeOut('fast');
					}
				});
				$(menu_sel).bind('mouseenter', function(){
					if(!self.disable_status)
						$(menu_sel+' .block-status').fadeIn('fast');
				});
				$(menu_sel).bind('mouseleave', function(){
					$(menu_sel+' .block-status').fadeOut('fast');
				});
				$(menu_sel+' .block-refresh').bind('click', function(){
					self.last();
				});
				$(menu_sel+' .block-prev').bind('click', function(){
					self.prev();
				});
				$(menu_sel+' .block-post').bind('click', function(){
					self.next();
				});
				$(menu_sel+' .block-edit').bind('click', function(){
					self.edit();
				});
			}
			
			var opts = this.block.getOptions();

			if(opts['AnchoAuto']){
				$(cont_sel).css('width', '');
			}else{
				$(cont_sel).css('width', opts['Ancho']+'px');
			}
			if(opts['AltoAuto']){
				$(cont_sel).css('overflow', '');
				$(cont_sel).css('height', '');
			}else{
				$(cont_sel).css('overflow', 'auto');
				$(cont_sel).css('height', opts['Alto']+'px');
			}

			/*$(cont_sel).css('width', opts['Ancho']+'px');
			$(cont_sel).css('height', opts['Alto']+'px');
			
			$(cont_sel).css('width', ($(cont_sel).width()-14)+'px');
			$(cont_sel).css('height', ($(cont_sel).height()-14)+'px');*/

			/*if(opts['Bordes'] == '1'){
				$(cont_sel+' .menu').css('margin-left', ($(cont_sel).width() - $(cont_sel+' .menu').width() - 22)+'px');
				$(cont_sel+' .menu').css('margin-top', '3px');
				if($(cont_sel+' .container').size() == 0){
					$(cont_sel+' .content').replaceWith('<div class="container"><div class="side_h top"><!----><div class="corner left_top"><!----></div><div class="corner right_top"><!----></div></div>\
					<div class="side_v right">\
						<div class="side_v left">\
						<div class="content"></div>\
						</div>\
					</div>\
					<div class="side_h bottom"><!----><div class="corner left_bottom"><!----></div><div class="corner right_bottom"><!----></div></div></div>');
					if($.browser.msie){
						$(cont_sel+' .content').css('width', ($(cont_sel).width()-4)+'px');
						$(cont_sel+' .content').css('height', ($(cont_sel).height()-4)+'px');
					}else{
						$(cont_sel+' .content').css('width', ($(cont_sel).width()-20)+'px');
						$(cont_sel+' .content').css('height', ($(cont_sel).height()-18)+'px');
					}
				}
			}else{
				$(cont_sel+' .menu').css('margin-left', ($(cont_sel).width() - $(cont_sel+' .menu').width() - 18)+'px');
				$(cont_sel+' .menu').css('margin-top', '1px');
				if($(cont_sel+' .container').size() > 0){
					$(cont_sel+' .container').replaceWith('<div class="content"></div>');
					$(cont_sel+' .content').css('width', $(cont_sel).width()+'px');
					$(cont_sel+' .content').css('height', $(cont_sel).height()+'px');
				}
			}*/
			
			if(opts['Bordes'] == '1'){
				$(cont_sel).css('border', '1px solid #CCC');
			}else{
				$(cont_sel).css('border', '0');
			}

			if(opts['OcultarHistorial'] == '1'){
				$(menu_sel+' .block-prev').hide();
				$(menu_sel+' .block-post').hide();
			}else{
				$(menu_sel+' .block-prev').show();
				$(menu_sel+' .block-post').show();
			}
			if(opts['OcultarActualizar'] == '1'){
				$(menu_sel+' .block-refresh').hide();
			}else{
				$(menu_sel+' .block-refresh').show();
			}
			if(opts['OcultarMasOpciones'] == '1'){
				$(menu_sel+' .block-more').hide();
			}else{
				$(menu_sel+' .block-more').show();
			}
			
			if(opts['OcultarInfo'] == '1'){
				this.disable_status = true;
			}else{
				this.disable_status = false;
			}
			
			if(this.block.isOwner()){
				$(menu_sel+' .block-edit').show();
			}else{
				$(menu_sel+' .block-edit').hide();
			}

			$(menu_sel+' .block-more').attr('href', this.block.getHost()+'Block/view?k='+this.block.getKey());
		};
		
		this.init = function(){
			//inicializo el contenedor, es independiente de los bloques
			
			var self = this;
			
			if(!document.getElementById(this.contId)) //Si no existe el contenedor lo creo
				document.write('<div id="'+this.contId+'"></div>');
			
			if(!BlockAPI.isLoaded()){
				BlockAPI.init(function(){
					self.init();				 
				});
				return;
			}
			BlockAPI.addContainer(this.contId, this);
			
			if(this.key)
				this.loadBlock(this.key, this.version, this.options, this.host);

			if(this.onReady)
				this.onReady();
		};

		this.init();
	}	
} /*Fin del if de chequeo*/
