include(path+'js/main-config.js');

if(typeof(JSON)!='object') include(path+'js/util/json2.js');

/*VARIABLES GLOBALES DEL PROYECTO*/
var _SESSION=null;
var diccionario=null;
var url_actual='';
var mainFocus=true;
var pageTracker=null; //Google Analitycs


$(document).ready(
	function() {
		try{
			$.ajaxSetup({
				url: "/xmlhttp/",
				type: 'POST',
				dataType: 'html',
				//timeout: 5000,
			    async:true,
			    global:false,
				beforeSend: function() {aBeforeSend(this);},
				error: function(e, xhr, settings, exception) {aError(e, xhr, settings, exception);},
				complete: function() {aComplete(this);},
				success: function() {aSuccess(this);}
			});

			
			//Inicia el tracer
			traceInit(show_trace);
			trace('main');
			initGA();//inicia Google Analityc Tracker

			//loadSession();
			/*if(getSession('languages')!=null){
				if(getSession('languages').indexOf(getSession('lang'))==-1){
					delSessionAttr('lang');
					//dumpSession();
				}
			}
			if(getSession('lang')==null || getSession('lang')=='') */setLang(default_lang);
			
		}catch(err){
			errorMsg(err,arguments);
			return null;
		}

		url_actual=window.location.href;
		
	}
);

function aBeforeSend(e){
	$('body').css('cursor', 'progress');  
	$('#preload').show();
	$('#cms_preloader').show();

}

function aError(e, xhr, settings, exception){
	//alert(xhr+'error in: ' + settings + ' \\n'+'error:\\n' + exception);
	$('body').css('cursor', 'default');
	$('#preload').hide();
	$('#cms_preloader').hide();
}

function aComplete(e){
	$('body').css('cursor', 'default');
	$('#preload').hide();
	$('#cms_preloader').hide();
}

function aSuccess(e){
	$('body').css('cursor', 'default');
	$('#preload').hide();
	$('#cms_preloader').hide();
}

function errorMsg(err,arg){
	try{
		if(showErrors){
			name=arg.callee.toString().substring(arg.callee.toString().indexOf('function')+9,arg.callee.toString().indexOf('('));
			alert('ERROR en funcion "'+name+'"\n\n'+err.name + ': ' + err.message);
		}
	}catch(err){
		if(showErrors){ alert('ERROR en funcion "errorMsg"\n\n'+err.name + ': ' + err.message);}		
	}		
}

function getFlash(objeto, src, idFlash, ancho, alto, parametros){
	try{
	
	objeto=objeto.replace(/#/g,'');
	escribir($('#'+objeto), '<div id="flashObjectConteiner"></div>');
	var vars = {};
    // parametros debe ser un arreglo
	for(var i=0; i < parametros.length; i++){
		//swfobject.addVariable("var_"+i, parametros[i]);
		vars["var_"+i] = parametros[i];
	}

	var params = {
		//scale: "noScale",
		allowScriptAccess: "always",
		//allowFullSCreen: "true",
		quality:'high',
		wmode:'transparent'
	};

	var attributes = {
		id: idFlash,
		name: idFlash
	};

	var callback=null;
	$('#'+objeto).addClass('flash');
	
	var url=path+"includes/"+src;
	if(src.indexOf('http')==0) url=src;

	swfobject.embedSWF(url, "flashObjectConteiner", ancho, alto, "9.0.24", null, vars, params, attributes, callback);

	return null;
	}catch(err){
		errorMsg(err,arguments);
		return null; 
	}
}

function initFlowplayer(){
	//FLOWPLAYER INIT
	try{
		$(document).find('script').each(
			function(i,it){
				if($(it).attr('src')!=null){
					if($(it).attr('src').indexOf('flowplayer-3.2.0')>-1){
						$(it).remove();
						$(it).unload();
					}
				}
			}
		);

		$.include('js/util/flowplayer-3.2.0.min.js', 
		function (){
			flowplayer("a.flowplayer", "./includes/flowplayer.swf", {
				// this is the player configuration. You'll learn on upcoming demos.
				plugins:  {
					controls:  {
						//volume: false,
						play: true,
						mute: false,
						time:false
					}
				},
				
				clip:  {
					autoPlay: false,
					autoBuffering: true
				}
			});
		});

	}catch(err){
		errorMsg(err,arguments);
		return null; 
	}
}

/*   
 *     EVENTS TRACER
 */    
function traceInit(show){
	try{
		if(typeof v_trace=="undefined"){
			v_trace='- tracer initiated -\n';
			var html='';
			html+='<span id="system_trace" style="text-align:center; width:100px; position:absolute; font-weight:1000; cursor:pointer; background: #ddd" onClick="alert(getTrace());">Show Trace</span>';
			html+='<span id="system_trace_reset" style="left:102px; text-align:center; width:25px; position:absolute; font-weight:1000; cursor:pointer; background: #ddd" onClick="v_trace=\'- tracer reseted -\\n\';">R</span>';
			html+='<span id="system_trace_session" style="left:129px; text-align:center; width:25px; position:absolute; font-weight:1000; cursor:pointer; background: #ddd" onClick="alert(unescape(JSONtoString(_SESSION)));">S</span>';
			$('body').prepend(html);
		}
		if(show){ 
			$('#system_trace').show();
			$('#system_trace_reset').show();
			$('#system_trace_session').show();
		}else{
			$('#system_trace').hide();
			$('#system_trace_reset').hide();
			$('#system_trace_session').hide();
		}

	}catch(err){
		errorMsg(err,arguments);
	}
}

function trace(str){
	try{
		v_trace+=str+'\n';
	}catch(err){
		//corrije si no se inicio el tracer para q no de error
		traceInit(true);
		v_trace+=str+'\n';
	}
}

function getTrace(){
	try{
		return v_trace;
	}catch(err){
		errorMsg(err,arguments);
		return null;
	}
}

function setLang(lang){
	try{
		if(getSession('lang')==lang) return;
		setSession('lang',lang);
		dumpSession(function(response){
			location.reload(true);
		});
		
	}catch(err){
		errorMsg(err,arguments);
		return null;
	}		
}

function i18n(e){
	try{
		if(e=='[object Object]'){
			$(e).find(".i18n-set").each(function(i){
				$(this).remove();
			});

			$(e).find(".i18n").each(function(i,element){
				$(this).show();
				if(getDicValor($(this).html())!=null){
					$('<object class="i18n-set">'+unescape(getDicValor($(this).html()))+'</object>').hide().insertAfter($(this)).show();
					$(this).hide();
				}
			});
		}else{	
			if(getDicValor(e)!=null){
				e=unescape(getDicValor(e));
			}
		}
		return e;
	}catch(err){
		errorMsg(err,arguments);
		return null;
	}		
}

function getDicValor(clave){
	clave=clave.replace(new RegExp('\n','g'),'');
	clave=clave.replace(new RegExp('\r','g'),'');	
	var Ji18n=null;
	if(getDic()!=''){ 
		Ji18n=parsearJSON(getDic());
		return Ji18n[clave];
	}else{
		return null;
	}
}

function getDic(){
	return diccionario;
}

function setDic(json){
	diccionario='{';
	for(var i=0 ; i < json.list.length ; i++){
		diccionario+=((i==0)?'':',')+'"'+json.list[i].clave+'":"'+json.list[i].valor+'"';
	}
	diccionario+='}';
}
function formatText(tipo,str){
	if(tipo=='ti'){
		str=str.toLowerCase( );
		return str.replace(/^(.)|\s(.)|[.](.)/g, function($1){ return $1.toUpperCase( ); });		
	}
	if(tipo=='or'){
		str=str.toLowerCase( );
		return str.replace(/^(.)|[.]\s(.)|[.](.)|[\n\r](.)/g, function($1){ return $1.toUpperCase( ); });  
	}
	if(tipo=='ma'){
		return str.toUpperCase( );
	}
	if(tipo=='mi'){
		return str.toLowerCase( );
	}
}

/* PAGINADOR CON LISTAS UL/LI */
function newPager(offset,total,xPage,xPageGroup,pagerContainer,list,Class,actClass){
	/*
	 * Funciï¿½n utilizada para crear paginador a partir de listas ul/li
	 * 
	 * parametros:
	 * -offset: pagina la lista a partir del <offset> elemento
	 * -total: cantidad de elementos
	 * -xPage: cuantos elementos de la lista muestra por pagina
	 * -xPageGroup: cantidad de paginas a mostrar por agrupadas en las flechas
	 * -pagerContainer: id del contenedor de la paginas 
	 * -list: id del objecto ul que contiene los li
	 * -Class: nombre de la clase css para la pagina INACTIVA
	 * -actClass: nombre de la clase css para la pagina activa
	 * 
	 * ejemplo de uso: home-ui.js / pintarNoticias()
	 */
	var group=1;
	var paginas='<ul id="page_groups" class="paginador-groups" style="margin:0px; padding:0px; display:inline; list-style:none; float:right;" >\n';
	paginas += '<li>\n';
	paginas += '<span class="'+Class+'-prev " onClick="listGotoPage(this,\'-1\','+Math.ceil((total-offset)/xPage)+',\''+list+'\',\''+actClass+'\');"> << </span>\n';
	paginas += '</li>\n';
	for(var i = 1 ; i <= Math.ceil((total-offset)/xPage) ; i++){
		if(i%xPageGroup==1){
			if(i==1){
				paginas += '<li style="display:block;" id="page_group_'+group+'" >';
			}else{
				paginas += '</li>';
				paginas += '<li style="display:none;" id="page_group_'+group+'" >'; 
			}
			group++;
		}
		//paginas += (i > 1 && i%xPageGroup!=1)?'-':'';
		paginas += '<span class="'+Class+' '+((i == 1)?''+actClass+'':'') +'" onClick="listGotoPage(this,'+i+','+Math.ceil((total-offset)/xPage)+',\''+list+'\',\''+actClass+'\');">'+i+'</span>';
	}
	paginas+='<li>\n';
	paginas+='<span class="'+Class+'-next " onClick="listGotoPage(this,\'+1\','+Math.ceil((total-offset)/xPage)+',\''+list+'\',\''+actClass+'\');"> >> </span>\n';
	paginas+='</li>\n';	
	paginas+='</ul>\n';
	
	escribir($(pagerContainer),paginas);

	if(Math.ceil((total-offset)/xPage) < 2){
		$(pagerContainer).hide();
	}else{
		$(pagerContainer).show();
	}
}


function listGotoPage(caller,page,totalPages,list,activeClassName){
	/*
	 * Funciï¿½n utilizada para mostrar galerias hechas con ul/li
	 * 
	 * parametros:
	 * -caller: es el objecto html que tiene el onClick
	 * -page: pï¿½gina que muestra
	 * -totalPages: cantidad de paginas 
	 * -list: id del objecto ul que contiene los li
	 * -activeClassName: nombre de la clase css para la pagina activa
	 * 
	 * ejemplo de uso: home-ui.js / pintarNoticias()
	 */
	var paginador=$(caller).parent().parent();
	//valida click en la misma pagina
	if(page==$(paginador).find('.'+activeClassName).html()) return;
	if( page.toString().indexOf('+')==0 || page.toString().indexOf('-')==0 ){
		$(paginador).children('li').each(
			function(i,it){
				$(this).children().each(
					function(j,it1){
						if($(this).attr('class').indexOf(activeClassName)>-1){
							page = parseInt($(this).html())+parseInt(page);
							if(page==0) page=1;
							if(page>totalPages) page=totalPages;
						}
					}
				);
			}
		);
	}
	
	if($(paginador) != null && activeClassName != null){
		$(paginador).children('li').each(
			function(i,it){
				//if($(this).attr('id')!='') $(this).css('display','none');
				$(this).children().each(
					function(j,it1){
						$(this).removeClass(activeClassName);
						if(parseInt($(this).html())==page){
							$(this).addClass(activeClassName);
							$(it).css('display','block');
						}
					}
				);
			}
		);
	}

	$(list).children('li').each(
		function(i,it){
			$(this).hide();
			if(i==(page-1)){
				if($.browser.safari)
					$(this).show();
				else
					$(this).fadeIn(1000);
				
			}
		}
	);
}

function initCarousel(e,cant){
	$(e).jcarousel({
        wrap: 'last',
        scroll: cant
    });
}	
function initGA(){
	try {
		if(ga_code_tracker=='') return null;
		_uacct = ga_code_tracker;
		urchinTracker();
		pageTracker=_gat._getTracker(ga_code_tracker);
		//pageTracker._trackPageview();
	} catch (err) {
		alert('Google Analitycs:'+err);
	}
}

function getViewerType(mime){
	
   if (mime == "ppt" || mime == "pptx" ||mime == "doc" ||mime == "docx" ||mime == "pdf" ){
	 return "gviewer";
   }
   else{
	return mime;   
   }
}

function dateStringFormat(fecha){
	var hora = fecha.substring(11, 16);
	var dia = fecha.substring(8, 10);
	var mes = fecha.substring(5, 7);
	var ano = fecha.substring(0, 4);
	return (dia + '-' + mes + '-' + ano + ' ' + hora +' hs');
}

function include(file){
	if(file.indexOf('.css')>-1){
		document.write('<link href="'+file+'" rel="stylesheet" type="text/css" />');
	}else{
		document.write('<script type="text/javascript" src="'+file+'"></script>');
	}
}

/*
*    FILES
*/
/*chequea existencia de un archivo en una url relativa URI es s�ncrono*/
function fileExists(uri){	
	var result='';
	$.ajax({
		url: uri,
		async:false,
		global:false,
		cache:true,
		type:'HEAD',
		success: function(html,state) {
			result=state;
		}
	});
	
	if(result=='success')
		return true;
	else
		return false;
}

function getFiles(carpeta,success){
	try{
		var valores ='"accion":"selFiles",';	
		valores +='"carpeta":"'+carpeta+'"';

		valores='_p='+encode(escape('{'+valores+'}'));

		var url=path+'src/controller/util.php';	
		
		$.ajax({
			url:  url,
			data: valores,
			success: function(response){
				success(carpeta,parsearJSON(decode(response)));
			}
		});
	}catch(e){
		alert(e);
	}	
}

function getFileContent(file,success){
		var url=file;	
		
		$.ajax({
			url: url,
			success: function(response){
				success(response);
			}
		});
}

function obtenerArchivos(carpeta,json,success){	
	try{
		var valores ='"accion":"selFiles",';	
		valores +='"carpeta":"'+carpeta+'"';

		valores='_p='+encode(escape('{'+valores+'}'));

		var url=path+'src/controller/util.php';

		$.ajax({
			url: url,
			data: valores,
			success: function(response){
				success(json,parsearJSON(decode(response)));
			}
		});
	}catch(e){
		alert(e);
	}
}

function delFile(file,success){
	var valores ='"accion":"delFile",';	
	valores +='"file":"'+file+'"';

	valores='_p='+encode(escape('{'+valores+'}'));
	
	var url=path+'src/controller/util.php';	
	
	$.ajax({
		url: path+'src/controller/util.php',
		data: valores,
		success: function(response){
			success(parsearJSON(decode(response)));
		}
	});
}

function MSG(tipo,titulo,mensaje,callback,valor){
	try{
		//titulo=i18n(titulo);
		//mensaje=i18n(mensaje);
		if(tipo=='alert'){
			jAlert( mensaje, titulo, callback );
		}
		if(tipo=='confirm'){
			jConfirm( mensaje, titulo, callback );
		}
		if(tipo=='prompt'){
			jPrompt( mensaje, valor, titulo, callback );
			//ejemplo de uso: jPrompt( 'pregunta?','texto propuesto','titulo',function(e){alert(e);} );
		}
	}catch(err){
		errorMsg(err,arguments);		
	}
}

/*
*      MODALS
*/
function destroyModal(){
	if($('#dialog_modal').html()!=null){
		$('#dialog_modal').remove();
	}	
	if($('#dialog_modal_content').html()!=null){
		$('#dialog_modal_content').remove();
	}	
	if($('#dialog_modal_excersice').html()!=null){
		$('#dialog_modal_excersice').remove();
	}	
}


function getModal(tit, msg, okfn, cancelfn){
	if($('#dialog_modal').html()==null)
		$('body').append('<div id="dialog_modal"></div>');

	var ok=false;
	$("#dialog_modal").html(msg);
	var idioma='esp';
	//if(getSession('paisId')=='7' || getSession('paisId')=='10' || getSession('paisId')=='12') idioma='ing';
	//-------- EJEMPLO DE USO -------  getModal('titulo de ventana', 'texto de la ventana')
	if(idioma=='esp'){
		$("#dialog_modal").dialog({
			draggable: false,
			resizable: false,
			width: 500,
			modal: true,
			title: tit,
			close:function(event,ui){if(ok) okfn(); else cancelfn();$("#dialog_modal").empty();},
			buttons: { "CANCELAR": function() { ok=false; $(this).dialog("close"); }, "OK": function() { ok=true; $(this).dialog("close"); } }
		});
	}else{
		$("#dialog_modal").dialog({
			draggable: false,
			resizable: false,
			width: 500,
			modal: true,
			title: tit,
			close:function(event,ui){if(ok) okfn(); else cancelfn();$("#dialog_modal").empty();},
			buttons: { "CANCEL": function() { ok=false; $(this).dialog("close"); }, "OK": function() { ok=true; $(this).dialog("close"); } }
		});
	}
}

function getModalContent(tit, ancho, alto, html, callback){
	if($('#dialog_modal_content').html()==null)
		$('body').append('<div id="dialog_modal_content"></div>');
	
	//-------- EJEMPLO DE USO -------  getModalContent('titulo de ventana', 500, 'texto de la ventana')
	$("#dialog_modal_content").html(html);	
	$("#dialog_modal_content").dialog({
		position: 'center',
		draggable: true,
		resizable: false,
		autoResize:true,
		width: ancho,
		minHeight: alto,
		zIndex: 9999,
		modal: true,
		open: function(){$('.ui-dialog-titlebar-close').attr('href', '#'+seccion); $('embed').hide();},
		close:function(){$('embed').show(); $("#dialog_modal_content").remove();  },
		title: tit
	});
}

function getFloatWindow(id, tit, ancho, alto, html){
	if($('#dialog_float_content_'+id).html()==null)
		$('body').append('<div id="dialog_float_content_'+id+'"></div>');
	
	//-------- EJEMPLO DE USO -------  getModalContent('titulo de ventana', 500, 'texto de la ventana')
	escribir($('#dialog_float_content_'+id), html);	
	$('#dialog_float_content_'+id).dialog({
		position: 'center',
		draggable: true,
		resizable: false,
		autoResize:true, 
		width: ancho,
		minHeight: alto,
		modal: false,
		close:function(event,ui){$('#dialog_float_content_'+id).empty();},
		title: tit
	});
}

function parsearJSON(str){
	try{
		//if(debug) alert('parsearJSON:'+str);
		return eval('('+str+')');
	}catch(err){
		errorMsg(err,arguments);
		return null;
	}
}

function JSONtoString(json){
	try{
		//if(debug) alert('parsearJSON:'+str);
		return JSON.stringify(json);
	}catch(err){
		errorMsg(err,arguments);
		return null;
	}
}

function preEscribir(e,str){
	try{
		$(e).prepend(str);
		i18n($(e));
	}catch(err){
		errorMsg(err,arguments);
	}		
}

function postEscribir(e,str){
	try{
		$(e).append(str);
		i18n($(e));
	}catch(err){
		errorMsg(err,arguments);
	}		
}

function escribir(e,str){
	try{
		$(e).html(str);
		i18n($(e));
	}catch(err){
		errorMsg(err,arguments);
	}		
}

function encode(str){
	try{
		return $.base64Encode(str);
	}catch(err){
		return null;
	}
}

function decode(str){
	try{
		if(str.indexOf('}str_end')>-1){
			str=str.substring(0,str.lastIndexOf('}str_end'))
		}
		return $.base64Decode(str);
	}catch(err){
		return null;
	}
}

function inspect(obj, maxLevels, level)
{
  var str = '', type, msg;

    // Start Input Validations
    // Don't touch, we start iterating at level zero
    if(level == null)  level = 0;

    // At least you want to show the first level
    if(maxLevels == null) maxLevels = 1;
    if(maxLevels < 1)     
        return '<font color="red">Error: Levels number must be > 0</font>';

    // We start with a non null object
    if(obj == null)
    return '<font color="red">Error: Object <b>NULL</b></font>';
    // End Input Validations

    // Each Iteration must be indented
    str += '<ul>';

    // Start iterations for all objects in obj
    for(property in obj)
    {
      try
      {
          // Show "property" and "type property"
          type =  typeof(obj[property]);
		  if(obj[property]!=null){
          str += '<br><li><span style="color:#00e">(' + type + ') ' + property + 
                 ( (obj[property]==null)?(': <b>null</b>'):('')) + '</span> = '+obj[property]+'</li>';
		  }
          // We keep iterating if this property is an Object, non null
          // and we are inside the required number of levels
          if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))
          str += inspect(obj[property], maxLevels, level+1);
      }
      catch(err)
      {
        // Is there some properties in obj we can't access? Print it red.
        if(typeof(err) == 'string') msg = err;
        else if(err.message)        msg = err.message;
        else if(err.description)    msg = err.description;
        else                        msg = 'Unknown';

        str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';
      }
    }

    // Close indent
    str += '</ul>';
      
	if($('#dialog_modal_inspect').html()==null)
		$('body').append('<div id="dialog_modal_inspect"></div>');
	
	var ok=false;
	$("#dialog_modal_inspect").html(str);
	  
	$("#dialog_modal_inspect").dialog({
		draggable: false,
		resizable: false,
		width: 500,
		modal: true,
		title: 'Inspect',
		close: null,
		buttons: { "CERRAR": function() { ok=false; $(this).dialog("close"); } } 
	});

    return str;
}

function geti18nLang(success){
	try{
		var valores ="'accion':'sel',";
		valores+="'id':'0'";

		valores='_p='+encode(escape('{'+valores+'}'));
				
		url=path+'src/controller/i18n_lenguaje.php';

		$.ajax({
		    url: url,
		    data: valores,
		    success: function(response){
				success(parsearJSON(decode(response)));
			}
		});
	}catch(err){
		errorMsg(err,arguments);
		return null;
	}
}

function geti18nClaves(success){
	try{
		var valores ="'accion':'sel',";
		valores+="'id':'0'";

		valores='_p='+encode(escape('{'+valores+'}'));
				
		url=path+'src/controller/i18n.php';

		$.ajax({
		    url: url,
		    data: valores,
		    success: function(response){
				success(parsearJSON(decode(response)));
			}
		});
	}catch(err){
		errorMsg(err,arguments);
		return null;
	}
}
