var mCore = new Class({
	Implements: [Options,Events],
	options: {
		historyCalls:null
	},
	services:null,
	reqHistory:null,
	originalStyles:null,
    initialize: function(){
    	this.historyCalls = new Hash();
		window.addEvent('domready', function(){
 			HistoryManager.initialize();
			
			this.reqHistory = HistoryManager.register(
			'page-index',
			[0], // default, page 0
			function(values) {
				this.requestCall(values[0]);
			}.bind(this),
			function(values) {
				return '' + values[0] + '';
			},
			/(.*)/ // the regexp to match after the #
			);
			HistoryManager.start();
		}.bind(this));
		
		document.comCalls = new Hash();
		
				
       
    },
    placeVideoPlayer: function(video){
    
    
    		var autostart = 'false';
    		
    		if($type(video['autostart']) == 'boolean')
    		{
    			if(video['autostart'])
    			{
    				autostart = 'true';
    			}
    		}
    		
    		var width = 570;
    		var height = 352;
    		
    		if($type(video['width']) == 'number')
    		{
    			width = video['width'];
    		}

    		if($type(video['height']) == 'number')
    		{
    			height = video['height'];
    		}
    		
	    	var obj = new Swiff('players/player.swf', {
			    id: 'videoPlayer',
			    width: width,
			    height: height,
			    container: video['div'],
			    params: {
			        allowfullscreen: 'true',
			        allowscriptaccess: 'always',
			        flashvars:'file='+video['video']+'&image='+video['prev']+'&'+autostart,
			        bufferlength:'50'
			    }

			});
			//this.options.videoPlayer = obj;
		
    },
    login:function(options)
    {
    	if($type(options) != 'object')
    	{
    		return false;
    	}
    	
    	if($type(options['ready'])=="boolean")
    	{
    		if(options['ready'])
    		{
    			$('userDiv_cont').style.display = 'block';
    			$('formEmail').focus();
    			$('loginForm').addEvent('submit', function(e) {
					//Prevents the default submit event from loading a new page.
					new Event(e).stop();
					//If either the username or the password is blank we stop the request
					
					if($('formEmail').value == '' || $('formPass').value == '')
					{
						$('loginStatus').set('html','Usuario/Contraseña no pueden estar en blanco');
						return false;
					}
										
					//Empty the log and show the spinning indicator.
					var log = $('loginStatus').empty().addClass('loading');
					//Set the options of the form's Request handler. 
					//("this" refers to the $('myForm') element).
					
					
					//This code will send a data object via a GET request and alert the retrieved data.
					var jsonRequest = new Request.JSON({url: "services/login/login.php", onComplete: function(data){
					    log.empty().removeClass('loading');
					    
					    //de una vez revisamos si hubo errorses
					    if($type(data) != 'object')
					    {
					    	return false;
					    }
					    if($type(data.message) == "string")
					    {
					    	$('loginStatus').set('html',data.message);
					    }
					    else
					    {
					    	document.c.login(data);
					    }
					    
					}}).post({'formEmail': $('formEmail').value, 'formPass': $('formPass').value,'do':'login'});
					
				});

    		}	
    		return true;
    	}
    	else if($type(options.usr) == 'object')
    	{
    		
    		$('userDiv').empty();
    		$('userDiv').set('html',options.usr.nombre);
	    	this.JSONRequestData(options);
    	}
    },
    request:function(options)
    {
    	this.displayNotification({clear:true});
    	if($type(options.url) != "string")
    	{
    		return false;
    	}
    	
    	var divLess = true;
    	var updateDiv;
    	
    	if($type(options.div) == "string" || $type(options.div) == "object")
    	{
    		if($type(options.scroll) == "boolean")
    		{
    			if(options.scroll)
    			{
    				this.scroll(0);
    			}
    		}
    		else
    		{
    			this.scroll(0);
    		}
    		
    		
    		if($type(options.div) == "string")
    		{
    			updateDiv = $(options.div);
    		}
    		else
    		{
    			updateDiv = options.div;
    		}
    		
    		divLess = false;
    	}
    	
    	if($type(options.noclear) == "boolean")
    	{
    		if(options.noclear)
    		{
    			//do nothing
    		}
    		else
    		{
    			//go back to norla
    			this.setStyles({original:true});
    		}
    	}
    	else
    	{
    		//back to normal
    		this.setStyles({original:true});
    	}
    	
    	var params;
    	
    	if($type(options.params) == "string")
    	{
    		params = options.params;
    	}
    	else
    	{
    		params = "";
    	}
    	
    	var var_string = options.url;
		
		
			var myRequest = new Request.HTML({
    						method: 'post', 
    						url: options.url,
    						onRequest: function()
    						{
								if(!divLess)
								{
									updateDiv.empty().addClass('loading');
								}
								
    						},
    						onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript)
							{
								if(!divLess)
								{
									updateDiv.empty().removeClass('loading');
									updateDiv.adopt(responseTree);
								}
								
								eval(responseJavaScript);
							  
							  	if($type(options.onComplete) == 'function')
								{
									eval(options.onComplete);
								}
							    
							},
							data:params
			});
					
		
		
		if($type(options.history) == "boolean" && $type(options.uid) == "string")
		{
			if(options.history)
			{
				var muu = document.URL;
		
				if(muu.indexOf("?p=") > 0)
				{
					window.location = '/#'+options.uid;
				}
				else
				{
					this.historyCalls.set(options.uid,myRequest);
					this.reqHistory.setValue(0,options.uid);
				}
			
				
			}
		}
		
		myRequest.send();

    },
    requestCall:function(rqst)
    {
    	if(rqst == '')
    	{
    		var muu = document.URL;
		
			if(muu.indexOf("?p=") > 0)
			{
				//must relocate
				
				var title = '';
				
				var parts = muu.split('/');
				
				this.request({
						'url':'services/index/index.php',
						'div':'content',
						'history':false,
						'uid':'',
						'params':'find='+parts[parts.length-1]
					});
				
			}
			else
			{
				this.request({url:document.defaultCall,div:'content'});
			}
		
    		return true;
    	}
    	//get the request and send it =P
    	//alert(rqst);
    	if(this.historyCalls.has(rqst))
    	{
    		this.historyCalls.get(rqst).send();
    	}
    	else
    	{
    		var partesPeticion = rqst.split("/");
    		rqst = partesPeticion[0];
    		//si no hemos descargado la lista de servicios lo hacemos
			if(this.services == null)
			{
				//Obtenemos la lista de los servicios del sistema
				var jsonRequest = new Request.JSON({url: "services/catalogs/catalogs.php",async:false, onComplete: function(data){				    
				    document.c.services = data;
				    //alert(data.registro);
				    //data.each(function(uno,dos){ alert(uno + dos); });
				}}).post({'do':'getCatalogs'});	
			}
			
			//Pasamos la peticion a el servicio	si lo encontramos en el catalogo
			var service = "";
			if($type(this.services[rqst]) == "string")
			{
				//si encontre el servicio
				service = this.services[rqst];
			}
			else
			{
				//solicita que se te localize el servicio,sino 404
				var searchRes = null;
				var jsonRequest = new Request.JSON({url: "services/catalogs/catalogs.php",async:false, onComplete: function(data){				    
				    searchRes = data;
				}}).post({'do':'getCatalogs','find':rqst});
				
				if($type(searchRes.service) == "string")
				{
					service = searchRes.service;
				}
				else
				{
					this.request({url:'services/notfound/404.php',div:'content'});
					return false;
				}
			}
			
			//encontramos el servicio desconocido, mandemosle su peticion
			
			//serializemos el resto de la peticion
			var pars = "";
			var symbol = 0;
			for(var i = 0 ; i < partesPeticion.length;i++)
			{
				pars = pars + partesPeticion[i];
				
				if(symbol == 0)
				{
					symbol = 1;
					pars = pars + "=";
					
				}
				else
				{
					symbol = 0;
					pars = pars + "&";
				}
				
			}
			
			this.request({url:service,div:'content',params:pars});
			
			
			
    	}
    	
    },
    displayNotification:function(options)
    {
    	var notifDiv = 'notificationDiv';
    	if($type(options.clear) == "boolean")
    	{
    		if(options.clear)
    		{
    			$(notifDiv).empty();
    			$(notifDiv).removeClass('bad');
    			$(notifDiv).removeClass('good');		
    		}
    	}
    	
    	if($type(options.message) == "string")
    	{
    		
    		if($type(options.kind) == "string")
    		{
	    		$(notifDiv).addClass(options.kind);
    		}
    		
    		$(notifDiv).set('html',options.message);
    		this.scroll(0);
    	}
    	
    	return false;
    	
    },
    updateTopMenu:function(options)
    { 
    	if($type(options.topMenu) != "array")
    	return false;
    	
    	var topMenu = options.topMenu;
    	
    	$('topRightMenu').empty();
    	
    	var defClass = 'first';
    	
    	topMenu.each(function(el)
    	{
    		var menuElement = new Element('li',{
    				'id':el.id,
    				'html':el.name,
    				'class':defClass,
		    		'events':{
		    		 	'click': function(){
		    		 		eval(el.action);
		    		 		}
		    			}
		    		});
    		
    		menuElement.inject($('topRightMenu'));
    		
    		defClass = '';
    	});
    	
    	return true;
    },
    JSONRequestData:function(options)
    {
    	this.updateTopMenu(options);
		
		
    },
    evalRemoteCall:function(options)
    {
    	
    	
    	if($type(options.responseHTML) == "string")
    	{
    		
    		if($type(options.div) == "string")
    		{
    			//alert(options.div + "a" + options.responseHTML);
    			$(options.div).set('html',options.responseHTML);
    		}
    		
    	}

    	if($type(options.responseJavaScript) == "string")
    	{
    		eval(options.responseJavaScript);
    	}
	
		if($type(options.cRname) == 'string')
		{

			if(document.comCalls.has(options.cRname))
			{
				//alert(document.comCalls.get(options.cRname));			
				document.comCalls.get(options.cRname).run();
				alert('aa');
			}
		}
		
    		
    },
    scroll:function(val)
    {
    	if($type(val) == "number")
    	{
    		scroll(val,0);
    	}
    	else if($type(val) == "string")
    	{
    		//var myFx = new Fx.Scroll(window).toElement(val);
			var myElement = $(document.body);
			var pos = $(val).getPosition();
			
			var myFx = new Fx.Scroll(myElement).start(pos.x, pos.y - 200);
    	}
    },
    setStyles:function(data)
    {
    	if($type(data) != "object")
    	{
    		return false;
    	}
    	if(this.originalStyles == null)
    	{
    	
    		this.originalStyles = new Hash();
    	}
    	
    	var objs = document.c.originalStyles;
    			
    			objs.each(function(val,key)
    			{

    				$each(val,function(valor,llave){
    					$(key).setStyle(llave,valor);
    				});
    				
    			});
    	
    	if($type(data.original) == "boolean")
    	{
    		if(data.original)
    		{
    			//regresamos todo a como estaba
    			
    			return true;
    			
    		}
    	}
    	
    	$each(data,function(val,key){
    		
    		if(document.c.originalStyles.has(key))
    		{
	    		var oriObject = document.c.originalStyles.get(key);
    		}
    		else
    		{
    			var oriObject = {};
    		}
    		
    		//alert(val.toString);
    		//recopilamos valores originales
    		$each(val,function(valor,llave){
    			
    			if($type(oriObject[llave]) == false)
    			{
    				oriObject[llave] = $(key).getStyle(llave);	
    			}
    			//aplica
    			//$(key).setStyle(llave,valor);
    		
    		});
    		
    		//guardar	
    		document.c.originalStyles.set(key,oriObject);
    	
    	});
    	
    	
    		//aplicamos
    	$each(data,function(val,key){
    		$each(val,function(valor,llave){
				$(key).setStyle(llave,valor);
    			
    		});
    	});
    	
    	
    	
    }
});