/**JavaScript Document
*
*	@title: Functions
*	@author: Jesús Antonio García Valadez
*       @updated: Analee Gonzalez
*       @updated: Jorge Altamirano
*		@updated: Omar Pellon
* 	@sitio: México Desconocido
* 
* 	Ingenia Group 2010
*
**/

$j = jQuery.noConflict();
$j(document).ready(function(){
//::::::::::::::::::::::::::::::Menú de navegación::::::::::::::::::::::::::::::::::::
	var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {
								   imgDown:"assets/SpryAssets/SpryMenuBarDownHover.gif", 
								   imgRight:"assets/SpryAssets/SpryMenuBarRightHover.gif"
								   });
	
//:::::::::::::::::::::::::::::Buscador::::::::::::::::::::::::::::::::::::::::::
	$j("#search-input").focus(function(){
		this.value = (this.value == '¿Qué lugar de México quieres descubrir?') ? '' : this.value;
	});
	
	$j("#search-input").blur(function(){
		this.value = (this.value == '') ? '¿Qué lugar de México quieres descubrir?' : this.value;
	});

	$j("#search-input").focus(function(){
		this.value = (this.value == 'Introduce la palabra que deseas buscar') ? '' : this.value;
	});

	$j("#icon-magnifier").click(function(e){
		if($j("#search-input").val() == ''){
			$j("#search-input").val('Introduce la palabra que deseas buscar');
			e.preventDefault();
		}else if($j("#search-input").val() == 'Introduce la palabra que deseas buscar'){
			e.preventDefault();
		}else if($j("#search-input").val() == '¿Qué lugar de México quieres descubrir?'){
			$j("#search-input").val('Introduce la palabra que deseas buscar');
			e.preventDefault();
		}else if($j("#search-input").val() == ' '){
			$j("#search-input").val('Introduce la palabra que deseas buscar');
			e.preventDefault();
		}else{
			jQuery("#search-form").submit();
		}
	});

	YAHOO.example.BasicRemote = function() {
		// Use an XHRDataSource
		var oDS = new YAHOO.util.XHRDataSource("resultados-autocomplete.html");
		// Set the responseType
		oDS.responseType = YAHOO.util.XHRDataSource.TYPE_TEXT;
		// Define the schema of the delimited results
		oDS.responseSchema = {
			recordDelim: "|",
			fieldDelim: "|"
		};
		// Enable caching
		oDS.maxCacheEntries = 5;
	
		// Instantiate the AutoComplete
		var oAC = new YAHOO.widget.AutoComplete("search-input", "container-results", oDS);

		oAC.animVert = true;
		oAC.animSpeed = 2;
		oAC.maxResultsDisplayed = 20;
		oAC.useShadow = true;
		oAC.allowBrowserAutocomplete = true;
		oAC.autoHighlight = false;
		oAC.forceSelection = false;
		oAC.dataRequestEvent.subscribe(dataRequestoAC);
		oAC.dataReturnEvent.subscribe(dataReturnoAC);

		return {
			oDS: oDS,
			oAC: oAC
		};
	}();

	function dataRequestoAC(){
		jQuery('#icon-magnifier').after(jQuery('<img src="assets/templates/md2010/images/para_home/generator.gif" alt="loading..." id="loading-data">'), jQuery('#loading-data').fadeIn());
	}

	function dataReturnoAC(){
		jQuery('#loading-data').remove();
	}


	/*::::::::::::::::::::::::::::::::::::::::::::::::bindings de la eliminación:::::::::::::::::::::::::::::::::::::::::::::::*/
	$j('a.delete-content').unbind('click');
	$j('a.delete-content').click(function() {
	    s = $j(this).attr('href').match(/#([^#]*$)/)[1].split('|');
	    if(s.length != 2) {
	        window.alert('Mala llamada');
	        return false;
	    }
	    s = 'i='+s[0]+'&t='+s[1];
	    m = $j('a:eq(0)', $j(this).parents('td'));
	    m = (m.length>0)? '¿Deseas borrar\n"'+m.text()+'"\nde manera definitiva?' : '¿Deseas borrar ese registro de manera definitiva?';
	    if(window.confirm(m)) {
	        $j.ajax({
	            type: 'POST',
	            url: 'form-delete',
	            data: s,
	            success: delSuccessResponse,
	            dataType: 'html',
	            error: delErrorResponse
	        });
	    } 
	    return false;
	});

	//binding para la votación: donde se puede votar... se vota :-D
	//votación user
	$j('.user-vote-neg,.user-vote-pos').unbind('click');
	$j('.user-vote-pos').click(function() {
	      return voteRequest(this, 'p');
	});
	$j('.user-vote-neg').click(function() {
	      return voteRequest(this, 'n');
	});
	//votación posts
	$j('.post-vote-neg,.post-vote-pos').unbind('click');
	$j('.post-vote-pos').click(function() {
	      return voteRequest(this, 'p');
	});
	$j('.post-vote-neg').click(function() {
	      return voteRequest(this, 'n');
	});
	//votacion media
	$j('.userimg-vote-pos,.userimg-vote-neg').unbind('click');
	$j('.userimg-vote-pos').click(function() {
	    return voteRequest(this, 'p');
	});
	$j('.userimg-vote-neg').click(function() {
	    return voteRequest(this, 'n');
	});
	//votacion preguntas
	$j('.question-vote-pos,.question-vote-neg').unbind('click');
	$j('.question-vote-pos').click(function() {
	    return voteRequest(this, 'p');
	});
	$j('.question-vote-neg').click(function() {
	    return voteRequest(this, 'n');
	});
	//votacion comentarios de preguntas, alias respuestas
	$j('.answer-vote-pos,.answer-vote-neg').unbind('click');
	$j('.answer-vote-pos').click(function() {
	    return voteRequest(this, 'p');
	});
	$j('.answer-vote-neg').click(function() {
	    return voteRequest(this, 'n');
	});
	//votacion negocios
	$j('.vote-pos-bussine,.vote-neg-bussine').unbind('click');
	$j('.vote-pos-bussine').click(function() {
	    return voteRequest(this, 'p');
	});
	$j('.vote-neg-bussine').click(function() {
	    return voteRequest(this, 'n');
	});
	//votacion comentarios
	$j('.comment-vote-pos,.comment-vote-neg').unbind('click');
	$j('.comment-vote-pos').click(function() {
	    return voteRequest(this, 'p');
	});
	$j('.comment-vote-neg').click(function() {
	    return voteRequest(this, 'n');
	});
	
	//bugfix IE7 para botones de submit
	if(navigator.userAgent.indexOf('MSIE 7') != -1) {
		bs = $j('button.text-expose-but');
		is = $j('<input type="submit" class="text-expose-but" style="color: black;" />').val(bs.html());
		bs.replaceWith(is);
	}
	
	//Mostrar y esconder form login y olvide password
	$j('.text-olvido-pass').click(function(){
		$j('.wrapper-expose-login').css({display:'none'}); 
		$j('.wrapper-expose-olvido').css({display:'block'});
	});
	$j('.text-return-login').click(function(){
		$j('.wrapper-expose-olvido').css({display:'none'});
		$j('.wrapper-expose-login').css({display:'block'}); 
	});

	//respuestas se pueden responder en todo el sitio
	validaRespuesta();
	
	//Elimina el link de la última pestaña del anunciante, a esta sección sólo se llega mediante el listado de negocios.
	$j(".last-anun-tab a").removeAttr("href");
	//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Funciones de Log-in y olvido de password:::::::::::::::::::::::::::::::::::::::
//Valida y envia el Log-in	
	$j('#frmLogin-User').validate({
	    messages: {
	         user_nom: {
			required: 'Campo Obligatorio'
	         },
	         user_pass: {
			required: 'Campo Obligatorio'
	         }
	    },
	    rules: {
	        user_nom: {
	            required: true
	        },
	        user_pass: {
	            required: true
	        }
	    },
	    errorClass: "invalid-password",
	    submitHandler: function(frm) {
			$j('#wrongpass').remove();
			$j('label.invalid-password').remove();
			frm.p.value = hex_sha1(frm.user_pass.value);
			frm.user_pass.value = "";
			$j("#frmLogin-User").ajaxSubmit({
				beforeSubmit: loginRequestUser, // pre-submit callback 
				success: loginResponseUser // post-submit callback
			});
		}
	});

//Valida y envia el mail para recuperar los datos de acceso
	$j("#olvido").validate({
		messages: { 
			mail: {
				required: "Campo Obligatorio",
				email: "Escribe un mail válido"
			}
		},
		rules: {
			mail: {
				required: true,
				email: true
			}
		},
		errorClass: "invalid-password",
		submitHandler: function(frm) {
			$j("#wrongpass").remove();
		$j("#success-pass").empty();
			$j("#success-pass").hide(15000);
			var encrypt = hex_sha1($j("#olvido-mail").val());
			$j("#olvido-mail").value = encrypt;
			$j("#olvido").ajaxSubmit({
				beforeSubmit: missedPasswordRequestUser, // pre-submit callback 
				success: missedPasswordResponseUser, // post-submit callback
				clearForm: true
			});
		}
	});
	
//Valida y envia el mail para recuperar los datos de acceso anunciante
	$j("#olvido-advertiser").validate({
		messages: { 
			mail_advertiser: {
				required: "Campo Obligatorio",
				email: "Escribe un mail válido"
			}
		},
		rules: {
			mail_advertiser: {
				required: true,
				email: true
			}
		},
		errorClass: "invalid-password",
		submitHandler: function(frm) {
			$j("#wrongpass").remove();
			$j("#success-pass-advertiser").empty();
			$j("#success-pass-advertiser").hide(15000);
			var encrypt = hex_sha1($j("#olvido-mail-advertiser").val());
			$j("#olvido-mail-advertiser").value = encrypt;
			$j("#olvido-advertiser").ajaxSubmit({
				beforeSubmit: missedPasswordRequestAdvertiser, // pre-submit callback 
				success: missedPasswordResponseAdvertiser, // post-submit callback
				clearForm: true
			});
		}
	});	
//Valida y envia el Log-in Anunciante	
	$j('#frmLogin-Advertiser').validate({
	    messages: {
	         advertiser_nom: {
			required: 'Campo Obligatorio'
	         },
	         advertiser_pass: {
			required: 'Campo Obligatorio'
	         }
	    },
	    rules: {
	        advertiser_nom: {
	            required: true
	        },
	        advertiser_pass: {
	            required: true
	        }
	    },
	    errorClass: "invalid-password",
	    submitHandler: function(frm) {
		$j('#wrongpass').remove();
		frm.a.value = hex_sha1(frm.advertiser_pass.value);
		frm.advertiser_pass.value = "";
            $j("#frmLogin-Advertiser").ajaxSubmit({
				beforeSubmit: loginRequestAdvertiser, // pre-submit callback 
				success: loginResponseAdvertiser // post-submit callback
	    	});
	    }
	});	
    
//Pruebas Israel
	jQuery('#weather-widget').append('<div id="weather-layer"></div>');
	jQuery('#weather-layer').click(function(e){
		e.preventDefault();
		return false;
	});
	jQuery('#netWxV2').click(function(e){
		e.preventDefault();
		return false;
	});
	
}); 
/*
 * Fin de document.ready
 */

//:::::::::::::::::::::::::::::::::: Funciones para AjaxSubmit de login usuario ::::::::::::::::::::::::::::::::::
	function loginRequestUser(formData, frm, options) {
		$j('input[name=p]', frm).after($j('<span id="sending" class="text-normal2" style="color: #ff6600">Validando usuario</span>'))
	}

	function loginResponseUser(responseText, statusText, xhr, frm) {
		$j("#sending").remove();
		//Obtiene la información sobre de donde vino el log-in
		var origen = $j("#origen").val();
		var origenId = $j("#origen-id").val();
		if(responseText == $j('#user_nom').val()) {
			//revisa el origen del log-in para saber si recarga la página o abreo otro overlay
			if(origen == 'login' && origenId == 0){
				location.href = location.href.replace(/\#.*$/, '');
			} else {
				switch(origen){
					case 'responder':
						//alert("Al recibir respuesta: origen: "+origen+" / origenId: "+origenId);
						$j("#wrapper-loginForm-user").css({display:'none'});
						$j("#responder-preg").css({'display':'block', 'z-index':'10000', 'position':'absolute', 'top':'50%', 'left':'40%'});
						$j("#resp-preid").attr({value:origenId});
					break;	
					/*case 'preguntar':
						window.location.assign('http://www.mexicodesconocido.com.mx/nueva_pregunta.html');
					break;*/
					case 'comentar':
						location.href = location.href+'#comentar';
						window.location.reload();
					break;
					default:
						location.href = location.href.replace(/\#.*$/, '');
					break;
				}
			}
		} else { 
			$j('#user_nom').val('');
			$j('#user_pass').val('');
			$j('input[name=p]', frm).after($j('<span id="wrongpass" class="text-normal2" style="color: #ff6600">Usuario y/o Password incorrecto</span>'))
		}
	}
//:::::::::::::::::::::::::::::::::: Funciones para AjaxSubmit de olvido de password de usuario ::::::::::::::::::::
	function missedPasswordRequestUser(formData, frm, options) {

	}

	function missedPasswordResponseUser(responseText, statusText) {
		if(responseText == '1') {
			location.href = location.href.replace(/\#.*$/, "");
			$j("#success-pass").append("Tu password ha sido enviado a tu correo.");
		} else { 
			$j("#olvido-mail").val("");
			$j("#success-pass").after($j('<span id="wrongpass" class="text-olvido-pass" style="color: #ff6600">Usuario y/o Password incorrecto</span>')).hide(15000).remove();
		}
	}
//::::::::::::::::::::::::::::::::: Funciones dpara AjaxSubmit de login de anunciante ::::::::::::::::::::::::::::::
	function loginRequestAdvertiser(formData, frm, options) {
	}

	function loginResponseAdvertiser(responseText, statusText, xhr, frm) {
		if(responseText == $j('#advertiser_nom').val()) {
			location.href = location.href.replace(/\#.*$/, '');
		} else { 
			$j('#advertiser_nom').val('');
			$j('#advertiser_pass').val('');
			$j('input[name=a]', frm).after($j('<span id="wrongpass" class="text-olvido-pass" style="color: #ff6600">Usuario y/o Password incorrecto</span>'))
		}
	}
//::::::::::::::::::::::::::::::::: Funciones para AjaxSubmit de olvido de passsword de anunciante ::::::::::::::::
	function missedPasswordRequestAdvertiser(formData, frm, options) {

	}

	function missedPasswordResponseAdvertiser(responseText, statusText) {
		if(responseText == '1') {
			location.href = location.href.replace(/\#.*$/, "");
			$j("#success-pass-advertiser").append("Tu password ha sido enviado a tu correo.");
		} else { 
			$j("#success-pass-advertiser").append(responseText).hide(15000).empty();
			$j("#olvido-mail-advertiser").val("");
			$j("#success-pass-advertiser").after($j('<span id="wrongpass" class="text-olvido-pass" style="color: #ff6600">Usuario y/o Password incorrecto</span>')).hide(15000).remove();
		}
	}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Funciones de Log-in y olvido de password usuario :::::::::::::::::::::::::::::::::::::::
	function showLogin(origen, origenId){
		jQuery('body').append(jQuery('#wrapper-loginForm-user')).css('z-index', '10000');
		$j(".show-expose").overlay({
			target: "#wrapper-loginForm-user", 
			close: ".close-expose", 
			left: "center", 
			top: "center", 
			expose: '#000', 
			onLoad: function(event, tabIndex) {
				//Obtiene el origen e id del lugar donde se hace clic
				jQuery('body').append('<div id="overlay-background"></div>');
				jQuery('#overlay-background').fadeIn();
				var aLink = this.getTrigger().attr("href");
				var linkLimit = aLink.length-2;
				var linkParams  = aLink.substring(22, linkLimit);
				var linkArray = linkParams.split(",",2);
				var trigger = linkArray[0].replace("'","");
				//asigna los valores a un campo en el form de log-in
				$j('#origen').val(trigger);
				$j('#origen-id').val(linkArray[1]);
				$j('#loginForm-user').fadeIn('5000');
				$j('#user_nom').val('');
				$j('#user_pass').val('');
				// Manejador de evento de botón cerrar
				jQuery('#wrapper-loginForm-user .close-expose').click(function(){
					jQuery('#overlay-background').fadeOut(500, function(){jQuery('#overlay-background').remove();});
					jQuery('#wrapper-loginForm-user').fadeOut();
				});
				
				jQuery('#overlay-background').click(function(){
					jQuery('#wrapper-loginForm-user .close-expose').click();
				});
			}, 
			onClose: function() {
				$j('#origen').val('');
				$j('#origen-id').val('');
				$j('#wrapper-loginForm-user').removeAttr('style');
				var aLink = this.getTrigger().attr("href");
				var linkLimit = aLink.length-2;
				var linkParams  = aLink.substring(22, linkLimit);
				var linkArray = linkParams.split(",",2);
				var trigger = linkArray[0].replace("'","");
				//revisa si tiene que esconder algun campo
				switch(trigger){
					case 'responder':
						$j("#responder-preg").css({'display':'none'});
						$j("#resp-preid").val('');
						window.location.reload();
					break;
					/*case 'comentar':
						$j("#expose-comenta").css({'display':'none'});
						window.location.reload();
					break;*/
				}
				jQuery('#overlay-background').fadeOut(500, function(){jQuery('#overlay-background').remove();});
				jQuery('#wrapper-loginForm-user').fadeOut();
			}
		});
	}
	
	$j('#loginForm-user div#frmLogin-User div.olvido-pass a.text-olvido-pass').click(function(e){
		e.preventDefault();
		$j('#loginForm-user').hide('', $j('#olvido-pass-user').fadeIn('5000'));
	});
	
	$j('#olvido-pass-user div#olvido div.olvido-pass a.text-return-login').click(function(e){
		e.preventDefault();
		$j('#olvido-pass-user').hide('', $j('#loginForm-user').fadeIn('5000'));
	});
	
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Funciones de Log-in y olvido de password anunciante :::::::::::::::::::::::::::::::::::::::
//muestra el Log-in

	function showLoginAdvertiser(){
		jQuery('body').append(jQuery('#loginForm-Advertiser')).css('z-index', '10000');
		$j("#advertiser-overlay").overlay({
			target: "#loginForm-Advertiser", 
			close: ".close-expose", 
			left: "center", 
			top: "center", 
			expose: '#000', 
			onLoad: function(event, tabIndex) {
				jQuery('body').append('<div id="overlay-background"></div>');
				jQuery('#overlay-background').fadeIn();
				$j('#form-advertiser').fadeIn('5000');
				$j('#advertiser_nom').val('');
				$j('#advertiser_pass').val('');
				// Manejador de evento de botón cerrar
				jQuery('#loginForm-Advertiser .close-expose').click(function(){
					jQuery('#overlay-background').fadeOut(500, function(){jQuery('#overlay-background').remove();});
					jQuery('#loginForm-Advertiser').fadeOut();
				});
				
				jQuery('#overlay-background').click(function(){
					jQuery('#loginForm-Advertiser .close-expose').click();
				});
			}, 
			onClose: function() {
				$j('#form-advertiser').removeAttr('style');
				jQuery('#overlay-background').fadeOut();
			}
		});
	}
	
	$j('#form-advertiser .olvido-pass a.text-olvido-pass').click(function(e){
		e.preventDefault();
		$j('#form-advertiser').hide('', $j('#olvido-pass').fadeIn('5000'));
	});
	
	$j('#olvido-pass #olvido .olvido-pass a.text-return-login').click(function(e){
		e.preventDefault();
		$j('#olvido-pass').hide('', $j('#form-advertiser').fadeIn('5000'));
	});
/********Funciones*Sección para eliminar genéricamente************************/
function delSuccessResponse(data, textStatus, xml) {
    data = data.split('|', 2);
    if(data.length != 2 || data[0] < 1) 
        alert('Something went wrong :-( ' + data[0] + '\n' + data);
    else {
        location.href = (data[1]);
    }
}

function delErrorResponse(XMLHttpRequest, textStatus, errorThrown) {
    console.log(XMLHttpRequest);
    window.alert('Error al guardar en el servidor:\n' +
        'xmlHttpRequest.status: ' + XMLHttpRequest.status + '\n' +
        'status: ' + textStatus + '\n' +
        'errorThrown: ' + errorThrown + '\n'
    );
}

/*:::::::::::::::::::::::::::::::::::::::Galería foto del día y nota:::::::::::::::::::::::::::::::::*/
function getMainGalleryPic(){
	var mainPhoto = $j(".thumbnail:first img").attr("src");
	var mainTitle = $j(".thumbnail:first span:first").html();
	var mainAutor = $j(".thumbnail:first span:last").html();

	$j("#main-photo img").attr({src:mainPhoto});
	$j("#main-photo-name").html(mainTitle+'<span class="main-photo-walk-text-separator"> / </span>'+mainAutor);
}

function galleryControls(){
	//Crea el scroll de los thumbs
	$j("#content-thumbs").scrollable({
		prev:"#left-control-gallery",
		next:"#right-control-gallery"
	});

	// Eliminar el bind de la flecha "siguiente", y crear el nuestro, bloqueando el scroll al llegar
	// al antepenúltimo elemento para evitar espacios en blanco al final.
	// Como el evento del scrollable no me da las propiedades que necesito, hay que hacer esto a mano.
	$j("html.home #right-control-gallery,html.nota #right-control-gallery,html.indices #right-control-gallery")
		.unbind("click")
		.bind("click",function(e){
				e.preventDefault();

				var a = $j("#content-thumbs").data("scrollable"); // Scrollable API
				var size = a.getSize();		// Total de elementos
				var index = a.getIndex();	// Elemento actual

				if(index < (size - 3)) {	// Si aún no estamos viendo el antepenúltimo elemento,
					a.move(1);				// hacer el scroll normal
				}
			}
		);

	//Controla el cambio de flechas de thumbs
	$j("#left-control-gallery img").mouseover(function(){
		$j(this).attr({src: "assets/templates/md2010/images/para_home/gal_flecha_atras.png"});
	});
	$j("#left-control-gallery img").mouseout(function(){
		$j(this).attr({src: "assets/templates/md2010/images/para_home/gal_flecha_atras_gris.png"});
	});
	$j("#right-control-gallery img").mouseover(function(){
		$j(this).attr({src: "assets/templates/md2010/images/para_home/gal_flecha_siguiente.png"});
	});
	$j("#right-control-gallery img").mouseout(function(){
		$j(this).attr({src: "assets/templates/md2010/images/para_home/gal_flecha_siguiente_gris.png"});
	});
}
//Cambio de imagenes en galería Foto del día
function changeImage(phoId){
	var photoUrl = $j("#thumb-photo"+phoId+" img").attr("src");
	var photoInfo = $j("#thumb-photo"+phoId+" p").html();
	var newInfo = $j("#thumb-photo"+phoId+" span:first").html() + '<span class="main-photo-walk-text-separator"> / </span>' + $j("#thumb-photo"+phoId+" span:last").html();
	$j("#main-photo img").attr({src: photoUrl});
	$j("#main-photo-name").html(newInfo);
	//$j("#zoom-button-gallery a").attr({href:photoUrl});
	//$j("#zoom-button-gallery a").attr({id:phoId});
}
//Crear la foto incial para la galería del post
function getPostGalleryPic(){
	var mainPhoto = $j(".thumbnail:first img").attr("src");
	var mainTitle = $j(".thumbnail:first span:first").html();
	var getZoomLink = $j(".thumbnail:first a").attr("href");
	var parentesisIni = getZoomLink.indexOf("(");
	var coma = getZoomLink.indexOf(",");
	var parentesisFini = getZoomLink.indexOf(")");
	var phoId = getZoomLink.substring(parentesisIni+1,coma);
	var foUsId = getZoomLink.substring(coma+1,parentesisFini);
	var zoomLink = "ver-imagen.html?usid="+foUsId+"&fid="+phoId;
	$j("#main-photo img").attr({src:mainPhoto});
	$j("#main-photo-name").html(mainTitle);
	$j("#postZoom").attr({href:zoomLink});
}
//Cambio de imagenes para la galería del post
function changePostImage(phoId, foUsId){
	var photoUrl = $j("#thumb-photo"+phoId+" img").attr("src");
	var photoInfo = $j("#thumb-photo"+phoId+" p").html();
	var newInfo = $j("#thumb-photo"+phoId+" span:first").html();
	$j("#main-photo img").attr({src: photoUrl});
	$j("#main-photo-name").html(newInfo);
	var zoomLink = "ver-imagen.html?usid="+foUsId+"&fid="+phoId;
	$j("#postZoom").attr({href:zoomLink});
}
/*:::::::::::::::::::::::::::::::::::::::::Altura general para Wrapper full content:::::::::::::::::::::::::::::::::::::::*/
function getMainHeight(){
	var fullHeight = $j("#wrapper-full-main-content").height();
	if($j("#wrapper-full-main-content").height() <= $j("#wrapper-secondary-content").height()){
		$j("#wrapper-full-main-content").height($j("#wrapper-secondary-content").height());
		fullHeight = $j("#wrapper-full-main-content").height();
	}
}
/*:::::::::::::::::::::::::::::::::::::::::Control de altura en columnas de nota::::::::::::::::::::::::::::::::::::::::::*/
function getNoteMainHeight(){
	// No se dejen llevar por el nombre de la función; lo que hace es ajustar la altura del contenido
	// y de la barra derecha para conservar el borde entre ellos
	var c = $j("#wrapper-full-main-content");
	var s = $j("#wrapper-secondary-content");
	if (s.height() > c.height()) c.height(s.height());

	// Preservemos el siguiente código para la posteridad
	//var mainContent = $j("#wrapper-full-main-content");
	//var fullHeight = mainContent.height();
	//var secondaryContent = $j("#wrapper-secondary-content");
	//var secondaryHeight = secondaryContent.height();
	//getNoteColHeight(fullHeight,1); // Alto de la barra de funciones igual al alto del contenido
	//var difference = mainContent.height() - fullHeight;
	//console.log("Altura original: "+fullHeight);
	//console.log("Altura actual: "+mainContent.height());
	//console.log("Diferencia: "+difference);
	//if(fullHeight <= secondaryHeight){
		//mainContent.height(secondaryHeight);
		//fullHeight = mainContent.height();
		//getNoteColHeight(fullHeight,2); // Alto de la barra de funciones igual al alto del contenido
	//}
}
function getNoteColHeight(fullHeight, calling){
	var noteTitleHeight = $j("#note-title").height();
	var mainContent = $j("#wrapper-full-main-content");
	var noteFunctions = $j("#wrapper-note-functions");
	if(calling==1){
		if(noteTitleHeight > 45){
			//noteFunctions.height(fullHeight-200);
			noteFunctions.height(fullHeight);
		} else {
			//noteFunctions.height(fullHeight-230);
			noteFunctions.height(fullHeight-30);
		}
	} else {
		if(noteTitleHeight > 45){
			//noteFunctions.height(fullHeight-375);
			noteFunctions.height(fullHeight-175);
		} else {
			//noteFunctions.height(fullHeight-315);
			noteFunctions.height(fullHeight-115);
		}
	}
}

/*::::::::::::::::::::::::::::::::::Tags Tooltip start::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
function getTooltipsNow() {
	$j('a.more-tags').each(function(i,e) {
	    ti = $j('#tooltip').clone().
		attr('id', 'tooltip'+i).
		insertAfter($j(this));
	    $j('.tooltip-content', ti).
		append(
		    $j('ul>li:lt(3)>a', 
			$j(this).parents('td.table-col-data2')).clone()
		).
		append(
		    $j('ul>li:gt(2)>a', 
			$j(this).parents('td.table-col-data2'))
		);
	    $j(this).tooltip({
		tip:"#tooltip"+i, 
		position: "top center", 
		offset:[7,48], 
		onBeforeShow: true
	    });
	});
}
/*:::::::::::::::::::::::::::::::::Tags Tooltip end:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/

/*:::::::::::::::::::::::::::::::::::::::::Control de altura en columnas de post::::::::::::::::::::::::::::::::::::::::::*/
function getPostMainHeight(){
	var fullHeight = $j("#wrapper-full-main-content").height();
	getPostColHeight(fullHeight,1);
	if($j("#wrapper-full-main-content").height() <= $j("#wrapper-secondary-content").height()){
		$j("#wrapper-full-main-content").height($j("#wrapper-secondary-content").height());
		fullHeight = $j("#wrapper-full-main-content").height();
		getPostColHeight(fullHeight,2);
	}
}
function getPostColHeight(fullHeight, calling){
	if(calling==1){
		if($j("#note-title").height() == 60){
			$j("#wrapper-note-functions").height($j("#wrapper-full-main-content").height()-129);
		} else {
			$j("#wrapper-note-functions").height($j("#wrapper-full-main-content").height()-99);
		}
	} else {
		if($j("#note-title").height() == 60){
			$j("#wrapper-note-functions").height(fullHeight-197);
		} else {
			$j("#wrapper-note-functions").height(fullHeight-147);
		}
	}
}
/*::::::::::::::::::::::::::::::::::::::::::ALtura del contenedor de la sección del usuario::::::::::::::::::::::::*/
function getUserMainHeight(){
	var fullHeight = $j("#wrapper-user-pages-main-content").height();
	getUserColHeight(fullHeight,1)
	if($j("#wrapper-user-pages-main-content").height() <= $j("#wrapper-secondary-content").height()){
		var newHeight = $j("#wrapper-secondary-content").height() - 126;
		$j("#wrapper-user-content").height(newHeight);
		fullHeight = $j("#wrapper-user-content").height();
		getUserColHeight(fullHeight,2);
	}
}
function getUserColHeight(fullHeight, calling){
	if(calling==1){
		$j("#user-recent-activity").height(fullHeight-445);
	} else {
		$j("#user-recent-activity").height(fullHeight-295);
	}
}
/*::::::::::::::::::::::::::::::::::::::::::ALtura del contenedor de la sección de preguntas y respuestas::::::::::::::::::::::::*/
function getQuestionMainHeight(){
	var fullHeight = $j("#wrapper-user-pages-main-content").height();
	if($j("#wrapper-user-pages-main-content").height() <= $j("#wrapper-secondary-content").height()){
		var newHeight = $j("#wrapper-secondary-content").height() - 48;
		$j("#wrapper-user-content").height(newHeight);
		fullHeight = $j("#wrapper-user-content").height();
	}
}
/*::::::::::::::::::::::::::::::::::::::::::ALtura del contenedor de la sección de ficha indices::::::::::::::::::::::::*/
function getIndexHeight(){
	if($j("#wrapper-full-main-content2").height() <= $j("#wrapper-secondary-content").height()){
		var newHeight = $j("#wrapper-secondary-content").height() - 364;
		$j("#wrapper-ficha-index-main").height(newHeight);
	}
}
/*::::::::::::::::::::::::::::::::::::::::::Altura del contenedor de la sección rutas::::::::::::::::::::::::*/
function getRuteHeight(){
	var fullHeight = $j("#wrapper-rutes-main-content").height();
	if($j("#wrapper-rutes-main-content").height() <= $j("#wrapper-secondary-content").height()){
		var newHeight = $j("#wrapper-secondary-content").height() - 511;
		$j(".editorial-content").height(newHeight);
	}
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::Home Main gallery:::::::::::::::::::::::::::::::::::::::::::::::::*/
function switchGalleryType(){
	//Gallery buttons
	$j('#gallery-view-mosaic').click(function() {
	    $j('#tiledGallery').show().next().hide();
	    $j('#mosaic-image').attr('src', 'assets/templates/md2010/images/para_home/viewer_6_blanco.png'); //w/ highlight
	    $j('#framelist-image').attr('src', 'assets/templates/md2010/images/para_home/viewer_full_naranja.png'); // wo/ highlight
	});
	
	$j('#gallery-view-framelist').click(function() {
	    $j('#tiledGallery').hide().next().show();
	    $j('#framelist-image').attr('src', 'assets/templates/md2010/images/para_home/viewer_full_blanco.png'); // w/ highlight
	    $j('#mosaic-image').attr('src', 'assets/templates/md2010/images/para_home/viewer_6_naranja.png'); //wo/ highlight
	});
}
/*::::::::::::::::::::::::::::::::::::::::::::::::Validación de Registro Usuario:::::::::::::::::::::::::::::::::*/
function validaRegistroUser() {
	$j.validator.addMethod('iecompatcombo', function(value, method) {
		return (value.length > 0)? true : false;
	}, 'Seleccione una opción');
	$j.validator.addMethod('username', 
	    function(value, method) {
	         return /^[-_a-z0-9]*$/.test(value);
	    },
	    "Este campo debe contener únicamente minúsculas de la a-z (sin acentos, diéresis, ñ), guión, guión bajo (_) y números."
	);
	$j('#form-register-user').validate({
	    messages: {
	        nombre: {
	            required: 'Llene este campo con su nombre.',
	            minlength: 'Llene con su nombre completo.'
	        },
	        mail: {
	            required: 'Llene este campo con su e-mail', 
	            email: 'Llene este campo con un correo electrónico válido'
	        },
	        nombreusuario: {
	            required: 'Llene este campo con su nombre de usuario',
	            minlength: 'Su nombre de usuario debe ser mínimo de 6 caracteres',
		    username: 'Este campo debe contener únicamente minúsculas de la a-z (sin acentos, diéresis, ñ), guión, guión bajo (_) y números.',
		    remote: 'Usuario ya existe'
	        },
	        password: {
	            required: 'Llene en este campo su contraseña',
	            minlength: 'Su contraseña debe contener al menos 8 caracteres'
	        },
	        repassword: {
	            required: 'Llene este campo con su contraseña nuévamente',
	            equalTo: 'Las contraseñas deben coincidir'
	        },
	        pregunta: {
	            required: 'Debe escoger una pregunta de seguridad',
		    iecompatcombo: 'Debe escoger una pregunta de seguridad'
	        },
	        secreta: {
	            required: 'Debe de escribir la respuesta a su pregunta de seguridad'
	        },
	        ciudad: {
	            required: 'Debe escribir la ciudad'
	        },
	        pais: {
	            required: 'Seleccione su país de la lista',
	            iecompatcombo: 'Seleccione su país de la lista'
	        },
	       
	    },
	    rules: {
	        nombre: {
	            required: true,
	            minlength: 6
	        },
	        mail: {
	            required: true, 
	            email: true
	        },
	        nombreusuario: {
	            required: true,
	            minlength: 6,
	            username: true,
		    remote: {
			type: 'post',
			url: 'procesa-username_check'
		    }
	        },
	        password: {
	            required: true,
	            minlength: 8
	        },
	        repassword: {
	            required: true,
	            equalTo: "#input-password-user"
	        },
	        pregunta: {
			required: true, 
			iecompatcombo: true
		},
		
	        secreta: {required: true},
	        ciudad: {required: true},
	        pais: {
			required: true, 
			iecompatcombo: true 
		}
	    }, submitHandler: function() {
            	$j("#form-register-user").ajaxSubmit({
            		beforeSubmit: showRequestRegistro, // pre-submit callback 
            		success: showResponseRegistro // post-submit callback
	    	});
	    }
	});
}

function showRequestRegistro(formData, jqForm, options) {
	$j('#loading-img').remove();
	$j('#button-submit-user').after($j('<img id="loading-img" src="assets/images/ajax-loader.gif" />'));
	$j('button, select, input', $j('#form-register-user')).attr('disabled', 'disabled');
}

function showResponseRegistro(responseText, statusText, xhr, $form) {
	$j('#loading-img').remove();
	if(responseText == '1') {
		go2editPerfil();
	} 
	if(responseText == '2'){
		window.location = "http://mexicodesconocido.com.mx/ebook.html";
	}
	else {
		$j('button, select, input', $j('#form-register-user')).removeAttr('disabled');
		$j('#button-submit-user').after($j('<div id="loading-img" class="text-note-funcs" style="color: #ff6600" />'));
		$j('#loading-img').text(responseText);
	}
}

/*::::::::::::::::::::::::::::::::::::::::::::::::Validación de Registro Anunciante:::::::::::::::::::::::::::::::::*/
function validaRegistroAdvertiser() {
	$j.validator.addMethod('iecompatcombo', function(value, method) {
		return (value.length > 0)? true : false;
	}, 'Seleccione una opción');
	$j('#form-register-advertiser').validate({
	    messages: {
	        nombre: {
	            required: 'Llene este campo con su nombre.',
	            minlength: 'Llene con su nombre completo.'
	        },
	        mail: {
	            required: 'Llene este campo con su e-mail', 
	            email: 'Llene este campo con un correo electrónico válido'
	        },
	        empresa: {
	            required: 'Llene este campo con el nombre de su empresa'
	        },
	        lada: {
	            required: ''
	        },
	        tel: {
	            required: '',
	            minlength: ''
	        },
	        pais: {
	            required: '',
	            iecompatcombo: ''
	        },
	        estado: {
	            required: '',
	            iecompatcombo: ''
	        },
	        del: {
	            required: 'Escriba su municipio, delegación o localidad'
	        }
	    },
	    rules: {
	      	nombre: {
	            required: true,
	            minlength: 8
	        },
	        mail: {
	            required: true, 
	            email: true
	        },
	        empresa: {
	            required: true
	        },
	        lada: {
	            required: true
	        },
	        tel: {
	            required: true,
	            minlength: 6
	        },
	        pais: {
	            required: true,
	            iecompatcombo: true
	        },
	        estado: {
	            required: true,
	            iecompatcombo: true
	        },
	        del: {
	            required: true
	        }
	    }
	});
}

/*:::::::::::::::::::::::::::::::::::::::::::::::::::Subsección Código::::::::::::::::::::::::::::::::::::::::::*/
function adaptSubSizes() { //adapta los tamaños, similar a 
	$j('.wrapper-subseccion-areas').each(function() {
	    t = $j(this);
	    t.height(t.children('.subseccion-areas:first').height());
	});
        $j('#subseccion-right-shadow').height($j('#wrapper-full-main-content').height()); //corrección de tamaño para fondo doble
}

/*:::::::::::::::::::::::::::::::::::::::::::::::::::Sección Código::::::::::::::::::::::::::::::::::::::::::*/
function adaptCenterAboveFooter() {
	//fixer for the title
	$j('#wrapper-section-title').width(
	    $j('#content-maingallery').width() + 
	        parseInt($j('#content-maingallery').
	            css('padding-right').replace(/[^0-9]*/g, '')) +
	        parseInt($j('.wrapper-main-content-margin').eq(0).
	            css('margin-left').replace(/[^0-9]*/g, ''))
	);

	border = 1;
        margin = 5;
        $j("div#mainGallery").slideViewerPro({
		buttonsWidth: 20,
		buttonsTextColor: '#000',
		leftButtonInner: '<img src="images/para_home/gal_flecha_atras_gris.png" />',
		rightButtonInner: '<img src="images/para_home/gal_flecha_siguiente_gris.png" />',
		thumbsVis: true,
                galBorderWidth: 0, 
                thumbsBorderWidth: border,
                thumbsPercentReduction: 15.10,
                thumbsTopMargin: margin,
                typo: true,
                typoFullOpacity: 0.75,
                autoslide: true,  
                asTimer: 3500,
                thumbs: 6
        });
	//añadir el hover a las flechas
	$j('#left0').bind('mouseover', function() {
	    t = $j(this); 
	    t.css('background', 'url(images/para_home/gal_flecha_atras.png) no-repeat 50% 50%');
	    i = t.children('span').children('img');
	    if(i.length > 0)
	        i.remove();
	});
	$j('#left0').bind('mouseout', function() {
	    t = $j(this); 
	    i = t.children('span').children('img');
	    t.css('background', 'url(images/para_home/gal_flecha_atras_gris.png) no-repeat 50% 50%');
	    if(i.length > 0)
	        i.remove();
	});
	$j('#right0').bind('mouseover', function() {
	    t = $j(this); 
	    t.css('background', 'url(images/para_home/gal_flecha_siguiente.png) no-repeat 50% 50%');
	    i = t.children('span').children('img');
	    if(i.length > 0)
	        i.remove();
	});
	$j('#right0').bind('mouseout', function() {
	    t = $j(this); 
	    i = t.children('span').children('img');
	    t.css('background', 'url(images/para_home/gal_flecha_siguiente_gris.png) no-repeat 50% 50%');
	    if(i.length > 0)
	        i.remove();
	});

        //centering the elements of the #wrapper-section-abovefooter:eq(0) element
        li = $j('.wrapper-section-link:eq(0)>li');
        if(li.length > 6) {
            var w = $j('<ul class="wrapper-section-link" />').css('margin', '0 auto');
            for(i = 6; i < li.length; i++) {
                li.eq(i).appendTo(w);
            }
            w.appendTo($j('#wrapper-section-abovefooter:eq(0)'));
            w.width((li.eq(0).width()+li.eq(0).css('margin-left').replace(/[^0-9]*/g, '')*2)*3);
        }
}

/*:::::::::::::::::::::::::::::::::::::::::::::::Ficha Estado Código::::::::::::::::::::::::::::::::::::::::::*/
/*--------------------------------Control del ancho del tituelo de estado---------------------------------------*/
function edoTitleWidth(){
	$j('#wrapper-section-title').width(
	    $j('#content-maingallery').width() + 
	        parseInt($j('#content-maingallery').
	            css('padding-right').replace(/[^0-9]*/g, '')) +
	        parseInt($j('.wrapper-main-content-margin').eq(0).
	            css('margin-left').replace(/[^0-9]*/g, ''))
	);
}

/*::::::::::::::::::::::::::::::::::::::User Write Post::::::::::::::::::::::::::::::::::::::::::::::::*/
function validaUserWritePost() {
       $j("#wrapper-category-tags").tabs(".wrapper-tags-options", {tabs:".tag-tab", current:"current-tag-cat"});

       $j('#main-post-editor').ckeditor({
                toolbar:[
                        ['Styles', 'Format'],
                        ['Bold', 'Italic', 'HorizontalRule', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink', 'Image']
                ],
                language:'es',
                resize_enabled: false
        });
        CKEDITOR.instances["main-post-editor"].on("instanceReady", function() {
            //set keyup event
            this.document.on("keyup", updateCkArea);
            //and paste event
            this.document.on("paste", updateCkArea);
        });

	$j.validator.addMethod('ckEditorRequired', function(value, method) {
		return ($j('#main-post-editor').val().replace(/<[^>]+>|\s/mg, '').length > 10)?
			true : false;
	}, 'Campo Obligatorio');
	$j.validator.addMethod('someCategory', tagRequired, 'Al menos selecciona un campo.');
	$j('#form-write-post').validate({
	    messages: {
	         nombre: {
			required: 'Campo Obligatorio'
	         },
	         'main_post_editor': {
			required: 'Campo Obligatorio'
	         },
	         'post-galleries': {
			required: 'Campo Obligatorio'
	         },
	         'tag_category3': {
	         }
	    },
	    rules: {
	        nombre: {
	            required: true
	        },
	        'main_post_editor': {
	            ckEditorRequired: true
	        },
		'tag_category3': {
			someCategory: true
		}
	    },
	    submitHandler: function() {
            	$j("#form-write-post").ajaxSubmit({
					//resetForm: true,
            		beforeSubmit: showRequestPost, // pre-submit callback 
            		success: showResponsePost // post-submit callback
	    	});
	    }

	});

	//manual validation of select categories
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('focusin', validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('focusout',validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('click',   validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('change',  validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('keydown', validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('keyup',   validateTags); 

	//hide error label for CK Editor
	$j('label.error[for=main-post-editor]').hide();
	//hide error label for cats and set styles
	$j('label.error[for=tag_category3]').hide().css({
		'float': 'left',
		'height': '14px',
		'margin': '-12px 0 0 162px',
		'width': '100%'
	});
}

function showRequestPost(formData, jqForm, options) {
	$j('#write-post-messages').html('<img id="loading-img" src="assets/images/ajax-loader.gif" /> Guardando...');
	$j('button, select, input', $j('#form-write-post')).attr('disabled', 'disabled');
}

function showResponsePost(responseText, statusText, xhr, $form) {
	$j('button, select, input', $j('#form-write-post')).removeAttr('disabled');
	$j('#write-post-messages').html(responseText);
}

function updateCkArea() {
	CKEDITOR.instances["main-post-editor"].updateElement;
	$j().validate().element('#main-post-editor');
}

function validateCats() {
	$j().validate().element('#form-write-post select[name=tag_category3]');
}

/*::::::::::::::::::::::::::::::::::::::Vote Now::::::::::::::::::::::::::::::::::::::::::::::::*/
function voteRequest(e, type) {
    $j(e).unbind('click');
    $j(e).click(function() { return false; });
    $j(e).fadeIn(200).append('<img src="assets/images/ajax-loader.gif" style="width:12px !important; height:12px !important; display:inline;" id="vote-loader"/>');
    p = $j(e).attr('href').substring(1);
    p = p.split('|',2);
    p.push(type);
    p = 't='+p[0]+'&i='+p[1]+'&c='+p[2];
    $j.ajax({
        type: "POST",
        url: "form-vote",
        data: p,
        cache: false,
        success: function(x,t,a) { successVote(x,t,e); }
        //error: function(x,t,a) { failVote(x,t,e) }
    });
    return false;
}

function successVote(xhr,type, p) {
	$j("#vote-loader").remove();
	if(xhr == "Votado"){
		window.alert('Ya votaste. ¡Gracias!');
	} else if(xhr == "Error"){
		window.alert('Por el momento no podemos guardar tu voto, por favor intenta más tarde.');	
	} else {
    	$j(p).html(xhr);
	}
}

function failVote(xhr,t,p) {
    if(xhr.status == 401) {
        $j(p).html(xhr.responseText);
        window.alert('Ya votaste. ¡Gracias!');
    } else {
        window.alert('No se pudo aplicar su voto,\n'+
            "necesita estar loggeado.\n"+
            "Se recargará la página\n\nError:\n"+
            xhr.responseText);
        window.location.href=location.href.replace(/#.*$/, '');
    }
}

/*:::::::::::::::::::::::::::::::::Ends Vote Now::::::::::::::::::::::::::::::::::::::::::::::::*/

/*::::::::::::::::::::::::::::::::::::::User Edit Post::::::::::::::::::::::::::::::::::::::::::::::::*/
function validaUserEditProfile() {
        getUserMainHeight();
	$j('#label-state-user').width('120px');
	$j('label.error').hide();
	$j.validator.addMethod('mxPhoneOpt', mxPhoneOpt, 'Formato Inválido');
	$j.validator.addMethod('mxPhoneToll', mxPhoneToll, 'Formato Inválido');
	$j.validator.addMethod('birthday', function(value, method) {
		return !/Invalid|NaN/.test(new Date(
			parseInt($j('#select-day-user').val()), 
			parseInt($j('#select-month-user').val()) - 1, 
			parseInt($j('#input-year-user').val()), 
			0, 0, 0, 0)) &&
			16 <= (new Date().getFullYear() - parseInt($j('#input-year-user').val())) && 
			(new Date().getFullYear() - parseInt($j('#input-year-user').val())) <= 100;
	}, 'Campo Obligatorio');
	$j('#form-edit-user-profile').validate({
	    messages: {
	         nombre: {
			required: 'Campo Obligatorio'
	         },
	         mail: {
			required: 'Campo Obligatorio',
			email: 'E-mail inválido'
	         },
	         sexo: {
			required: 'Campo Obligatorio'
	         },
	         dia: {
	         },
	         'new_pass': {
			required: 'Campo Obligatorio',
			minlength: 'Mínimo 8 caracteres'
	         },
	         'confirm_pass': {
			required: 'Campo Obligatorio',
			equalTo: 'Las contraseñas no coinciden'
	         },
	         ciudad: {
			required: 'Campo Obligatorio'
	         },
	         estado: {
			required: 'Campo Obligatorio'
	         },
	         pais: {
			required: 'Campo Obligatorio'
	         },
	         presentacion: {
			required: 'Campo Obligatorio'
	         },
	         "select-favorite-destination[]": {
			required: 'Campo Obligatorio'
	         },
		 cp: {
		 	number: 'Sólo Números'
		 },
		 lada: {
		 	mxPhoneOpt: 'Formato Inválido'
		 },
		 cel: {
		 	mxPhoneToll: 'Formato Inválido'
		 }
	    },
	    rules: {
	         nombre: {
			required: true
	         },
	         mail: {
			required: true,
			email: true
	         },
	         sexo: {
			required: true
	         },
	         dia: {
			birthday: true
	         },
	         'new_pass': {
			required: true,
			minlength: 8
	         },
	         'confirm_pass': {
			required: true,
			equalTo: '#input-change-password'
	         },
	         pais: {
			required: true
	         },
	         estado: {
			required: true
	         },
	         ciudad: {
			required: true
	         },
	         presentacion: {
			required: true
	         },
	         "select-favorite-destination[]": {
			required: true
	         },
		 cp: {
		 	number: true
		 },
		 lada: {
		 	mxPhoneOpt: true
		 },
		 cel: {
		 	mxPhoneToll: true
		 }
	    }, submitHandler: function(){
            	$j("#form-edit-user-profile").ajaxSubmit({
            		beforeSubmit: showRequestEditRegistro, // pre-submit callback 
            		success: showResponseEditRegistro // post-submit callback
	    	});
	    }
	});
	$j('#select-day-user, #select-month-user, #input-year-user').bind('focusin', validateBirthday); 
	$j('#select-day-user, #select-month-user, #input-year-user').bind('focusout', validateBirthday); 
	$j('#select-day-user, #select-month-user, #input-year-user').bind('click', validateBirthday); 
	$j('#select-day-user, #select-month-user, #input-year-user').bind('change', validateBirthday); 
	$j('#select-day-user, #select-month-user, #input-year-user').bind('keydown', validateBirthday); 
	$j('#select-day-user, #select-month-user, #input-year-user').bind('keyup', validateBirthday); 
	$j('#input-lada-user, #input-telephone-user').bind('focusin', validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('focusout',validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('click',   validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('change',  validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('keydown', validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('keyup',   validatePhone); 
	$j('#input-celular-user').bind('focusin', validateCel); 
	$j('#input-celular-user').bind('focusout',validateCel); 
	$j('#input-celular-user').bind('click',   validateCel); 
	$j('#input-celular-user').bind('change',  validateCel); 
	$j('#input-celular-user').bind('keydown', validateCel); 
	$j('#input-celular-user').bind('keyup',   validateCel); 

	//remove error from view
	$j('label.error[for=select-day-user]').hide();
}
function showRequestEditRegistro(formData, jqForm, options) {
	$j('#loading-img').remove();
	$j('#button-submit-user').after($j('<img id="loading-img" src="assets/images/ajax-loader.gif" />'));
	$j('button, select, input', $j('#form-edit-user-profile')).attr('disabled', 'disabled');
}

function showResponseEditRegistro(responseText, statusText, xhr, $form) {
	$j('#loading-img').remove();
	$j('button, select, input', $j('#form-edit-user-profile')).removeAttr('disabled');
	activeChangePass();
	if(responseText == '1') {
		//successfully saved data
		$j('#button-submit-user').after($j('<div id="loading-img" class="text-note-funcs" style="color: #ff6600" />'));
		$j('#loading-img').text('Sus datos han sido guardados con éxito.');
	} else {
		$j('#button-submit-user').after($j('<div id="loading-img" class="text-note-funcs" style="color: #ff6600" />'));
		$j('#loading-img').html('Existe algún error en su forma. Por favor llénela nuevamente<br />Error número ' + 
			responseText );
	}
}

function validateBirthday() {
	$j().validate().element('#select-day-user');
}
function validateCel() {
	$j().validate().element('#input-celular-user');
}

//Userprofile callback 
function showRequestProfile(formData, jqForm, options){
	$j('#button-submit-user').hide();
}

// post-submit callback 
function showResponseProfile(responseText, statusText){
	$j('#button-submit-user').show();
}

/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Funcion para Tabs vip:::::::::::::::::::::::::::::::::::*/
function vipTabs() {
	$j("#wrapper-vip-recomendation").tabs(".vip-recomendation-text", {
		tabs: ".vip-reco-button", 
		effect: "horizontal",
		onClick: function() { 
			if($j("#vip0:has(a)").length == 0){
				$j("#vip0 img").remove();
				$j("#vip0").prepend('<a href="#">spa\'s</a>');
			}
			if($j("#vip1:has(a)").length == 0){
				$j("#vip1 img").remove();
				$j("#vip1").prepend('<a href="#">hospedaje</a>');
			}
			if($j("#vip2:has(a)").length == 0){
				$j("#vip2 img").remove();
				$j("#vip2").prepend('<a href="#">gastronomía</a>');
			}
			if($j("#vip3:has(a)").length == 0){
				$j("#vip3 img").remove();
				$j("#vip3").prepend('<a href="#">actividades</a>');
			}
			this.getCurrentTab().children("a").remove();
			var currentIma = this.getCurrentTab().children("input:hidden").val();
        	this.getCurrentTab().prepend('<img src="'+currentIma+'" alt="" />'); 
   		} 
	});	
}
/*::::::::::::::::::::::::::::::::::::::Ciertas Validaciones::::::::::::::::::::::::::::::::::::::::::::::::*/
function mxPhone(value, method) {
	return /^[-+()0-9 ]{5,}$/.test($j('#input-telephone-user').val()) &&
                        /^[-+()0-9 ]{1,}$/.test($j('#input-lada-user').val());
}

function mxPhoneToll(value, method) {
	return /^[-+()0-9 ]*$/.test(value);
}

function mxPhoneOpt(value, method) {
	return /^[-+()0-9 ]*$/.test($j('#input-telephone-user').val()) &&
		/^[-+()0-9 ]*$/.test($j('#input-lada-user').val());
}

function mxFaxOpt(value, method) {
	return /^[-+()0-9 ]*$/.test($j('#input-telephone-fax').val()) &&
		/^[-+()0-9 ]*$/.test($j('#input-lada-fax').val());
}

function tagRequired(value, method) {
	b=false;
	$j('input[type=checkbox]', '#wrapper-category-tags').each(function() {
		b = b || ($j(this).attr('checked'))? true : false;
		if(b) return; // great efficiency due to this :-D
		//but could be better. Validation by @phil_websurfer
	});

	return b;
}
/*::::::::::::::::::::::::::::::::::::::Valida Datos Anunciante 1::::::::::::::::::::::::::::::::::::::::::::::::*/
function validaAnunciante1() {
	getUserMainHeight();
	$j('label.error').hide();
	$j.validator.addMethod('mxPhone', mxPhone, 'Campo Obligatorio');
	$j('#form-advertiser1').validate({
	    messages: {
	        nombre: {
		       required: 'Campo Obligatorio'
	        },
		nombreusuario: {
		       required: 'Campo Obligatorio',
		       remote: 'Usuario ya existente'
		},
		apellidos: {
		       required: 'Campo Obligatorio'
		},
	        mail: {
		       required: 'Campo Obligatorio',
		       email: 'E-Mail Inválido'
	        },
	        'new_pass': {
		       required: 'Campo Obligatorio',
		       minlength: 'Mín. 8 caracteres'
	        },
	        'confirm_pass': {
		       required: 'Campo Obligatorio',
		       equalTo: 'Passwords no coinciden'
	        },
	        lada: {
			mxPhone: 'Campo Obligatorio'
	        },
	        ext: {
		       number: 'Sólo números'
	        },
	        cel: {
	        }
	    },
	    rules: {
	        nombre: {
		       required: true
	        },
		nombreusuario: {
		       required: true,
		       remote: {
				type: 'post',
				url: 'procesa-busername_check'
			}
		},
		apellidos: {
		       required: true
		},
	        mail: {
		       required: true,
		       email: true
	        },
	        'new_pass': {
//		       required: true,
		       minlength: 8
	        },
	        'confirm_pass': {
//		       required: true,
		       equalTo: '#input-change-password'
	        },
	        lada: {
		       mxPhone: true
	        },
	        tel: {
	        },
	        ext: {
			number: true
	        },
	        cel: {
	        }
	    },
	    submitHandler: function(){
            	$j("#form-advertiser1").ajaxSubmit({
            		beforeSubmit: showRequestContacto, // pre-submit callback 
            		success: showResponseContacto // post-submit callback
	    	});
	    }
	});
	$j('#input-lada-user, #input-telephone-user').bind('focusin', validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('focusout',validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('click',   validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('change',  validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('keydown', validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('keyup',   validatePhone); 
}

function validatePhone() {
	$j().validate().element('#input-lada-user');
}

function showRequestContacto(formData, jqForm, options){
	$j('#loading-img').remove();
	$j('#button-submit-user').after($j('<img id="loading-img" src="assets/images/ajax-loader.gif" />'));
	$j('button, select, input', $j('#form-register-user')).attr('disabled', 'disabled');
}

// post-submit callback 
function showResponseContacto(responseText, statusText){
	$j('#loading-img').remove();
	if(responseText == '1') {
		go2editContact();
	} else {
		$j('button, select, input', $j('#form-register-user')).removeAttr('disabled');
		$j('#button-submit-user').after($j('<div id="loading-img" class="text-note-funcs" style="color: #ff6600" />'));
		$j('#loading-img').text(responseText);
	}
}


/*::::::::::::::::::::::::::::::::::::::Valida Datos de los negocios::::::::::::::::::::::::::::::::::::::::::::::::*/
function validaAnunciante2() {
	getUserMainHeight();
	$j('label.error').hide();
	$j.validator.addMethod('mxPhoneToll', mxPhoneToll, 'Formato Inválido');
	$j.validator.addMethod('mxPhoneOpt', mxPhoneOpt, 'Formato Inválido');
	$j.validator.addMethod('mxFaxOpt', mxFaxOpt, 'Formato Inválido');
	$j.validator.addMethod('tagRequired', tagRequired, 'Campo Obligatorio');
	//Valida datos del formulario para editar el negocio
	$j('#form-advertiser2').validate({
	    messages: {
	        nombre: {
		       required: 'Campo Obligatorio'
	        },
		street: {
			required: 'Campo Obligatorio'
		},
		streetnum: {
			required: 'Campo Obligatorio'
		},
		colonia: {
			required: 'Campo Obligatorio'
		},
		ciudad: {
			required: 'Campo Obligatorio'
		},
		estado: {
			required: 'Campo Obligatorio'
		},
		zipcode: {
			required: 'Campo Obligatorio',
			minlength: 'Campo Obligatorio',
			number: 'Únicamente números'
		},
		role1: {
			required: 'Campo Obligatorio'
		},
		lada: {
			mxPhoneOpt: 'Formato Inválido'
		},
		ladafax: {
			mxFaxOpt: 'Formato Inválido'
		},
		ext: {
			mxPhoneToll: 'Formato Inválido'
		},
		'[+tag+]': {
			tagRequired: 'Campo Obligatorio'
		},
		promembership: {
			required: 'Campo Obligatorio'
		}
	    },
	    rules: {
	        nombre: {
		       required: true
	        },
		street: {
			required: true
		},
		streetnum: {
			required: true
		},
		colonia: {
			required: true
		},
		ciudad: {
			required: true
		},
		estado: {
			required: true
		},
		zipcode: {
			required: true,
			number: true,
			minlength: 4
		},
		role1: {
			required: true
		},
		lada: {
			mxPhoneOpt: true
		},
		ladafax: {
			mxFaxOpt: true
		},
		ext: {
			mxPhoneToll: true
		},
		'[+tag+]': {
			tagRequired: 'Campo Obligatorio'
		},
		promembership: {
			required: true
		}
	    },
	    submitHandler: function() {
            	$j("#form-advertiser2").ajaxSubmit({
            		beforeSubmit: requestEditBiz, // pre-submit callback 
            		success: responseEditBiz // post-submit callback
	    	});
	    }
	});
	
	//Valida formulario de registro de negocio
	$j('#reg-nuevo-negocio').validate({
	    messages: {
	        nombre: {
		       required: 'Campo Obligatorio'
	        },
			street: {
				required: 'Campo Obligatorio'
			},
			colonia: {
				required: 'Campo Obligatorio'
			},
			ciudad: {
				required: 'Campo Obligatorio'
			},
			estado: {
				required: 'Campo Obligatorio'
			},
			zipcode: {
				required: 'Campo Obligatorio',
				minlength: 'Campo Obligatorio',
				number: 'Únicamente números'
			},
			giro: {
				required: 'Campo Obligatorio'
			},
			lada: {
				mxPhoneOpt: 'Formato Inválido'
			},
			ladafax: {
				mxFaxOpt: 'Formato Inválido'
			},
			ext: {
				mxPhoneToll: 'Formato Inválido'
			},
			'[+tag+]': {
				tagRequired: 'Campo Obligatorio'
			},
			promembership: {
				required: 'Campo Obligatorio'
			}
	    },
	    rules: {
	        nombre: {
		       required: true
	        },
			street: {
				required: true
			},
			streetnum: {
				required: true
			},
			colonia: {
				required: true
			},
			ciudad: {
				required: true
			},
			estado: {
				required: true
			},
			zipcode: {
				required: true,
				number: true,
				minlength: 4
			},
			giro: {
				required: true
			},
			lada: {
				mxPhoneOpt: true
			},
			ladafax: {
				mxFaxOpt: true
			},
			ext: {
				mxPhoneToll: true
			},
			'[+tag+]': {
				tagRequired: 'Campo Obligatorio'
			},
			promembership: {
				required: true
			}
	    },
	    submitHandler: function() {
            	$j("#reg-nuevo-negocio").ajaxSubmit({
					resetForm: true,
            		beforeSubmit: requestEditBiz, // pre-submit callback 
            		success: responseNewBiz // post-submit callback
	    	});
	    }
	});
	
	
	$j('#input-lada-user, #input-telephone-user').bind('focusin', validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('focusout',validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('click',   validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('change',  validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('keydown', validatePhone); 
	$j('#input-lada-user, #input-telephone-user').bind('keyup',   validatePhone); 
	$j('#input-lada-fax, #input-telephone-fax').bind('focusin', validateFax); 
	$j('#input-lada-fax, #input-telephone-fax').bind('focusout',validateFax); 
	$j('#input-lada-fax, #input-telephone-fax').bind('click',   validateFax); 
	$j('#input-lada-fax, #input-telephone-fax').bind('change',  validateFax); 
	$j('#input-lada-fax, #input-telephone-fax').bind('keydown', validateFax); 
	$j('#input-lada-fax, #input-telephone-fax').bind('keyup',   validateFax); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('focusin', validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('focusout',validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('click',   validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('change',  validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('keydown', validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('keyup',   validateTags); 

        $j("#wrapper-category-tags").tabs(".wrapper-tags-options", {tabs:".tag-tab", current:"current-tag-cat"});
}

function requestEditBiz(formData, jqForm, options) {
	$j('#loading-img').remove();
	$j('#button-submit-user').after('<div id="loading-img" class="text-normal2" style="color: #ff6600"><img src="assets/images/ajax-loader.gif" /> Enviando información</div>');
	$j('button, select, input', $j('#form-edit-user-profile')).attr('disabled', 'disabled');
}

//Maneja la respuesta de la forma para editar
function responseEditBiz(responseText, statusText, xhr, $form) {
	$j('button, select, input', $j('#form-edit-user-profile')).removeAttr('disabled');
	$j('#loading-img').html(responseText );
}

//Manage la respuesta de la forma para registar un nuevo negocio
function responseNewBiz(responseText, statusText, xhr, $form) {
	$j('#loading-img').remove();
	$j('button, select, input', $j('#form-edit-user-profile')).removeAttr('disabled');
	if(responseText == "exito") {
		//successfully saved data
		$j('#button-submit-user').after($j('<div id="loading-img" class="text-normal2" style="color: #ff6600" />'));
		$j('#loading-img').html('El negocio se ha guardado con éxito.<br/> Si quieres registrar otro negocio sólo vuelve a llenar los campos y haz clic en GUARDAR CAMBIOS.<br/>Para ver tus negocios haz clic <span  class="text-normal1"><a href="mis_negocios.html">AQUÍ</a></span>');
		if(typeof go2biz == 'function') {
			go2biz(responseText);
		}
	} else {
		$j('#button-submit-user').after($j('<div id="loading-img" class="text-note-funcs" style="color: #ff6600" />'));
		$j('#loading-img').html('Existe algún error en su forma. Por favor llénela nuevamente<br />Error número ' + 
			responseText );
	}
}

function validateFax() {
	$j().validate().element('#input-lada-fax');
}

function validateTags() {
	$j().validate().element('input[name=\\[\\+tag\\+\\]]');
}

//Hace el cambio de opciones en los select y la visiblidiad de esto dependiendo del giro seleccionado.
function changeNegProps(){
	var hotelGiro = new Array('1');
	var restGiro = new Array('2', '3', '4', '5', '6', '7');
	var barGiro = new Array('8', '9', '10', '11');
	var actGiro = new Array('12');	
	var giroActual = $j("#input-advertiser-role1 option:selected").val();
	var found = -1;
	
	for(var hg = 0; hg < hotelGiro.length; hg++){
		if(hotelGiro[hg] == giroActual){
			found = "hotel";	
		}
	}
	for(var rg = 0; rg < restGiro.length; rg++){
		if(restGiro[rg] == giroActual){
			found = "rest";	
		}
	}
	for(var bg = 0; bg < barGiro.length; bg++){
		if(barGiro[bg] == giroActual){
			found = "bar";	
		}
	}
	for(var ag = 0; ag < actGiro.length; ag++){
		if(actGiro[ag] == giroActual){
			found = "act";	
		}
	}
	
	switch(found){
		case "hotel":
			$j("#dynamic-label").css({display:"inline"});
			$j("#dynamic-label").html("* Categoría");
			$j("#input-advertiser-role3").css({display:"inline"});
			$j("#input-advertiser-role3").html(hotelOptions);
			$j("#wrapper-prices").css({display:"none"});
            $j("#select-advertiser-prices").removeClass("valid");
		break;
		case "rest":
			$j("#dynamic-label").css({display:"inline"});
			$j("#dynamic-label").html("* Tipo de comida");
			$j("#input-advertiser-role3").css({display:"inline"});
			$j("#input-advertiser-role3").html(restOptions);
			$j("#wrapper-prices").css({display:"inline"});
            $j("#select-advertiser-prices").addClass("valid");
		break;
		case "bar":
			$j("#dynamic-label").css({display:"inline"});
			$j("#dynamic-label").html("* Tipo de música");
			$j("#input-advertiser-role3").css({display:"inline"});
			$j("#input-advertiser-role3").html(barOptions);
			$j("#wrapper-prices").css({display:"inline"});
            $j("#select-advertiser-prices").removeClass("valid");
		break;
		default:
			$j("#dynamic-label").css({display:"none"});
			$j("#input-advertiser-role3").css({display:"none"});
			$j("#input-advertiser-role2").css({display:"none"});
			$j("#wrapper-prices").css({display:"none"});
            $j("#select-advertiser-prices").removeClass("valid");
		break;	
	}
}

//Muestra o esconde el mensaje en caso de seleccioanr una memebresía pagada
function showPaidMsg(){
	if($j("#mem-paid").attr("checked") == true){
		$j("#paid-info").css({display:"block"});	
	} else {
		$j("#paid-info").css({display:"none"});	
	}
}
/*::::::::::::::::::::::::::::::::::::::Valida User Ask::::::::::::::::::::::::::::::::::::::::::::::::*/
function validaUserAsk() {
    $j('label.error').hide();
	$j.validator.addMethod('tagRequired',tagRequired, 'Campo Obligatorio');
	$j('#form-user-ask').validate({
	    messages: {
	        pregunta: {
		       required: 'Campo Obligatorio'
	        },
		'[+tag+]': {
			tagRequired: 'Campo Obligatorio'
		}
	    },
	    rules: {
	        pregunta: {
		       required: true
	        },
		'[+tag+]': {
			tagRequired: 'Campo Obligatorio'
		}
	    },
	    submitHandler: function() {
            	$j("#form-user-ask").ajaxSubmit({
            		beforeSubmit: showRequestQuestion, // pre-submit callback 
            		success: showResponseQuestion // post-submit callback
	    	});
	    }
	});
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('focusin', validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('focusout',validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('click',   validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('change',  validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('keydown', validateTags); 
	$j('#input[type=checkbox]', '#wrapper-category-tags').bind('keyup',   validateTags); 
}

function showRequestQuestion(formData, jqForm, options) {
        $j('#loading-img').remove();
        $j('#button-submit-user').after($j('<img id="loading-img" src="assets/images/ajax-loader.gif" />'));
        $j('button, select, input', $j('#form-user-ask')).attr('disabled', 'disabled');
}

function showResponseQuestion(responseText, statusText, xhr, $form) {
        $j('#loading-img').remove();
        $j('button, select, input', $j('#form-user-ask')).removeAttr('disabled');
        //activeChangePass();
        if(responseText.charAt(0) == '2') {
                //successfully saved data
                $j('#button-submit-user').after($j('<div id="loading-img" class="text-note-funcs" style="color: #ff6600" />'));
                $j('#loading-img').text('Sus datos han sido guardados con éxito.');
		window.location.href = responseText.substring(2); 
        } else {
                $j('#button-submit-user').after($j('<div id="loading-img" class="text-note-funcs" style="color: #ff6600" />'));
                $j('#loading-img').html('Existe algún error en su forma. Por favor llénela nuevamente<br />Error número ' +
                        responseText );
        }
}
/*::::::::::::::::::::::::::::::::::::::Valida User New Album::::::::::::::::::::::::::::::::::::::::::::::::*/
function validaUserNewAlbum() {
    $j('label.error').hide();
	$j('#form-user-ask').validate({
	    messages: {
	        album_nom: {
		       required: 'Campo Obligatorio'
	        }
	    },
	    rules: {
	        album_nom: {
		       required: true
	        }
	    }
	});
	//$j('#wrapper-category-tags input:checkbox').bind('change',  validaTags); 
	$j("#button-submit-user").bind('click', validaTags);
}

function validaTags(){
	$j('#form-user-ask').submit(function(){
		if($j('#wrapper-category-tags input:checked').length > 0){
			$j("#tag-error").hide();
			return true;
		} else {
			$j("#tag-error").show();
			return false;
		}
	});
}

/******************** Seccion de Preguntas y Respuestas *************************************/
//::::::::::::::::::::::::::::::::::::::::::Expose de la forma de respuesta::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
	function showAnswerForm(){
     	$j("a[rel='responder']").overlay({
			target:"#responder-preg", 
			close:".close-expose",
			closeOnClick: true,
			expose: '#000',
			top: 'center',
			onBeforeLoad: function(){
				var getPregid = this.getTrigger().attr("name");
				var pregid = getPregid.substring(3);
				$j("#resp-preid").attr({value:pregid});
				$j('body').append(jQuery('<div id="overlay-background"></div>'));
				$j('#overlay-background').fadeIn();
			},
			onClose: function(){
				$j('#responder-preg').fadeOut();
				$j('#overlay-background').fadeOut();
			}
		});
	}
//Valida la forma de respuesta
function validaRespuesta() {
	$j('#responder').validate({
	    messages: {
	        respuesta: {
		       required: 'Campo Obligatorio'
	        }
	    },
	    rules: {
	        respuesta: {
		       required: true
	        }
	    },
	    submitHandler: function() {
            	$j("#responder").ajaxSubmit({
					resetForm: true,
            		beforeSubmit: showRequestAnswer, // pre-submit callback 
            		success: showResponseAnswer // post-submit callback
	    	});
	    }
	});
}

function showRequestAnswer(formData, jqForm, options) {
        $j('.expose-mensajes').html('Enviando información');
        $j('button, select, input', $j('#form-user-ask')).attr('disabled', 'disabled');
}

function showResponseAnswer(responseText, statusText, xhr, $form) {
		var pregid = $j("#resp-preid").val();
        if(responseText.charAt(0) == '2') {
            //successfully saved data
            //window.location.href("pregunta.html?preid="+pregid);
			window.location.href = responseText.substring(2); 
        } else {
        	$j('.expose-mensajes').html('Existe algún error en su forma. Por favor llénela nuevamente<br />Error número ' + responseText );
        }
}


/*************************************************************************************
 *******************MD5/SHA Library integrated to this file to reduce*****************
 *******************HTTP Requests, used in all Login Authentication*******************
 ************************************************************************************/
/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
 * in FIPS 180-1
 * Version 2.2 Copyright Paul Johnston 2000 - 2009.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Modified and minified by Jorge III Altamirano Astorga
 * using Google Closure Compiler
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_sha1(s)    { return rstr2hex(rstr_sha1(str2rstr_utf8(s))); }
function b64_sha1(s)    { return rstr2b64(rstr_sha1(str2rstr_utf8(s))); }
function any_sha1(s, e) { return rstr2any(rstr_sha1(str2rstr_utf8(s)), e); }
function hex_hmac_sha1(k, d)
  { return rstr2hex(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
function b64_hmac_sha1(k, d)
  { return rstr2b64(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
function any_hmac_sha1(k, d, e)
  { return rstr2any(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d)), e); }

function sha1_vm_test(){return hex_sha1("abc").toLowerCase()=="a9993e364706816aba3e25717850c26c9cd0d89d"}function rstr_sha1(b){return binb2rstr(binb_sha1(rstr2binb(b),b.length*8))}function rstr_hmac_sha1(b,d){var a=rstr2binb(b);if(a.length>16)a=binb_sha1(a,b.length*8);for(var c=Array(16),e=Array(16),f=0;f<16;f++){c[f]=a[f]^909522486;e[f]=a[f]^1549556828}a=binb_sha1(c.concat(rstr2binb(d)),512+d.length*8);return binb2rstr(binb_sha1(e.concat(a),672))}
function rstr2hex(b){for(var d=hexcase?"0123456789ABCDEF":"0123456789abcdef",a="",c,e=0;e<b.length;e++){c=b.charCodeAt(e);a+=d.charAt(c>>>4&15)+d.charAt(c&15)}return a}function rstr2b64(b){for(var d="",a=b.length,c=0;c<a;c+=3)for(var e=b.charCodeAt(c)<<16|(c+1<a?b.charCodeAt(c+1)<<8:0)|(c+2<a?b.charCodeAt(c+2):0),f=0;f<4;f++)d+=c*8+f*6>b.length*8?b64pad:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e>>>6*(3-f)&63);return d}
function rstr2any(b,d){var a=d.length,c=Array(),e,f,g,h,j=Array(Math.ceil(b.length/2));for(e=0;e<j.length;e++)j[e]=b.charCodeAt(e*2)<<8|b.charCodeAt(e*2+1);for(;j.length>0;){h=Array();for(e=g=0;e<j.length;e++){g=(g<<16)+j[e];f=Math.floor(g/a);g-=f*a;if(h.length>0||f>0)h[h.length]=f}c[c.length]=g;j=h}a="";for(e=c.length-1;e>=0;e--)a+=d.charAt(c[e]);c=Math.ceil(b.length*8/(Math.log(d.length)/Math.log(2)));for(e=a.length;e<c;e++)a=d[0]+a;return a}
function str2rstr_utf8(b){for(var d="",a=-1,c,e;++a<b.length;){c=b.charCodeAt(a);e=a+1<b.length?b.charCodeAt(a+1):0;if(55296<=c&&c<=56319&&56320<=e&&e<=57343){c=65536+((c&1023)<<10)+(e&1023);a++}if(c<=127)d+=String.fromCharCode(c);else if(c<=2047)d+=String.fromCharCode(192|c>>>6&31,128|c&63);else if(c<=65535)d+=String.fromCharCode(224|c>>>12&15,128|c>>>6&63,128|c&63);else if(c<=2097151)d+=String.fromCharCode(240|c>>>18&7,128|c>>>12&63,128|c>>>6&63,128|c&63)}return d}
function str2rstr_utf16le(b){for(var d="",a=0;a<b.length;a++)d+=String.fromCharCode(b.charCodeAt(a)&255,b.charCodeAt(a)>>>8&255);return d}function str2rstr_utf16be(b){for(var d="",a=0;a<b.length;a++)d+=String.fromCharCode(b.charCodeAt(a)>>>8&255,b.charCodeAt(a)&255);return d}function rstr2binb(b){for(var d=Array(b.length>>2),a=0;a<d.length;a++)d[a]=0;for(a=0;a<b.length*8;a+=8)d[a>>5]|=(b.charCodeAt(a/8)&255)<<24-a%32;return d}
function binb2rstr(b){for(var d="",a=0;a<b.length*32;a+=8)d+=String.fromCharCode(b[a>>5]>>>24-a%32&255);return d}
function binb_sha1(b,d){b[d>>5]|=128<<24-d%32;b[(d+64>>9<<4)+15]=d;for(var a=Array(80),c=1732584193,e=-271733879,f=-1732584194,g=271733878,h=-1009589776,j=0;j<b.length;j+=16){for(var k=c,l=e,m=f,n=g,o=h,i=0;i<80;i++){a[i]=i<16?b[j+i]:bit_rol(a[i-3]^a[i-8]^a[i-14]^a[i-16],1);var p=safe_add(safe_add(bit_rol(c,5),sha1_ft(i,e,f,g)),safe_add(safe_add(h,a[i]),sha1_kt(i)));h=g;g=f;f=bit_rol(e,30);e=c;c=p}c=safe_add(c,k);e=safe_add(e,l);f=safe_add(f,m);g=safe_add(g,n);h=safe_add(h,o)}return Array(c,e,f,g,
h)}function sha1_ft(b,d,a,c){if(b<20)return d&a|~d&c;if(b<40)return d^a^c;if(b<60)return d&a|d&c|a&c;return d^a^c}function sha1_kt(b){return b<20?1518500249:b<40?1859775393:b<60?-1894007588:-899497514}function safe_add(b,d){var a=(b&65535)+(d&65535);return(b>>16)+(d>>16)+(a>>16)<<16|a&65535}function bit_rol(b,d){return b<<d|b>>>32-d};


//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Function para enviar comentarios:::::::::::::::::::::::::::::::::::::::::::::::
function sendComments(){
	$j("#comentar-form").ajaxForm({
    	type: "POST",
        url: "assets/php/insertComment.php",
		async:true,
        resetForm: true,
        beforeSubmit: function(){
        	$j(".expose-mensajes").html('<img src="../images/ajax-loader.gif"/> enviando informacion');
        },
        success: function(respuesta){
            if(respuesta=="exito"){
				var getUrl = location.href;
                var comment = getUrl.indexOf("#comentar");
                if(comment != -1){
					location.href = location.href.replace("#comentar", '');	
				} else {
            		window.location.reload();
				}
            } else {
			    $j(".expose-mensajes").html(respuesta);
            }
		 }
     });	
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Ajax para obtener las opcione sde filtrado
function getOptions(){
	showFilter();
	$j(".filter-options").html("");
	$j(".filter-type").html(""); 
	$j("#filter-message").html("");
	var index = $j("#giro_actual").val();
	var precioOps = '<li><input type="checkbox" name="prop-filter[]" value="menos de 150" /><label class="text-filter-option">Menos de $150</label></li><li><input type="checkbox" name="prop-filter[]" value="150 - 250" /><label class="text-filter-option">De $150 a $250</label></li><li><input type="checkbox" name="prop-filter[]" value="250 - 350" /><label class="text-filter-option">De $250 a $350</label></li><li><input type="checkbox" name="prop-filter[]" value="350 - 500" /><label class="text-filter-option">De $350 a $500</label></li><li><input type="checkbox" name="prop-filter[]" value="más de 500" /><label class="text-filter-option">Más de $500</label></li>';
	if(index == 1 || index == 3){
		if(index == 1){
			var opLabel = "tipo de comida";
		} else {
			var opLabel = "tipo de música";
		}
		var filterType = '<input type="radio" name="tipo_bus" value="prop" /><label class="text-filter-type">Por '+opLabel+'</label><input type="radio" name="tipo_bus" value="precio" /><label class="text-filter-type">Por precio</label>';
		$j(".filter-type").html(filterType);
		$j(":radio[name='tipo_bus']").click(function(){
			if($j(this).val()=="precio"){
				$j(".filter-options").html(precioOps); 
				$j("#tipo-filtro").val("precio");
			} else {
				$j("#tipo-filtro").val("prop");
				callOps(index);	
			}
		});
	} else if(index == 2){
		$j(".filter-options").html(precioOps); 
		$j("#tipo-filtro").val("precio");
	} else {
		$j("#tipo-filtro").val("prop");
		callOps(index);
	}
}
//Envio del filtrado

function validateFiltro(){
	if($j("#filter-ops input:checked").length < 1){
		$j("#filter-message").html("Al menos debes seleccionar una opción");
		return false;
	} else {
		$j("#filter-message").html("Enviando Información...");
		return true;	
	}
}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Cambia el tipo de negocio en el select del directorio de servicios
function changeNegTipo(){
	var prices = '<option value="">Selecciona</option><option value="menos de 150">Menos de $150</option><option value="150 - 250">De $150 a $250</option><option value="250 - 350" >De $250 a $350</option><option value="350 - 500" >De $350 a $500</option><option value="más de 500" >Más de $500</option>';
	var hotelGiro = new Array('1');
	var restGiro = new Array('2', '3', '4', '5', '6', '7');
	var barGiro = new Array('8', '9', '10', '11');
	var actGiro = new Array('12');	
	var giroActual = $j("#directory-giros option:selected").val();
	var found = -1;
	
	for(var hg = 0; hg < hotelGiro.length; hg++){
		if(hotelGiro[hg] == giroActual){
			found = "hotel";	
		}
	}
	for(var rg = 0; rg < restGiro.length; rg++){
		if(restGiro[rg] == giroActual){
			found = "rest";	
		}
	}
	for(var bg = 0; bg < barGiro.length; bg++){
		if(barGiro[bg] == giroActual){
			found = "bar";	
		}
	}
	for(var ag = 0; ag < actGiro.length; ag++){
		if(actGiro[ag] == giroActual){
			found = "act";	
		}
	}
	
	switch(found){
		case "hotel":
			$j("#directory-props").html(hotelOptions);
		break;
		case "rest":
			$j("#directory-props").html(restOptions);
		break;
		case "bar":
			$j("#directory-props").html(barOptions);
		break;
		case "act":
			$j("#directory-props").html(prices);
		break;
		default:
			$j("#directory-props").html('');
		break;	
	}
}

/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Scrolable para la paginación:::::::::*/
function scrollPagesSearch(currentDocs, currentDest, currentPost){
	//Paginación de artículos
	//Define el index del documento actual
	var indexDocs = currentDocs -1;
	$j("#pags-articulos .wrapper-pages-num").scrollable({
		next:".search-button-fwd", 
		prev:".search-button-back",
		disabledClass: "pag-disabled"
	});
	var apiDocs = $j("#pags-articulos .wrapper-pages-num").data("scrollable");
	//Mueve el scroll al index actual
	apiDocs.seekTo(indexDocs);
	//Obtiene el número de páginas en el scroll
	var docPagSize = apiDocs.getSize();
	//Obtiene el número en donde desaparece el link a la última página
	var docLastLimit = docPagSize - 7;
	//Obtiene el índice actua en el que está el scroll
	var scrollIndex = apiDocs.getIndex();
	//Comprueba la posición del scroll para mostrar u ocultar el link a la última página
	if(scrollIndex >= docLastLimit && scrollIndex <= docPagSize){
		$j("#pags-articulos .total-pags").css({display:"none"});	
	} else {
		$j("#pags-articulos .total-pags").css({display:"inline"});	
	}
	//Comprueba la posición del scroll para ocultar o mostrar el link a la primera página
	if(scrollIndex >= 5){
		$j("#pags-articulos .inicio-pags").css({display:"inline"});	
	} else {
		$j("#pags-articulos .inicio-pags").css({display:"none"});	
	}
	//Genera la función para avanzar más de un documento a la vez comprabar el índice
	$j("#pags-articulos .search-button-fwd").click(function(){
		apiDocs.move(4);
		var newIndex = apiDocs.getIndex();
		if(newIndex >= docLastLimit && newIndex <= docPagSize){
			$j("#pags-articulos .total-pags").css({display:"none"});	
		} else {
			$j("#pags-articulos .total-pags").css({display:"inline"});	
		}
		if(newIndex >= 5){
			$j("#pags-articulos .inicio-pags").css({display:"inline"});	
		} else {
			$j("#pags-articulos .inicio-pags").css({display:"none"});	
		}
	});
	//Genera la función para retoceder más de un documento a la vez comprabar el índice
	$j("#pags-articulos .search-button-back").click(function(){
		apiDocs.move(-4);
		var newIndex = apiDocs.getIndex();
		if(newIndex < docLastLimit){
			$j("#pags-articulos .total-pags").css({display:"inline"});	
		} else {
			$j("#pags-articulos .total-pags").css({display:"none"});	
		}
		if(newIndex >= 5){
			$j("#pags-articulos .inicio-pags").css({display:"inline"});	
		} else {
			$j("#pags-articulos .inicio-pags").css({display:"none"});	
		}
	});
	//Paginación de destinos
	var indexDest = currentDest -1;
	$j("#pags-destinos .wrapper-pages-num").scrollable({
		next:".search-button-fwd", 
		prev:".search-button-back",
		disabledClass: "pag-disabled"
	});
	var apiDest = $j("#pags-destinos .wrapper-pages-num").data("scrollable");
	apiDest.seekTo(indexDest);
	var destPagSize = apiDest.getSize();
	var destLastLimit = destPagSize - 7;
	var scrollIndexDest = apiDest.getIndex();
	if(scrollIndexDest >= destLastLimit && scrollIndexDest <= destPagSize){
		$j("#pags-destinos .total-pags").css({display:"none"});	
	} else {
		$j("#pags-destinos .total-pags").css({display:"inline"});	
	}
	if(scrollIndexDest >= 5){
		$j("#pags-destinos .inicio-pags").css({display:"inline"});	
	} else {
		$j("#pags-destinos .inicio-pags").css({display:"none"});	
	}
	$j("#pags-destinos .search-button-fwd").click(function(){
		apiDest.move(4);
		var newIndexDest = apiDest.getIndex();
		if(newIndexDest >= destLastLimit && newIndexDest <= destPagSize){
			$j("#pags-destinos .total-pags").css({display:"none"});	
		} else {
			$j("#pags-destinos .total-pags").css({display:"inline"});	
		}
		if(newIndexDest >= 5){
			$j("#pags-destinos .inicio-pags").css({display:"inline"});	
		} else {
			$j("#pags-destinos .inicio-pags").css({display:"none"});	
		}
	});
	$j("#pags-destinos .search-button-back").click(function(){
		apiDest.move(-4);
		var newIndexDest = apiDest.getIndex();
		if(newIndexDest < destLastLimit){
			$j("#pags-destinos .total-pags").css({display:"inline"});	
		} else {
			$j("#pags-destinos .total-pags").css({display:"none"});	
		}
		if(newIndexDest >= 5){
			$j("#pags-destinos .inicio-pags").css({display:"inline"});	
		} else {
			$j("#pags-destinos .inicio-pags").css({display:"none"});	
		}
	});
	//Paginación de posts
	var indexPost = currentPost -1;
	$j("#pags-posts .wrapper-pages-num").scrollable({
		next:".search-button-fwd", 
		prev:".search-button-back",
		disabledClass: "pag-disabled"
	});
	var apiPost = $j("#pags-posts .wrapper-pages-num").data("scrollable");
	apiPost.seekTo(indexPost);
	var postPagSize = apiPost.getSize();
	var postLastLimit = postPagSize - 7;
	var scrollIndexPost = apiPost.getIndex();
	if(scrollIndexPost >= postLastLimit && scrollIndexPost <= postPagSize){
		$j("#pags-posts .total-pags").css({display:"none"});	
	} else {
		$j("#pags-posts .total-pags").css({display:"inline"});	
	}
	if(scrollIndexPost >= 5){
		$j("#pags-posts .inicio-pags").css({display:"inline"});	
	} else {
		$j("#pags-posts .inicio-pags").css({display:"none"});	
	}
	$j("#pags-posts .search-button-fwd").click(function(){
		apiPost.move(4);
		var newIndexPost = apiPost.getIndex();
		if(newIndexPost >= postLastLimit && newIndexPost <= postPagSize){
			$j("#pags-posts .total-pags").css({display:"none"});	
		} else {
			$j("#pags-posts .total-pags").css({display:"inline"});	
		}
		if(newIndexPost >= 5){
			$j("#pags-posts .inicio-pags").css({display:"inline"});	
		} else {
			$j("#pags-posts .inicio-pags").css({display:"none"});	
		}
	});
	$j("#pags-posts .search-button-back").click(function(){
		apiPost.move(-4);
		var newIndexPost = apiPost.getIndex();
		if(newIndexPost < postLastLimit){
			$j("#pags-posts .total-pags").css({display:"inline"});	
		} else {
			$j("#pags-posts .total-pags").css({display:"none"});	
		}
		if(newIndexPost >= 5){
			$j("#pags-posts .inicio-pags").css({display:"inline"});	
		} else {
			$j("#pags-posts .inicio-pags").css({display:"none"});	
		}
	});
}
//Scoll de todas las paginaciones
function scrollPages(currentPag){
	//Define el index del documento actual
	var indexPags = currentPag -1;
	$j(".wrapper-pages-num").scrollable({
		next:".search-button-fwd", 
		prev:".search-button-back",
		disabledClass: "pag-disabled"
	});
	var apiPags = $j(".wrapper-pages-num").data("scrollable");
	//Mueve el scroll al index actual
	apiPags.seekTo(indexPags);
	//Obtiene el número de páginas en el scroll
	var pagSize = apiPags.getSize();
	//Obtiene el número en donde desaparece el link a la última página
	var pagLastLimit = pagSize - 7;
	//Obtiene el índice actua en el que está el scroll
	var scrollIndex = apiPags.getIndex();
	//Comprueba la posición del scroll para mostrar u ocultar el link a la última página
	if(scrollIndex >= pagLastLimit && scrollIndex <= pagSize){
		$j(".total-pags").css({display:"none"});	
	} else {
		$j(".total-pags").css({display:"inline"});	
	}
	//Comprueba la posición del scroll para ocultar o mostrar el link a la primera página
	if(scrollIndex >= 5){
		$j(".inicio-pags").css({display:"inline"});	
	} else {
		$j(".inicio-pags").css({display:"none"});	
	}
	//Genera la función para avanzar más de un documento a la vez comprabar el índice
	$j(".search-button-fwd").click(function(){
		apiPags.move(4);
		var newIndex = apiPag.getIndex();
		if(newIndex >= pagLastLimit && newIndex <= pagSize){
			$j(".total-pags").css({display:"none"});	
		} else {
			$j(".total-pags").css({display:"inline"});	
		}
		if(newIndex >= 5){
			$j(".inicio-pags").css({display:"inline"});	
		} else {
			$j(".inicio-pags").css({display:"none"});	
		}
	});
	//Genera la función para retroceder más de un documento a la vez comprabar el índice
	$j(".search-button-back").click(function(){
		apiPags.move(-4);
		var newIndex = apiPags.getIndex();
		if(newIndex >= pagLastLimit && newIndex <= pagSize){
			$j(".total-pags").css({display:"none"});	
		} else {
			$j(".total-pags").css({display:"inline"});	
		}
		if(newIndex >= 5){
			$j(".inicio-pags").css({display:"inline"});	
		} else {
			$j(".inicio-pags").css({display:"none"});	
		}
	});
}

/* Funcion para galería de foto del día
---------------------------------------------------------------------------*/

function exposeGall(idImg){
	//Se declara el overlay
	//var attIdentificador = jQuery('#main-photo img').attr('src');

	var overlayGallery = jQuery('#' + idImg + ' > img').overlay({
		target: "#container-img-from-gallery", 
		close: ".close-expose", 
		left: "center",
		top: "center", 
		expose: '#000', 
		closeOnClick: true, 
		closeOnEsc: true, 
		onLoad: function(event, tabIndex) {
                         var attIdentificador = jQuery('#main-photo img').attr('src');
			// Al cargar el overlay se adecúa el div para insertar y mostrar los elementos
			jQuery('#container-img-from-gallery').empty();
			jQuery('#container-img-from-gallery').after(jQuery('<div id="overlay-background"></div>'));
			jQuery('#overlay-background').fadeIn();
			
			// Se agrega botón de previo
			jQuery('#container-img-from-gallery').append(jQuery('<a id="overlay-arrow-left" alt="Anterior" class="previousImg" title="Anterior" ></a>'));
			
			// Se obtiene la galería para modificar los atributos y mostrarla
			var clonImg = jQuery('.thumbnail').clone();
			jQuery('#overlay-arrow-left').after(jQuery('<div id="gallery-scrollable" class="scrollable"><div class="items"></div</div>'));

			// Se obtiene el contenedor para la imágenes
			var contenedor = jQuery('.items');
			
			// Se agregan las imágenes con sus descripciones al contenedor
			contenedor.append(clonImg);

			// Se agrega botón de siguiente
			jQuery('#container-img-from-gallery').append(jQuery('<a id="overlay-arrow-right" alt="Siguiente" class="nextImg" title="Siguiente" /></a>'));

			// Se agrega botón de cerrar overlay
			jQuery('#container-img-from-gallery').append(jQuery('<img src="assets/templates/md2010/images/para_expose/corte_x_close.png" alt="close" class="close-expose" title="Cerrar" />'));

			// Se obtienen una referencia a las imágenes
			var contenedores = jQuery('#gallery-scrollable .items .thumbnail');
			var cantidad = jQuery('#gallery-scrollable .items .thumbnail').length;
			var links = jQuery('#gallery-scrollable .items .thumbnail a');
			var imagenes = jQuery('#gallery-scrollable .items .thumbnail a img');
			var primera = jQuery('#gallery-scrollable .items .thumbnail:first');
			var ultima = jQuery('#gallery-scrollable .items .thumbnail:last');
			var previo = jQuery('#overlay-arrow-left');
			var siguiente = jQuery('#overlay-arrow-right');
			// Si el usuario está viendo alguna imagen que no se la primera se selecciona 
			// en la galería grande
			var seleccionada = jQuery('#gallery-scrollable .items .thumbnail a img[src$="' + attIdentificador + '"]');
			var directorioSeleccionado = seleccionada.parent().parent();
			var indice1 = directorioSeleccionado.index();

			// Se les quitan los atributos de altura y ancho
			imagenes.removeAttr('height');
			imagenes.removeAttr('width');
			links.attr('href', '#');
			links.click(function(e){e.preventDefault();});
			// Si la imágen no es la primera de la galería se muestra el botón de imágen previa.
			if(indice1 == 0){
				previo.hide();
			}
			
			contenedores.hide();
			//primera.addClass('current-image').show();
			// Se muestra la imágen que el usuario está viendo en la galería foto del día.
			contenedores.eq(indice1).addClass('current-image').show();

			var i = indice1;

			// Funcionalidad de los botones siguiente y previo.
			siguiente.click(function(){
				if(i <= cantidad){
					jQuery('.current-image').next().show(30, function(){
						jQuery('.current-image:first').fadeOut().removeClass('current-image');
					}).addClass('current-image');
					previo.fadeIn();
					i++;
				}
				if(i == cantidad - 1){
					siguiente.fadeOut();
				}
			});

			previo.click(function(){
				if(i <= cantidad){
					jQuery('.current-image').prev().show(30, function(){
						jQuery('.current-image:last').fadeOut().removeClass('current-image');
					}).addClass('current-image');
					siguiente.fadeIn();
					i--
				}
				if(i == 0){
					previo.fadeOut();
				}
			});

			// Manejador de evento de botón cerrar
			jQuery('#container-img-from-gallery .close-expose').click(function(){
				jQuery('#overlay-background').fadeOut(500, function(){jQuery('#overlay-background').remove();});
				jQuery('#container-img-from-gallery').fadeOut();
				jQuery('#container-img-from-gallery').empty();
			});
			
			jQuery('#overlay-background').click(function(){
				jQuery('#container-img-from-gallery .close-expose').click();
			});
		}, 
		// Manejador de evento de botón cerrar
		onClose: function() {
			jQuery('#overlay-background').fadeOut(500, function(){jQuery('#overlay-background').remove();});
			jQuery('#container-img-from-gallery').fadeOut();
			jQuery('#container-img-from-gallery').empty();
		}
	});
}

