var dBug= location.href.match('debug')?true:false;
if (!dBug) 	if (Right(location.hostname,4)!='.com')	dBug=true;
/* dom ready handlers */
$(function(){
	if ($.browser.msie && $.browser.version.substr(0,1) <= 6){
		alert("Disculpa,estamos trabajando para conseguir que este sitio se vea correctamente en navegadores anteriores a Internet Explorer 7 \n .Te agradeceria que nos visitaras con un navegador actualizado, o con Firefox. \n Gracias");
//		$('body').css('display','none');	
		$('.fix-z-index').bgiframe();
		}

	var oCp = $('#Todo');

	var oURL;
	var pagina;
	oURL = new objURL()
	pagina=oURL.valor("pantalla")
	if (pagina!=false) emerge(oURL.raiz(pagina))

 	oPagina.drawSocialLinks(oCp);

	$('.linked, .buttonLink a').live('click',function(){
		var arrId = this.id.split('_');
		var classes = this.className.split(' ');
		if (typeof (linkedHandler[arrId[0]]) == 'function'){
			linkedHandler[arrId[0]](this,arrId);
		}else if(typeof (linkedHandler[classes[0]]) == 'function'){
			linkedHandler[classes[0]](this);
		}else{
			if (dBug){
			 alert('unhandled '+this.id+ ' '+this.className); return false
			}
			return true;
		}
		return false;
	});

	if (!dBug){
 	
		if ($.isFunction($.gaTracker)) $.gaTracker('UA-9095832-1')  // Your GA tracker code  
	}
});
$(document).ready(function() {
	$("#logon").ajaxForm({
        // target identifies the element(s) to update with the server response
        target: "#MensajeLogin",
        // pre-submit callback
		success: showResponseLogon,
		beforeSubmit: function() {
            $("#MensajeLogin").html("Espere un momento, por favor...");
			
        }
    });	

});
function emerge(pagina){
		tb_show("Mensaje",pagina + "?KeepThis=true&TB_iframe=true&height=300&width=400","/js/loadingAnimation.gif")
}

/* linkhandler lookup table */
var linkedHandler = {
	tagLink:function(el){
		var eForm = document.forms.googleSearchForm;
		eForm.q.value = $(el).text();
		eForm.action = 'http://www.google.com/search';
		eForm.submit();
	},
	logoTextHolder:function(){
		location.href = '/';
	},	
	unit:function(el){
		location.href = $(el).find('.contentLink').attr('href');
	},
	googleSubmit:function(el){
		var eForm = document.forms.googleSearchForm;
		if (eForm.q.value == 'search' || $.trim(eForm.q.value) ==''){
			alert('enter a search value first.');
			eForm.q.focus();
			return false;
		}
		eForm.action = 'http://www.google.com/search';
		eForm.submit();
	},
	googleSearch:function(el){
		el.value='';
	},
//	contactSubmit:function(el){
//		$('#cntct').ajaxSubmit({beforeSubmit:formShowRequest,success:formShowResponse,type:'post'});
//	},
	contentItem:function(el,arrId){
		window.location =$(el).find('h4 > a').eq(0).attr('href')
	},
//	linkSubmit:function(){
//		$('#commentForm').ajaxSubmit({beforeSubmit:formShowRequest,success:formShowResponse,type:'post'});		
//	},
	
	replyButton:function(el,spec){	
		linkedHandler.enviar(el,spec,'replying');
	},
	readNews:function(el){
		
		window.location.href = el.href; 
	}
	
}

/* form handlers    */
function formShowRequest(formData, jqForm, options) {
	var submitIt = true;
	var messages =false ;
	var formId = jqForm.attr('id');
	oPagina.setCurrentForm(formId);
	switch (formId){
		default:
			jqForm.find('input, textarea').each(function(){
				if ($(this).hasClass('mandatory')){
					$(this).css({border:'3px solid green'}); 
					if ($.trim($(this).val())==''){
						$(this).css({border:'3px solid red'}); 
						submitIt=false;
						var sName = this.name 
						$('label').each(function(){
							if ($(this).attr('for') == sName){
								if (!messages) messages='';
								messages +='Por favor, rellene el campo '+$(this).html().replace(':','')+' ; es obligatorio'+"\n";
							}
						})
						
					}
				}
			});
			if (submitIt) jqForm.fadeOut('slow');
		break;
	} 
	if (!submitIt){
		if (messages) alert(messages)
		return false;
	}else{
	    return true; 
	}
} 
 
/* post-submit callbacks for forms */
function formShowResponse(responseText, statusText)  {
	var sformId = oPagina.getCurrentForm();
	switch (sformId){
		case'frmcomentar':
			$('#comentario').html(responseText);
			if ($('.errorMessage').length){
				$('#frmcomentar').fadeIn('slow');
				$('html').animate({'scrollTop':$('#datosCorreo').offset().top},1000);
			}else{
//				alert('Gracias, hemos recibido su comentario');
/*				if ($('input[name=replyTo]').val()>0){
					var scrollTarget = $('#comment_'+$('input[name=replyTo]').val()+' .reply:last');
					
				}else{
					var scrollTarget = $('.comment');
				}			
				$('html').animate({'scrollTop':scrollTarget.offset().top},1000);
				$(scrollTarget).css({border:'2px solid blue'})
*/				
			}				
		break; 
		default:
			eval ('var d ='+responseText) 
			if (d.success.length){
				for (var x in d.success) $('#'+sformId).append(d.success[x]); 
			}
	}
} 

function showResponseLogon(responseText, statusText)  { 
	var finOK
	var piezas
	var a
	piezas=responseText.split(":")
	for (a=1;a<=piezas.length;a++){
		if (piezas[a]=="SI") {
			finOK=true;
			$("a.user").html(piezas[a+1]);
			$("#user").show();
			$("#toggle").hide();			
			$("div#panel").slideUp("slow");
			$(".toggleLogon").toggle();
			$("#MensajeLogin").html("")
		} else{
			if (piezas[a]=="NO") {
				finOK=false;
				$("#MensajeLogin").html(piezas[a+1]);
			}
		}
	}
	
} 

/*hardCodePage constructor*/
function gMundo (){
	var currentForm = null;
    this.webRoot = arguments[0].webRoot;
    this.getCurrentForm = function(){
        return currentForm;
    };
    this.setCurrentForm = function(val){
        currentForm = val;
    };

    this.pagInit = function(){

/*
	$(function () { 
			$('#navigation').accordion(
				{
				active: false, 
				header: '.head', 
				navigation: true, 
				event: 'mouseover', 
				fillSpace: true, 
				animated: 'easeslide',
				autoHeight: true
  				});
			});
		var accordions = jQuery('#navigation');
		accordions.accordion("enable");
*/
		

		//hover states on the static widgets
		$('#dialog_link, ul#icons li').hover(
			function() { $(this).addClass('ui-state-hover'); }, 
			function() { $(this).removeClass('ui-state-hover'); }
		);
    }
    
    this.drawSocialLinks = function(oContainers){
    	var l,i,socialList = [], socialHtm='';
    	var t = "Gastronomundo:"+ $('h1 span').eq(0).text();
    	var u = window.location.href;  
		var iconDirectory = 'imagenes/iconos/';
		
		
		var socialMedia = [
			{linkText: 'Del-icio-us', icon:'delicious.png',href:'http://del.icio.us/post?url='+u+'&amp;title='+t},
			{linkText: 'Stumbleupon', icon:'stumbleupon.png',href:'http://www.stumbleupon.com/submit?url='+u},
			{linkText: 'Facebook', icon:'facebook.png',href:'http://www.facebook.com/share.php?u='+u},
			{linkText: 'Digg', icon:'digg.png',href:'http://digg.com/submit?phase=2&amp;url='+u+'&amp;title='+t},
			{linkText: 'Twitter', icon:'twitter.png',href:'http://twitter.com/home?status='+u},
			{linkText: 'Google', icon:'google.png',href:'http://www.google.com/bookmarks/mark?op=edit&bkmk='+u}
		];

		l = socialMedia.length;
		for (i=0; i<l;i++){
			socialList.push('<li><a href="'+socialMedia[i].href+'" title="'+socialMedia[i].linkText+'"><img src ="'+this.webRoot+iconDirectory+socialMedia[i].icon+'" alt="'+socialMedia[i].linkText+'" /></a></li>');
		}
		socialHtm = '<ul>'+socialList.join("\n")+'</ul>';
		oContainers.append('<div class="socialMediaContainer">'+socialHtm+'</div>'); 
    }
    
    
} // fin definicion pagina gMundo
//---------------------------Indicar el contenido dentro de los campos (para clase "dentroCampo" desde Title-----------//
// activar en "ready"
function actDentroCampo(){
// APLICA WATERMARK SI EL TEXTBOX NO TIENE VALOR
	jQuery(".dentroCampo").each(function() {
		if ($(this).val() == $(this).attr('title'))
			$(this).val('').addClass('dentroCampoOn');
		else
			if ($.trim($(this).val()) == '')
				$(this).addClass('dentroCampoOn').val($(this).attr('title'));
	});
// AL OBTENER EL FOCO LIMPIA TITLE Y QUITA CLASE DE MARCA
	jQuery(".dentroCampo").focus(function() {
		if ($(this).hasClass("dentroCampoOn")) $(this).removeClass('dentroCampoOn').val(''); });
// AL PERDER FOCO SI EL INPUT ESTÁ VACIO VUELVE A PONER MARCA
	jQuery(".dentroCampo").blur(function() {
		if ($(this).val() == '')
		$(this).addClass('dentroCampoOn').val($(this).attr('title')); });
}
//-------------------------------------------------activar fckEditor clases fck, fck1, fck2, fck3
function activaFCK(){
	    jQuery.fck.config= {
	                            path:'../FCKeditor/',
	                            width: 550,
	                            height:100,
	                            ToolbarSet :'gMundo',
								AutoDetectLanguage:true,
              					DefaultLanguage:'es',
								Config:{CustomConfigurationsPath:'../../js/fckconfig_gmundo.js'}
//	                            ToolbarLocation :'Out:xToolbar'
	                             };
	    jQuery('textarea.fck').fck({height:100});
	    jQuery('textarea.fck2').fck({toolbar:'gMundoCom',height:500});
	    jQuery('textarea.fck3').fck({toolbar:'gMundoCom',height:100,width:300});
//		jQuery.noConflict();
	};
function actFechas(nombre){
	$.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['']));
	$(nombre).datepicker($.datepicker.regional['es']);
	$(nombre).datepicker({
		changeMonth: true,
		changeYear: true,

//		showOn: 'button',
//		buttonImage: '/img.png',
//		buttonImageOnly: true,

		dateformat: 'dd-mm-yy',
		firstDay: 1
	});

}
//--------------------------------------------------------objeto objURL
//Capturamos la URL 
function objURL() {
	var nURL = document.URL; 
	var cgi
	var URL
	var DELIMITER = '&';  //Fijamos el sepador entre parametros 
//Separamos los parametros 
	cgi = nURL.substring(nURL.indexOf('?')+1,nURL.length); 
	nURL = nURL.substring(0,nURL.indexOf('?'))
		
	//Eliminamos la almohadilla, si es que existe... cortamos por lo sano! 
	if (cgi.indexOf('#')!=-1) cgi=cgi.slice(0,cgi.indexOf('#')); 
	//Troceamos el cgiString ya limpiado, separando cada par variable=valor 
	//en una de las posiciones del array 
	var arrayParams=cgi.split(DELIMITER); 
	
	this.raiz = function(pagina)
		{
		var direc;
		direc=document.location.protocol + "//" + document.location.hostname + "/" 
		if (arguments[0]) 
				direc = direc + pagina;
		return direc
		}
	this.valor = function(nombre)
		{
//			alert(nURL + "|" + cgi);
			var nombreP
			var valorP
			for (var i=0;i<arrayParams.length;i++){ 
				nombreP=arrayParams[i].substring(0,arrayParams[i].indexOf('='))
				valorP=arrayParams[i].substring(arrayParams[i].indexOf('=')+1,arrayParams[i].length) 	
				if (nombreP==nombre){
					return valorP
				}
			}
			return false
		}

	this.length=function() {return arrayParams.length;}
	this.cambia = function(nombre,valor)
		{
			var nombreP
			var valorP
			for (var i=0;i<arrayParams.length;i++){ 
				nombreP=arrayParams[i].substring(0,arrayParams[i].indexOf('='))
//				valorP=arrayParams[i].substring(arrayParams[i].indexOf('=')+1,arrayParams[i].length) 	
//				alert(nombreP+"="+nombre)
				if (nombreP==nombre){
					arrayParams[i]=nombre + "=" + valor
					return true
				}
			}
			return false
		}
	this.cambiaPagina = function(nueva)			//espera direccion absoluta desde host
		{
			nURL=raiz(nueva);
			return
		}
	this.toString = function()
		{
			var salida=nURL + "?"
			for (var i=0;i<arrayParams.length;i++){ 
				salida +=arrayParams[i] + "&"
			}
			return salida.substring(0,salida.length-1)
		}	
	this.normaliza = function(direccion,params)
		{
		var nuevo
		if (direccion.substring(0,4)=="http") 
			nuevo = direccion
		else
			nuevo = document.location.hostname + "/"+ direccion
		nuevo = document.location.protocol + "//" +nuevo
		if (arguments[1]) {
			if (params.length>0)
				nuevo=nuevo + "?" + params
		}
		return nuevo
		
		}
}

//-------------------------comunes
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}
function anotaCQ(area,id){
	if (!$.cookies.test()) {
		alert("Para usar esta funcion, \n su navegador debe aceptar cookies");
		return;
	}
	var nuevo;
	var lista=$.cookie(area)
	if (typeof(lista)=="string") {
		if ((lista+"/").indexOf("/"+id+"/")==-1) {
			lista += "/"+id;
			muevo=true;
		}
	} else{
		lista="/"+id;
		nuevo=true;
	}
/*	$.cookie(area,lista,{expires:365});
	if nuevo {
			$.post('/ajax/milista.asp',{funcion:area+"+",  valor : id } ,
			function(data) {alert('anotado!');},"JSON");
	}*/
	
}



/*     por probar se desplaza de hasta el destino de un (a) dentro de pagina
function enable_smooth_scroll() {
    function filterPath(string) {
        return string
                .replace(/^\//,'')
                .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
                .replace(/\/$/,'');
    }

    var locationPath = filterPath(location.pathname);
    
    var scrollElement = 'html, body';
    $('html, body').each(function () {
        var initScrollTop = $(this).attr('scrollTop');
        $(this).attr('scrollTop', initScrollTop + 1);
        if ($(this).attr('scrollTop') == initScrollTop + 1) {
            scrollElement = this.nodeName.toLowerCase();
            $(this).attr('scrollTop', initScrollTop);
            return false;
        }    
    });
    
    $('a[href*=#]').each(function() {
        var thisPath = filterPath(this.pathname) || locationPath;
        if  (   locationPath == thisPath
                && (location.hostname == this.hostname || !this.hostname)
                && this.hash.replace(/#/, '')
            ) {
                if ($(this.hash).length) {
                    $(this).click(function(event) {
                        var targetOffset = $(this.hash).offset().top;
                        var target = this.hash;
                        event.preventDefault();
                        $(scrollElement).animate(
                            {scrollTop: targetOffset},
                            500,
                            function() {
                                location.hash = target;
                        });
                    });
                }
        }
    });
}*/
function CleanHtml(h){
	h = h.replace(/<[/]?(font|st1|shape|path|lock|imagedata|stroke|formulas|span|xml|del|ins|[ovwxp]:\w+)[^>]*?>/gi, '')
	
	h = h.replace(/<([^>]*)style="([^>"]*)"([^>]*)>/gi, '<$1 $3>')
	h = h.replace(/<([^>]*)style='([^>']*)'([^>]*)>/gi, '<$1 $3>')
	h = h.replace(/<([^>]*)style=([^> ]*) ([^>]*)>/gi, '<$1 $3>')
	h = h.replace(/<([^>]*)style=([^>]*)>/gi, '<$1>')
	
	h = h.replace(/<([^>]*)class="([^>"]*)"([^>]*)>/gi, '<$1 $3>')
	h = h.replace(/<([^>]*)class='([^>']*)'([^>]*)>/gi, '<$1 $3>')
	h = h.replace(/<([^>]*)class=([^> ]*) ([^>]*)>/gi, '<$1 $3>')
	h = h.replace(/<([^>]*)class=([^>]*)>/gi, '<$1>')
}