/**
 * @author Isaac Peraza León.
 * 
 */
if (!Ser) {
	var Ser = {};
}
if (!Ser.Component) {
	Ser.Component = {};
}

Ser.apply = function(o, c, defaults){
    // no "this" reference for friendly out of scope calls
    if(defaults){
        Ser.apply(o, defaults);
    }
    if(o && c && typeof c == 'object'){
        for(var p in c){
            o[p] = c[p];
        }
    }
    return o;
};

Ser.applyIf = function(o, c){
    if(o){
        for(var p in c){
            if(Ext.isEmpty(o[p])){ 
                o[p] = c[p]; 
            }
        }
    }
    return o;
};



/*
 * Obtejo Ser.Component.Gallery
 * mas datos despues.
 */

Ser.Component.Gallery = function(config){
	
	/*Tipo de galeria parametro se enviara en request*/
	this.typeGallery = 0;
	
	this.start = 0;
	
	this.limit = 8;
	
	//INICIO Datos Agregado el 28-07-2010
	/*Variables de Parametro para la imagen Thumb e Imagen Completa*/
	this.thumbSize = 100;
	
	
	this.imageSize = 300;
	//Variable para Saber el Catalogo donde ira a buscar las imagenes
	//this.catalogoGallery = this.catalogoGallery;
	/*INICIO de TPLS*/
	//tpl de Gallery(Galeria Tam Completo)
	
	
	//tpl de GalleryThum(galeria en Mini)
	
	//tpl de Informacion
	
	
	//FINde Datos Agregados el 28-07-2010
	
	this.total = 0;
	
	this.totalPage = 0;
	
	this.totalShow = 0;
	
	// Galeria actual que se esta visualizando
	this.fotogallery = 0;
	
	this.timerGallery = '';
	
	this.timeToChange = 5000;	//10000;
	
	// Cantidad de thumbs por galeria.
	this.thumbsGallery = 8;
	
	// Ancho de la galeria de thumbs
	this.fotogalleryWidth = 600;
	
	// Indica si ya termino de mostrar el wrap con todo y animacion
	this.showComplete = true;
	
	Ser.apply(this, config);

	this.initComponent = function(){
		this.onRender();
	}
	this.initComponent();
};

Ser.Component.Gallery.prototype = {
	
	onRender : function(){
		this.selectorBase = this.selectorName;//galleryContainer
		this.imagenLoader = [];
		
		
		/*this.tpl = [		
			'<div class="fotogallery">',
				'<div class="display-picture">',
					'<div class="picturevid"><a class="picture" href="#" class="texto_0"><img width: 643px; border = "0" src="images/s.gif" /></a></div>',
					'<div class="information"></div>',
				'</div>',
				'<div class="bottom-bar">',
					'<div class="prev x-disable prev-disable y-bg-img-controls"></div>',
					'<div class="mask">',
						'<ol class="gsc">',
						'</ol>',
					'</div>',
					'<div class="next x-disable next-disable y-bg-img-controls"></div>',
				'</div>',
				'<div class="clear"></div>',
			'</div>'
		];*/
							
		//Asigna el tpl Que se envio como parametro
		this.tpl = this.tplGallery;
		
		var tag = this.tpl.join('');
		this.elDom = $(this.tpl.join('')).appendTo(this.selectorBase);
		this.galleries = $(".gsc", $(this.selectorBase));
		this.galleries.items = [];
		this.publics = new Array();
		this.prev = $(".prev", $(this.selectorBase));
		this.next = $(".next", $(this.selectorBase));
		
		this.information = $(".information", $(this.selectorBase));
		this.urlImagen 	 = $(".picturevid a", $(this.selectorBase));
		this.imgPicture  = $(".picture img:first-child", $(this.selectorBase));
		
		this.loadGallery();
		this.initEvents();
	},
	
	initEvents : function(){
		var t = this;
		this.prev.click(function(){
			t.onPrev(t);
		});
		this.next.click(function(){
			t.onNext(t);
		});
	},
	
	onPrev : function(){
		if(this.prev.hasClass('x-disable') || !this.showComplete) return;

		this.start = this.start - this.thumbsGallery;
		
		var currentGallery = $(".selected", this.galleries).parent();
		var fotogallery = currentGallery.prev();

		if(fotogallery.length == 0){
			this.moveLastGallery(currentGallery);
		}else{
			this.showGallery('PREV', true);
		}
	},
	
	onNext : function(){
		if(this.next.hasClass('x-disable') || !this.showComplete) return;
		
		this.start = this.start + this.thumbsGallery;

		var currentGallery = $(".selected", this.galleries).parent();
		var fotogallery = currentGallery.next();
		if(this.galleries.items.length == this.totalPage && fotogallery.length == 0){
			this.moveFirstGallery(currentGallery);
			return;
		}
		
		if(fotogallery.length == 0){
			this.loadGallery();
		}else{
			this.showGallery('NEXT', true);
		}
	},
	
	moveFirstGallery : function(currentGallery){
		var firstGallery = $(".gsc", $(this.selectorBase)).children(':first-child');
		
		//var pos = $(this.galleries).position();
		var posleft = parseInt($(this.galleries).css('left').replace(/px/i,''));
		var newPos = posleft + this.fotogalleryWidth;
		$(this.galleries).css("left", newPos+"px");
		
		$(currentGallery).after(firstGallery);	
		this.onNext();
	},
	
	moveLastGallery : function(currentGallery){
		var lastGallery = $(".gsc", $(this.selectorBase)).children(':last-child');

		$(this.galleries).css("left", "-"+this.fotogalleryWidth+"px");
		$(currentGallery).before(lastGallery);	
		this.onPrev();
	},
	
	loadGallery : function(){
		var t = this;
		
		//this.params = 'id='+1;
		//clearInterval(t.timerGallery);
		$.ajax({
			type: 'POST',
			url: this.urlRequest, //'request/fotogaleriaVisorRequest.php',
			data: 'limit='+t.limit+'&start='+t.start+'&'+this.params,
			success: function(response){
				t.createGallery(response);
			},
			failure: function(){
			
			}
		});
	},
	
	createGallery : function(response){
		var sdata = eval("(" + response + ")");
		this.total = sdata.totalRows;
		
		this.totalPage = Math.ceil(this.total / this.thumbsGallery);
		var t = this;
		var imgConfig = '';
		//Variable Local Que cacha el ID de la Imagen
		var id_img = this.id;
		
		if(sdata.data.length > 0){
			var wrap = $('<li class="thumb-gallery"></li>').appendTo(this.galleries);
			wrap.items = sdata.data.length;
			
			this.galleries.items.push(wrap);
			for(var i = 0; i < sdata.data.length; i++){
				
				this.publics[sdata.data[i].id_gal_det] = sdata.data[i];
				
				//Cargar imagenes de Marco principal
				
				//Asignacion de variable para la Imagen
				
				var imgL = new Image();
				
				//if(sdata.data[i].img_pri_gal == 'S'){
					var imagen = Base64.encode('img|null|'+this.catalogoGallery+'|'+sdata.data[i].code+'|'+sdata.data[i][id_img]+'|'+this.thumbSize);
					imgConfig = Base64.encode('img|null|'+this.catalogoGallery+'|'+sdata.data[i].code+'|'+sdata.data[i][id_img]+'|'+this.imageSize);
				//}else{
					//var imagen = Base64.encode('img|null|foto|'+sdata.data[i].code+'|'+0+'|70|noFoto.png');
					//imgConfig = Base64.encode('img|null|foto|'+sdata.data[i].code+'|'+0+'|300|noFoto.png');
				//}
				sdata.data[i].thumbImgCode = imagen;
				
				
				imgL.src = 'imagen.php?id='+imgConfig+'&c=1';
				this.imagenLoader.push(imgL);
				
				//"img|lineadirectaportal.com|foto|091222|12|100"
				//console.log(sdata.data[i]);
				var tpl = $.template(this.tplGalleryThum.template.join(''),{
					data : sdata.data[i]								  
				});
				var c = this.tplGalleryThum.config;
				wrap.append(tpl , c);
				//console.log(t);
				/*this.tplThumb = ['<a class="thumb-item y-bg-img-controls" href="index.php?opcion=publicacion&noticia='+sdata.data[i].id_gal_det+'" idpub="'+sdata.data[i].id_gal_det+'">',
									'<div class="y-bg-img-controls indicator"></div>',
									'<div class="img">',
										//'<img class="image" alt="descripcion imagen" src="imagen.php?id='+sdata.data[i].id_gal_det+'&cat=exterior&code=100106&s=70&X='+Math.random()+'" />',
										'<img class="image" alt="descripcion imagen" src="imagen.php?id='+imagen+'" />',
									'</div>',
									'<div class="foot">'+ellipsis(sdata.data[i].tit_gal, 60, true)+'</div>',
								'</a>'];
				*/
								
				//Asigna el tplThumb Que se envio como parametro
				//this.tplThumb = this.tplGalleryThum;
								
				//$(this.tplThumb.join('')).appendTo(wrap);
			}
			
			
			
			//Se pusieron aqui los eventos por que Jquery ocupa definirselos a cada uno de los elementos que se van creando.
			$("a.thumb-item", this.galleries).mouseover(function (e) { 
				var id = $(e.currentTarget).attr("idpub");
			   	//console.log(id);
				//console.log(e.currentTarget)
				//console.log(th)
				t.showPicture(id, e.currentTarget);
				t.clearTimer();
			});
			
			$("a.thumb-item", this.galleries).mouseout(function (e) { 
				var id = $(e.currentTarget).attr("idpub");
				t.initTimer();
			});
			
			if(this.galleries.items.length == 1){
				$('a:first', this.galleries.items[0]).mouseover();
				//this.showGallery(this.fotogallery + 1, 'NEXT', false);
				this.showGallery('NEXT', false);
			}else{
				//this.showGallery(this.fotogallery + 1, 'NEXT', true);
				this.showGallery('NEXT', true);
			}
			
			t.initTimer();
		}
	},
	
	showGallery : function(opt, animate, posCero){
		this.showComplete = false;
		this.initTimer();
		
		this.disEnableControls();
		
		if (!animate) {
			this.showComplete = true;
			return;
		}
		
		var parent = $(".selected", this.galleries).parent();
		var fotogallery = opt == 'PREV' ? parent.prev() : parent.next();
		//var posAct = this.galleries.position().left;
		var posAct = parseInt($(this.galleries).css('left').replace(/px/i,''));
		var posNew = opt == 'PREV' ? posAct + this.fotogalleryWidth : posAct - this.fotogalleryWidth;
		
		var t = this;
		
		
		/*$(this.galleries).css('left', posNew+"px");
		t.showComplete = true;
		var first = $(':first', $(fotogallery));
		t.showPicture(first.attr("idpub"), first);
		return;
		*/
		
		
		$(this.galleries).animate(
			{ 
				left: posNew+"px"
			}, 
			350, 
			null, 
			function(){
				t.showComplete = true;
				var first = $(':first', $(fotogallery));
				t.showPicture(first.attr("idpub"), first);
			}
		);
	},
	
	showInformation : function(id){
	
/* var t = $.template('<div id="foo">Hello ${name}, how are you ${question}?  I am ${me:substr(0,10)}</div>');
 *
 * $(selector).append( t , {
 *     name: 'Stan',
 *     question: 'feeling',
 *     me: 'doing quite well myself, thank you very much!'
 * });
 */
	
		var sdata = this.publics[id];
		var t = $.template(this.tplInfo.template.join(''),{
					data : sdata								  
				});
		var c = this.tplInfo.config;
		//console.log(this.information);
		this.information.html(t , c);

		//var info = this.tplInfo;
/*
		this.urlImagen.attr({
			href: 'index.php?opcion=publicacion&noticia='+data.id_gal_det
		});
		
			
		if (data.not_dia_gal == "S") {
			info.push('<p class="texto_fecha" style="font-weight: normal !important;">Actualización: '+data.hor_gal+'</p>');
		}
				
		info.push('<p class="sum">'+data.sum_gal+'</p>');			
					
		info.push('<ul class="boton" style="height: 20px; padding-top: 4px;">',
	            	'<li style="margin-right: 5px; height: 20px; border-top-width: 0px;">',
						//'<a href="index.php?opcion=publicacion&noticia='+data.id_gal_det+'" style="height: 14px;">Leer Nota</a>',
					'</li>');
	
		if(data.rel_gal >= 1){			
			info.push('<li style="background-color: #FFFFFF; margin-right: 5px; height: 20px; border-top-width: 0px;">',
							'<img src="images/galeria2.png" />',
					  '</li>');
		};
		
		if (data.rel_vid >= 1) {
			info.push('<li style="background-color: #FFFFFF; margin-right: 5px; height: 20px; border-top-width: 0px;">', 
							'<img src="images/video.png"/>', 
					  '</li>');
		}
					
		info.push('</ul>');
*/		//var info = this.tplInfo.template;
		//this.information.html(info.join(''));
		
		
		

	},
	
	showPicture : function(id, target){
		var data = this.publics[id];
		var id_img = this.id;
	   	$(".selected", this.galleries).removeClass('selected');
	   	$(target).toggleClass('selected', true);

		//if(data.img_pri_gal == 'S'){
			var imagen = Base64.encode('img|null|'+this.catalogoGallery+'|'+data.code+'|'+data[id_img]+'|'+this.imageSize);
			//var imagen = '';
		//}else{
			//var imagen = Base64.encode('img|null|exterior|'+data.code+'|'+0+'|300|noFoto.png');
		//}
		//console.log(this.tipoGaleria)
		if (this.tipoGaleria == 1){
			var srcString = '../imagen.php?id='+imagen+'&c=1';
		}else{
			var srcString = 'imagen.php?id='+imagen+'&c=1';
		}
		  
		$(this.imgPicture).attr({ 
			src: srcString
		});
		
		this.showInformation(id);	
	},
	
	disEnableControls : function(v){
		if(this.galleries.items.length == 1){
			this.prev.addClass('x-disable prev-disable');
			this.prev.removeClass('fotogallery-tbar-prev-on');
		}else{
			this.prev.removeClass('x-disable prev-disable');
		}

		if(this.totalPage == 1){
			this.next.addClass('x-disable next-disable');
			this.next.removeClass('fotogallery-tbar-next-on');
		}else{
			this.next.removeClass('x-disable next-disable');
		};	
	},
	
	initTimer : function(){
		var t = this;
		clearInterval(t.timerGallery);
		t.timerGallery = setInterval(function(){
			t.onChange();
		}, t.timeToChange);
	},
	clearTimer : function(){
		var t = this;
		clearInterval(t.timerGallery);
	},
	
	onChange : function(){
		var nextS = $(".selected", this.galleries).next();
		
		if(nextS.length > 0){//Si tiene hermanos posteriores.
			
			 this.showPicture(nextS.attr("idpub"), nextS);
		}else{
			
			if(this.next.hasClass('x-disable')){ //Si no hay mas paginas adelante.

				if(this.totalPage == 1){
					var parent = $(".selected", this.galleries).parent();
					var first = $(':first', $(parent));
					this.showPicture(first.attr("idpub"), first);
				}else{
					this.onNext();
				}
			}else{
				this.onNext();				
			}
		}
	}
} 














/*
 * Objeto Ser.ContentView
 * Carga contenido remoto y si se agrega un objecto Ser.ScrollBar realiza la paginación o
 * Si solo se cargara una vez el contenido el scroll se aplica local y no con paginado.
 */

Ser.Component.ContentView = function(main, config){
	
	if (main) {
		this.main = main;
	}
	
	this.id = '';
	
	this.elDom = '';
	
	/*Url a donde se va realizar la peticion de datos*/
	this.url = '';
	
	this.pageSize =  2;
	
	this.updateType = 'innerhtml'; /*json*/
	
	/*Object que guarda la respuesta del evento load mas el callback funcion y config del scroll*/
	this.responseSuccess = '';
	
	//Si ya se visualizo una vez 
	this.firstShow = false;
	
	this.scroll = true;
	
	this.pagesLoader = [];
	
	// Indica si ya termino de mostrar el contenido (Si tiene animacion se ejecuta hasta que termina la animacion);
	this.showComplete = true;
	
	this.isLoading = false;
	
	this.initEventsOnLoad = true;
	
	this.activateTimer = false;
	
	this.timeToChange = 10000;
	
	Ser.apply(this, config);
	
	this.initComponent = function(){
		this.onRender();
	}
	this.initComponent();
};

Ser.Component.ContentView.prototype = {
		
	onRender: function(){
		
		if(!this.elDom){
			this.elDom = $('#'+this.id);
		};		

		this.contentDom = $("."+this.cssContentDom, $(this.elDom));	
		this.scrollDom = $("."+this.cssScrollDom, $(this.elDom));	
		
		if (this.scroll) {
			this.scrollBar = new Ser.Component.ScrollBar({
				ownerCt: this,
				elDom: this.elDom, //this.scrollDom,
				targetScroller: this.contentDom,
				movePx: parseInt(this.movePx),
				moveTime: 350,
				pageSize: parseInt(this.pageSize),
				activateTimer: this.activateTimer,
				timeToChange: this.timeToChange
			});
		}
		
		if(this.autoLoad){
			this.load();
		}
		this.initEvents();
	},
	
	initEvents: function(){
		// Ejemplo para que se sobre escriba la funcionalidad en base a los items cargador via ajax.
		// Por que? el jquery no agrega el evento a los nuevos items generados, cada que cae uno se tiene que setear su evento.
		/*
		var t = this;
		$('.items', $('#idcomponente')).click(function(){
			t.verinfo();										   
		});
		*/
	},
	
	onShow : function(){
		
	},
	
	load : function(callback, config){
		this.isLoading = true;
		var t = this;
		var data;		
		if(!this.params){
			data = 'code='+t.id+'&tipo_lista='+$(t.elDom).attr('tipo_lista');
		}else{
			data = this.params;
		}
		
		//if(t.scrollBar){
			data = data +'&'+'&limit='+t.scrollBar.limit+'&start='+t.scrollBar.start;
		//}
		
		$.ajax({
			type: 'POST',
			url: t.url,
			data: data,
			success: function(response){
				t.isLoading = false;
				t.responseSuccess = {
					response: response,
					callback: callback,
					config: config
				}
				if (t.updateType = 'innerhtml') {
					t.updateInner();
				}else{
					t.updateJson();
				}
			},
			failure: function(){
			}
		});
	},
	
	updateInner : function(){
		var response = this.responseSuccess.response;
		pos = response.indexOf('|');
		//if(this.scrollBar){
			this.scrollBar.total = parseInt(response.substring(0, pos));
		//}
		var inner = response.substring(pos+1, response.length);
		
		$(this.contentDom).append(inner);
		if(!this.firstShow) {
			this.firstShow = true;
			
			if (this.main != null) {
				this.main.cargar();
			}
		}
		//if(this.scrollBar){
			this.scrollAction();
		//}
		
		if(this.initEventsOnLoad){
			this.initEvents();
		}
	},
	
	updateJson : function(){
		var t = this;
		var response = this.responseSuccess.response;
		$(this.contentDom).append(t.tpl);
		this.scrollAction();
		
		if(this.initEventsOnLoad){
			this.initEvents();
		}
	},
	
	scrollAction: function(){
		var r = this.responseSuccess;
		this.scrollBar.page = parseInt(this.pagesLoader.length) + 1;
		this.pagesLoader.push(this.scrollBar.page);
		if (r.callback) {
			//Se ejecuta una funcion de retorno enviando unos parametros.
			this.scrollBar[r.callback](r.config);
			return;
		}
		if(this.activateTimer){
			this.scrollBar.initTimer();
		}
		
		this.scrollBar.pageSize > 0 ? this.scrollBar.disEnableControlsPage() : this.scrollBar.disEnableControls();
	}
	
};



/*
 * Objeto ScrollBar.
 * Horizontal y Vertical
 */

Ser.Component.ScrollBar = function(config){
	
	this.idScrollBar = '';
	
	this.targetScroller = '';

	this.movePx  = 5;
	
	this.moveTime  = 350;
	
	this.moveClck  = true;
	
	this.moveOver  = false;
	
	this.completeMove  = true;
	
	/*Atributos para paginado*/
	this.start = 0;
	
	this.limit = 2;
	
	this.total = 0,
	
	// Cantidad de contenidos (filas, registros; etc) por vista
	this.pageSize = 2;
	
	this.page = 0;
	
	this.pagesContent = [];
	
	// Controles
	this.top = '';
	
	this.bottom = '';
	
	this.left = '';
	
	this.right = '';
	
	//this.limit = 2;
	
	this.activateTimer = false;
	
	this.timer = '';
	
	this.timeToChange = 10000;
	
	Ser.apply(this, config);
	
	this.initComponent = function(){
		this.onRender();
	}
	this.initComponent();
};
   
Ser.Component.ScrollBar.prototype = {

	onRender : function(config){
		var t = this;
		
		this.limit = this.pageSize;

		this.ctr = {};
		/*Se agrega el tag del Dom a los atributos del objeto scrolbar*/
		$('a[direction]', $(this.elDom)).each(function(){
			var dir = $(this).attr('direction');
			t.ctr[dir] = this;
		});
		
		this.initEvents();
	},
	
	initEvents : function(){
		var t = this;

		$('a[direction]', $(this.elDom)).click(function(){
			switch ($(this).attr('direction')) {
				case 'top':
					t.onMoveTop(this);
					break;
				case 'bottom':
					t.onMoveBottom(this);
					break;
				case 'left':
					t.onMoveLeft(this);
					break;
				case 'right':
					t.onMoveRight(this);
					break;
			}
		});
	},
	
	onMoveTop : function(tag){
		if($('img', $(tag)).hasClass('disable')) return;
		$('img', $(tag)).addClass('disable');
		
		var posAct = $(this.targetScroller).position()['top'];
		
		if (!this.pageSize) {
			var posNew = posAct + this.movePx;
		}else{	
			var posNew = posAct + this.movePx; //(this.movePx *  this.pageSize);
			this.page = this.page - 1;
		}
		this.scrollMove({top : posNew+'px'});
	},
	
	onMoveBottom : function(tag){
		if($('img', $(tag)).hasClass('disable') || this.ownerCt.isLoading) return;
		$('img', $(tag)).addClass('disable');	
		
		var posAct = $(this.targetScroller).position()['top'];
		
		
		if(!this.pageSize) {//El movimiento va hacer local
			var posNew = posAct - this.movePx;
			this.scrollMove({top : posNew+'px'});
			return;
		}
		
		var posNew = posAct - this.movePx; //(this.movePx *  this.pageSize);

		// Si la pagina no existe se crea; Se pone numero de la pagina ya que es un arreglo y este comienza en 0
		if(!this.ownerCt.pagesLoader[this.page]){
			this.start = this.start + this.pageSize;
			this.ownerCt.isLoading = true;
			this.ownerCt.load('scrollMove', {top : posNew+'px'});
		}else{
			this.page = this.page +  1;
			this.scrollMove({top : posNew+'px'});
		}
				
	},
	
	onMoveLeft : function(tag){
		if($('img', $(tag)).hasClass('disable')) return;
		$('img', $(tag)).addClass('disable');
		
		//var posAct = $(this.targetScroller).position()['left'];
		var posAct = parseInt($(this.targetScroller).css('left').replace(/px/i,''));

		if (!this.pageSize) {
			var posNew = posAct - this.movePx;
		}else{	
			var posNew = posAct + this.movePx; //(this.movePx *  this.pageSize);
			this.page = this.page - 1;
		}
		this.scrollMove({left : posNew+'px'});	
	},
	
	onMoveRight : function(tag){
		if($('img', $(tag)).hasClass('disable') || this.ownerCt.isLoading) return;
		$('img', $(tag)).addClass('disable');
		
		//var posAct = $(this.targetScroller).position()['left'];
		var posAct = parseInt($(this.targetScroller).css('left').replace(/px/i,''));
		
		if(!this.pageSize) {//El movimiento va hacer local
			var posNew = posAct - this.movePx;
			this.scrollMove({left : posNew+'px'});
			return;
		}
		
		var posNew = posAct - this.movePx; //(this.movePx *  this.pageSize);
		
		// Si la pagina no existe se crea; Se pone numero de la pagina ya que es un arreglo y este comienza en 0
		if(!this.ownerCt.pagesLoader[this.page]){
			this.start = this.start + this.pageSize;
			this.ownerCt.load('scrollMove', {left : posNew+'px'});
		}else{
			this.page = this.page +  1;
			this.scrollMove({left : posNew+'px'});
		}	
		
	},
	
	scrollMove : function(config, fast){
		if(!this.completeMove){ return;}
		this.completeMove = false;
				
		var t = this;
		

		if(!fast) fast = 1;

		$(t.targetScroller).animate(
			config, 
			(t.moveTime / fast), 
			null, 
			function(){
				if(t.activateTimer){
					t.initTimer();
				}
				t.pageSize > 0 ? t.disEnableControlsPage() : t.disEnableControls();
				t.completeMove = true;
			}
		);
	},
	
	disEnableControlsPage : function(v){
		/* Agregar o quitar clase de disable a controles top y left*/
		if(this.page == 1){
			if (this.ctr.top)	$('img', $(this.ctr.top)).addClass('disable'); 
			if (this.ctr.left)	$('img', $(this.ctr.left)).addClass('disable');
		}else{
			if (this.ctr.top)	$('img', $(this.ctr.top)).removeClass('disable'); 
			if (this.ctr.left)	$('img', $(this.ctr.left)).removeClass('disable');
		}
		
		//alert(this.page +' == '+ Math.ceil(this.total/this.pageSize));

		/* Agregar o quitar clase de disable a controles bottom y right*/
		if(this.page == Math.ceil(this.total/this.pageSize) || this.total == 0){
			if (this.ctr.bottom)	$('img', $(this.ctr.bottom)).addClass('disable'); 
			if (this.ctr.right)		$('img', $(this.ctr.right)).addClass('disable');
		}else{
			if (this.ctr.bottom)	$('img', $(this.ctr.bottom)).removeClass('disable'); 
			if (this.ctr.right)		$('img', $(this.ctr.right)).removeClass('disable');
		}
	},
	
	disEnableControls : function(v){
		var pos = this.ownerCt.contentDom.position();
		var posValue;
		/* Agregar o quitar clase de disable a controles top y left*/
		if(pos.top >= 0){
			if (this.ctr.top)	$('img', $(this.ctr.top)).addClass('disable'); 
			if (this.ctr.left)	$('img', $(this.ctr.left)).addClass('disable');
		}else{
			if (this.ctr.top)	$('img', $(this.ctr.top)).removeClass('disable'); 
			if (this.ctr.left)	$('img', $(this.ctr.left)).removeClass('disable');
		}
		
		this.ownerCt.firstChildContent = $(':first', this.ownerCt.contentDom);
		if (this.ctr.top) {
			posValue = (this.ownerCt.contentDom.height() + Math.abs(pos.top)) - this.movePx;
		}else{
			posValue = (this.ownerCt.contentDom.height() + Math.abs(pos.left)) - this.movePx;
		}
		
		if(posValue >= this.ownerCt.firstChildContent.height()){
			if (this.ctr.bottom)	$('img', $(this.ctr.bottom)).addClass('disable'); 
			if (this.ctr.right)		$('img', $(this.ctr.right)).addClass('disable');
		}else{
			if (this.ctr.bottom)	$('img', $(this.ctr.bottom)).removeClass('disable'); 
			if (this.ctr.right)		$('img', $(this.ctr.right)).removeClass('disable');
		}
	},
	
	initTimer : function(){
		var t = this;
		clearInterval(t.timer);
		t.timer = setInterval(function(){
			t.onChange();
		}, t.timeToChange);
	},
	
	clearTimer : function(){
		var t = this;
		clearInterval(t.timer);
	},
	
	onChange : function(){
		//Si hay paginas posteriores.
		if(this.page < Math.ceil(this.total/this.pageSize)){ 
			this.onMoveRight(this.ctr.right);
		}else{
			this.page = 1;
			this.scrollMove({left : '0px'}, 10);	
		}
	}
};








// Objeto Tab.
Ser.Component.Tab = function(config){
	
	this.idTab = '';
	
	this.preContent = '';
	
	this.idViewContent = '';
	
	Ser.apply(this, config);
	
	this.initComponent = function(){
		this.onRender();
	}
	this.initComponent();
};

Ser.Component.Tab.prototype = {
	
	onRender : function(){
		this.initEvents();
		
		var tabItems = $(".tabItem", $('#'+this.idViewContent));
		this.tabContents = [];
		for(i = 0; i < tabItems.length; i++){
			var v = i == 0 ? true : false;
			var idTab = $(tabItems[i]).attr('id');
			this.tabContents[idTab] = new Ser.Component.ContentView(this,{
				id: idTab,
				elDom: tabItems[i],
				autoLoad: v,
				url: this.url,
				pageSize: $(tabItems[i]).attr('pageSize') ? $(tabItems[i]).attr('pageSize') : 0,
				movePx: $(tabItems[i]).attr('movePx') ? $(tabItems[i]).attr('movePx') : 10,
				cssContentDom: 'tab-content',
				cssScrollDom: 'tab-content-scroll',
				params: this.params ? this.params : ''
			});
		}
	},
	
	initEvents : function(){
		var t = this;
		$('a.tabs', $('#'+this.idTab)).click(function(){
			t.onClick(this);
		});
	},
	
	onClick : function(tag){
		var t = this;
		$(".pestanaActiva", $('#'+t.idTab)).removeClass('pestanaActiva');
		$(tag).toggleClass('pestanaActiva', true);
		
		var content = t.preContent + $(tag).attr('id').slice(-1);
		$('#'+t.idViewContent+' > div').removeClass('tab-content-show');
		$('#'+content).addClass('tab-content-show');
	
		this.tabContents[content].onShow();
		
		if (!this.tabContents[content].firstShow) {
			this.tabContents[content].load();
		}
	},
	
	cargar: function(){
		
	}
}



// Funcion constructora de Menu Principal.
Ser.Component.MainMenu = function(config){

	this.renderTo = '';
	
	this.posMenu = [0, 0];
	
	this.targetMenu = '';
	
	this.timer = '';
	
	Ser.apply(this, config);
	
	this.initEvents();
};

Ser.Component.MainMenu.prototype = {
	
	initEvents : function(){
		var t = this;
		
		$('li', '#'+this.targetMenu).hover(
			function(){
				t.mouseOverMain();
        	}, 
			function () {
				t.initTimer();
			}
		);
		
        /*$("li:has(ul)", $('#'+this.targetMenu)).hover(
          function () {
              $('> ul', $(this)).css({display: "block", left: $(this).width()}); 
			  t.mouseOverMain();
          }, 
          function () {
              $('> ul', $(this)).css({display: "none"}); 
			  t.initTimer();
          }
        );*/	
		
		$("li div:has(ul)", $('#'+this.targetMenu)).hover(
          function () {
              $('> ul', $(this)).css({display: "block", left: $(this).width()}); 
			  t.mouseOverMain();
          }, 
          function () {
              $('> ul', $(this)).css({display: "none"}); 
			  t.initTimer();
          }
        );	
		
		$('#'+this.renderTo).hover(
			function(){
				t.mouseOverMain();
			},
			function(){
				t.initTimer();
			}
		);
	},

	initTimer : function(){
		var t = this;
		t.timer = setTimeout(function(){
			t.hideMenu();							  
		}, 1250);
	},
	
	hideMenu : function(){
		if(this.timer){
			$('#'+this.targetMenu).css({display: 'none'});
		}
	},

	mouseOverMain : function(){
		var t = this;
		t.timer = null;
		clearTimeout(t.timer);
		t.posMenu = $('#'+t.renderTo).position();
		$('#'+t.targetMenu).css({display: 'block'});
		$('#'+t.targetMenu).css({top: (t.posMenu.top+t.heightMenu) +"px", left: t.posMenu.left +"px"});
	}
}

