var HOME = 1;
var ACERCA_DE_SUAT = 2;
var SERVICIOS = 3;
var NOVEDADES = 4;
var CONSEJOS_MEDICOS = 5;
var ARTICULOS = 6;
var AGENDA_MEDICA = 7;
var DICCIONARIO = 8;
var CONTACTO = 9;
var BUSCADOR = 10;
var DETALLE_NOVEDAD = 11;
var DETALLE_CONSEJO = 12;
var DETALLE_ARTICULO = 13;
var	IS_WORST_BROWSER;

$(document).ready(function(){

	IS_WORST_BROWSER = $.browser.msie;

	// LINKS MENU SUPERIOR
	$('.link_acerca').click(function(){
            $('.submenu.servicios').hide();
            if(!$('.submenu.acerca').is(':visible')){
                $('.submenu.acerca').slideDown('slow')
                $('#hd').removeClass('off');
                $('#hd').addClass('on');
            }
	});

	$('.submenu.acerca .close').click(function(){
            $('.submenu.acerca').slideUp('slow');
            $('#hd').removeClass('on');
            $('#hd').addClass('off');
	});

        $('.link_servicios').click(function(){
            $('.submenu.acerca').hide();

            if(!$('.submenu.servicios').is(':visible')){
                $('.submenu.servicios').slideDown('slow');
                $('#hd').removeClass('off');
                $('#hd').addClass('on');
            }
	});

	$('.submenu.servicios .close').click(function(){
		$('.submenu.servicios').slideUp('slow');
		$('#hd').removeClass('on');
		$('#hd').addClass('off');
	});

	//BUSCADOR
	_initInput('search','Buscar en SUAT');

	//FORMULARIO SUGERENCIAS
	_initInput('c-name','Nombre');
	_initInput('c-mail','e-mail');
	_initInput('comment','Comentario');

	//BOLETIN
	if($('#name-boletin')){
		_initInput('name-boletin','Nombre');
		_initInput('mail-boletin','e-mail');
	}


   //Abrir sub menu de Acerca o Servicios
	/*if(SESSION == ACERCA_DE_SUAT)
		$('.submenu.acerca').slideDown('fast');
	else if(SESSION == SERVICIOS)
		$('.submenu.servicios').slideDown('fast');
	*/


	//Agregar clase top
	if(SESSION != HOME){
           $('.tef-gu.right-column .tef-md:first').addClass('top');
	}

        //TOOLTIP DICCIONARIO
        $('.tip').each(function() {
            $(this).simpletip({
                position: 'top',
                content: $(this).attr('texto')
            });
        });

		$('.item-toggle h3 a').click(function () {
			$(this).parent().parent().children('.info').slideToggle("slow");
		});

		initWindowLogin();
});

/**
* muestra o oculta el texto que describe el formato para ingresar la cédula de identidad
*/
function toogleCIDescription(){
	if($(this).val() == 1){ // CI
		$('#register_document_verification').show('slow');
		$('#register_document').addClass('short');
		$('#container_ci_registro').addClass('container_ci');
		$('#register_document').attr('maxlength', 7);
	}else{
		$('#register_document_verification').hide('slow');
		$('#register_document').removeClass('short');
		$('#container_ci_registro').removeClass('container_ci');
		$('#register_document').attr('maxlength', 30);
	}
}

function toogleCIDescription_tutor(){
	if($(this).val() == 1){ // CI
		$('#document_tutor_verification').show('slow');
		$('#document_tutor').addClass('short');
		$('#container_ci_tutor').addClass('container_ci');
		$('#document_tutor').attr('maxlength', 7);
	}else{
		$('#document_tutor_verification').hide('slow');
		$('#document_tutor').removeClass('short');
		$('#container_ci_tutor').removeClass('container_ci');
		$('#document_tutor').attr('maxlength', 30);
	}
}

function buscar(){
	if(!inputIsEmpty('search'))
		$('#frm_buscador').submit();
}
function buscar_definicion(){
		if(!inputIsEmpty('keyword'))
			$('#frm_diccionario').submit();
	}

function update_cantidad_clicks(id_banner, url_to_open)
{
    $.ajax({
        type: 'POST',
        url: WEB_PATH + 'app/ajax/update_cantidad_clicks.php',
        data: {id: id_banner},
        success: function(response) {
        }
    });
    window.open(url_to_open);
}

//SUGERENCIAS
function sugerencias_enviar(){
	if (inputIsEmpty('c-name')) {
		$('#msg_error_sugerencias').html(MSG_COMPLETAR_NOMBRE);
		$('#c-name').focus();
	} else
	if (inputIsEmpty('c-mail')) {
		$('#msg_error_sugerencias').html(MSG_COMPLETAR_EMAIL);
		$('#c-mail').focus();
	} else
	if (!is_email($('#c-mail').val())) {
		$('#msg_error_sugerencias').html(MSG_EMAIL_INCORRECTO);
		$('#c-mail').focus();
	} else
	if(inputIsEmpty('comment')){
		$('#msg_error_sugerencias').html(MSG_COMPLETAR_COMENTARIO);
		$('#comment').focus();
	}else{
		var dataObj = new Object();
		dataObj.nombre = $('#c-name').val();
		dataObj.email = $('#c-mail').val();
		dataObj.sugerencia = $('#comment').val();
		dataObj.seccion = $('#c-section').val();
		$.ajax({
			type: "POST",
			url: WEB_PATH + "app/ajax/sugerencias_enviar.php",
			data: dataObj,
                        beforeSend: function(){
                            $('#msg_error_sugerencias').html('Enviando...');
                            $('#btn_sugerencia').attr('disabled','disabled');
                        },
			success: function(response)
			{
                            if (response == 1) {
                                    $('#msg_error_sugerencias').html(MSG_ENVIO_SUGERENCIA_OK);
                                    clean_form('frm_sugerencias');
                            } else {
                                    $('#msg_error_sugerencias').html(MSG_ENVIO_SUGERENCIA_ERROR);
                            }
                            $('#btn_sugerencia').removeAttr('disabled');
			}
		});
	}

}

//SUSCRIPCION BOLETIN
function suscripcion_boletin_enviar(){
	if (inputIsEmpty('name-boletin')) {
		$('#msg_suscripcion_boletin').html(MSG_COMPLETAR_NOMBRE);
		$('#name-boletin').focus();
	} else
	if (inputIsEmpty('mail-boletin')) {
		$('#msg_suscripcion_boletin').html(MSG_COMPLETAR_EMAIL);
		$('#mail-boletin').focus();
	} else
	if (!is_email($('#mail-boletin').val())) {
		$('#msg_suscripcion_boletin').html(MSG_EMAIL_INCORRECTO);
		$('#mail-boletin').focus();
	} else{
		var dataObj = new Object();
		dataObj.nombre = urlencode($('#name-boletin').val());
		dataObj.email = urlencode($('#mail-boletin').val());
		$.ajax({
			type: "POST",
			url: WEB_PATH + "app/ajax/suscripcion_boletin_enviar.php",
			data: dataObj,
                        beforeSend: function(){
                            $('#msg_suscripcion_boletin').html('Enviando...');
                            $('#btn_suscripcion_boletin').attr('disabled','disabled');
                        },
			success: function(response)
			{
				if (response == 1) {
					$('#msg_suscripcion_boletin').html(MSG_ENVIO_SUSCRIPCION_BOLETIN_OK);
					clean_form('frm_suscripcion_boletin');
				} else {
					$('#msg_suscripcion_boletin').html(MSG_ENVIO_SUSCRIPCION_BOLETIN_ERROR);
				}
				$('#btn_suscripcion_boletin').removeAttr('disabled');
			}
		});
	}

}

//OBTENER SUBCATEGORIAS
function consejos_get_subcategorias(){

	var dataObj = new Object();
	dataObj.idCat = $('#cbo_consejos_categorias').val();
	$.ajax({
		type: "POST",
		url: WEB_PATH + "app/ajax/consejos_categorias.php",
		data: dataObj,
		async: false,
		success: function(response)
		{
			var arr_subcat = response.split("|");
			var subcategorias = '';
			for(var i = 0; i<arr_subcat.length; i++){
				var arr_subcat_detalle = arr_subcat[i].split("¦");
				subcategorias += '<li><a href="'+arr_subcat_detalle[2]+'">'+arr_subcat_detalle[1]+'</a></li>';
				$(".consejo_subcat").html(subcategorias);
			}
		}
	});
}

//
// Cargado de Subcategorias Generico
//
function cargarSubcategorias( oPropiedades ) {
	var sUrl = oPropiedades.sUrl;
	var oData = oPropiedades.oData;
	var sDiv = oPropiedades.sResultDiv;

	$.ajax({
		type:		"POST",
		url:		sUrl,
		data:		oData,
		success:	function( sData ) {
			$('#' + sDiv ).html( sData );
		}
	});
}



//CATEGORIAS NOVEDADES
function filtrar_noticias(){
	if($('#categoria-noticias').val() != 0){
		window.location.href = WEB_PATH+'novedades/'+$('#categoria-noticias').val()+'-'+urlencode($('#categoria-noticias option:selected').text())+'/';
	}
	else{
		window.location.href = WEB_PATH+'novedades/';
	}
}

//CATEGORIAS RECETAS
function filtrar_recetas(){
	if($('#categoria-recetas').val() != 0){
		window.location.href = WEB_PATH+'recetas/'+$('#categoria-recetas').val()+'-'+urlencode($('#categoria-recetas option:selected').text())+'/';
	}
	else{
		window.location.href = WEB_PATH+'recetas/';
	}
}

function suat_consejos_busqueda(search, p)
{
	$.ajax({
		type: "POST",
		url: WEB_PATH + "app/ajax/consejos_busqueda.php",
		data: {search: urlencode(search), p: p},
		async: false,
		success: function(response)
		{
			$('#div_consejos_busqueda').html(response);
		}
	});
}

function suat_articulos_busqueda(search, p)
{
	$.ajax({
		type: "POST",
		url: WEB_PATH + "app/ajax/articulos_busqueda.php",
		data: {search: urlencode(search), p: p},
		async: false,
		success: function(response)
		{
			$('#div_articulos_busqueda').html(response);
		}
	});
}

function suat_novedades_busqueda(search, p)
{
	$.ajax({
		type: "POST",
		url: WEB_PATH + "app/ajax/novedades_busqueda.php",
		data: {search: urlencode(search), p: p},
		async: false,
		success: function(response)
		{
			$('#div_novedades_busqueda').html(response);
		}
	});
}

function suat_recetas_busqueda(search, p)
{
	$.ajax({
		type: "POST",
		url: WEB_PATH + "app/ajax/recetas_busqueda.php",
		data: {search: urlencode(search), p: p},
		async: false,
		success: function(response)
		{
			$('#div_recetas_busqueda').html(response);
		}
	});
}

function suat_paginas_estaticas_busqueda(search, idCat, p)
{
	$.ajax({
		type: "POST",
		url: WEB_PATH + "app/ajax/paginas_estaticas_busqueda.php",
		data: {search: urlencode(search), idCat : idCat, p: p},
		async: false,
		success: function(response)
		{
			// 1 - ACERCA DE   2 - SERVICIOS
			var sDivBusqueda = (idCat == 1) ? 'div_acerca_de_busqueda' : 'div_servicios_busqueda';
			$('#'+sDivBusqueda).html(response);
		}
	});
}

function suat_rse_busqueda(search, p)
{
	$.ajax({
		type: "POST",
		url: WEB_PATH + "app/ajax/rse_busqueda.php",
		data: {search: urlencode(search), p: p},
		async: false,
		success: function(response)
		{
			$('#div_rse_busqueda').html(response);
		}
	});
}



function set_banner_size(width, height, n)
{
	var movie = 'banner_'+n;
	var my_swf = null;
	if (window.document[movie]) {
		my_swf = window.document[movie];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1) {
		if (document.embeds && document.embeds[movie]) {
			my_swf = document.embeds[movie];
		}
	} else {
		my_swf = document.getElementById(movie);
	}
	my_swf.width = width;
	my_swf.height = height;
}


/**********************************************************/

/**
 * Carga banner's y rota
 *
 */
var banner_cont = new Array(0,0,0,0,0);
var videonames = new Array();
var arraybanner = new Array();
var arrayurls = new Array();

function cambiar(id){
	//console.log ('cambiar' , id) ;
	if (videonames[id].length > 1){
		banner_cont[id] ++;
		if (banner_cont[id] > (videonames[id].length - 1)){
			banner_cont[id] = 0;
		}
	}
	var srcurl = videonames[id][banner_cont[id]];
	var urlbanner = arraybanner[id][banner_cont[id]];
	var url = arrayurls[id][banner_cont[id]];

	$('#divBanner_'+id).html('<a target="_blank" href="' +  url + '"><object height="250" width="300" id="banner" name="banner" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version= 8,0,19,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">	<param value="'+srcurl+'" name="movie"/><param value="always" name="allowScriptAccess"/><param value="high" name="quality"/><param value="" name="FlashVars"/><param value="#FFFFFF" name="bgcolor"/><param value="false" name="menu"/><param value="transparent" name="wmode"/><param value="true" name="allowFullScreen"/><embed src="'+urlbanner+'" height="250" width="300" id="embed_1" name="embed_1" swliveconnect="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" quality="high" allowscriptaccess="always" menu="false" flashvars="" allowfullscreen="true" bgcolor="#FFFFFF" /></object></a>');
	if(videonames[id].length > 1  ){
		setTimeout("cambiar("+id+")", 10000);
	}
}

/**********************************************************/





/*************************/
// MI SUAT
/*************************/


//LOGIN

function initWindowLogin(){

	$('.button_my').click(function() {
		showMiSuatLogin(true, WEB_PATH + "mi_suat/");
	});

	$('.button').click(function() {
		//if($('.hide').is(':visible')){
		hideMiSuatLogin();
	});

	$('#bt_regSocio').click(showFormRegistro);


	$('#document_type').change(toogleCIDescription);
	$('#register_typeDoc').change(toogleCIDescription);
	$('#typeDoc_tutor').change(toogleCIDescription_tutor);

	$('#registro_typeDoc').change(function(){
		if($(this).val() == 1){ // CI
			$('#registro_verification').show();
			$('#registro_user').addClass('short');
			$('#container_ci_registro').addClass('container_ci');
			$('#registro_user').attr('maxlength', 7);
		}else{
			$('#registro_verification').hide();
			$('#registro_user').removeClass('short');
			$('#container_ci_registro').removeClass('container_ci');
			$('#registro_user').attr('maxlength', 30);
		}
	});

	$('#typeDoc').change(function(){
		if($(this).val() == 1){ // CI
			$('#user').addClass('short');
			$('#container_ci_login').addClass('container_ci');
			$('#user').attr('maxlength', 7);
			$('#user_verification').show();
		}else{
			$('#user').removeClass('short');
			$('#container_ci_login').removeClass('container_ci');
			$('#user').attr('maxlength', 30);
			$('#user_verification').hide();
		}
	});
}


/**
 * despliega la ventana para loguearse
 * redirect Boolean indica si se debe redirigir al usuario al home una vez logeado
 */
function showMiSuatLogin(redirect , url){
	scroll(0,0);
	showBg();
	$('.miSuat').addClass('on');
	if(redirect){
		$('#redirect').attr('value','true');
		$('#redirect').data('url',url);
	}else{
		$('#redirect').attr('value','false');
	}
	//$('#bgtransparent').append($('.miSuat'));
}
function showMiSuatLoginD(redirect){
	scroll(0,0);
	showBg();
	$('.miSuat').addClass('on');
	if(!redirect){
		$('#redirect').attr('value','false');
	}
	//$('#bgtransparent').append($('.miSuat'));
}
/**
 * oculta la ventana para loguerceca
 */
function hideMiSuatLogin(){
	hideBg();
	$('.miSuat').removeClass('on');
}

/**
 * envia el formulario de logeo o registro de usuario
 *
 * redirect Boolean indica si se debe redirigir al usuario al home o no
 */
function login_submit(){
	if (inputIsEmpty('user')) {
		$('#msg_error_login').html(MSG_COMPLETAR_DOCUMENTO);
		$('#user').focus();
	}else if (inputIsEmpty('typeDoc')) {
		$('#msg_error_login').html(MSG_COMPLETAR_DOCUMENTO_TIPO);
		$('#typeDoc').focus();
	}else if (inputIsEmpty('password')) {
		$('#msg_error_login').html(MSG_COMPLETAR_PASSWORD);
		$('#password').focus();
	}else{
		var redirect = $('#redirect').attr('value');
		showLoading(false);
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/login.php",
			data:$('#form_login').serialize(),
			async: true,
			success: function(response){
				//hideLoading();
				$('#loader_ajax').hide();
				var v_result = response.split("|");
				if(v_result[0]=='0'){
					$('#msg_error_login').html(MSG_LOGIN_ERROR);
				}else if(v_result[0]=='1'){
					if(redirect == 'false'){
						hideMiSuatLogin();
					}else{
						//window.location.href = WEB_PATH + "mi_suat/";
						window.location.href = $('#redirect').data('url');
					}
				}else{

					$('#msg_error_login').html(MSG_SYSTEM_ERROR+" Error:#52468");
				}
			}
		});
	}
}

function logout(){
	showLoading(true);
	$.ajax({
		type:"POST",
		url: WEB_PATH + "app/ajax/logout.php",
		data:'',
		async: true,
		success: function(response){
			hideLoading();
			window.location.href = WEB_PATH;
		}
	});
}


/**
 * valida la cedula
 */
function validate_cedula(str){
    ci_ = clean_cedula(str);
    ci_sin_digito = ci_.substr(0, ci_.length - 1);
    if (ci_sin_digito.length<7) ci_sin_digito='0' + ci_sin_digito;
    multiplicador = new Array(8, 1, 2, 3, 4, 7, 6);
    var suma = 0;
    for (var i=0;i<7;i++){
        suma = suma+(ci_sin_digito[i]*multiplicador[i]);
    }
    var codigo= suma % 10;

    if (codigo==ci_.substr(ci_.length - 1, 1)){
        return true;
	}else{
        return false;
	}
}

function clean_cedula(str){
    ci = str.trim();
    ci = ci.replace('-', '');
    ci = ci.replace(/\./g, ''); //elimina todas las ocurrencias del .
    return ci;
}


/**
 * despliega el formulario para solicitar una nueva contraseña
 */
function show_recover_password(){
	/*if($('#form_registro').is(':visible')){
		$('#form_registro').slideUp('slow');
	}else if($('#form_login').is(':visible')){
		$('#form_login').slideUp('slow');
	}*/

	$('#bt_regSocio').hide();
	$('#form_registro').hide();
	$('#recover_password').show();
	$('#new_typeDoc').change(function(){
		if($('#new_typeDoc').val() == 1) {
			$('#container_ci_new').addClass('container_ci');
			$('#new_verification').show('slow');
			$('#new_user').addClass('short');
			$('#new_user').attr('maxlength', 7);
		}else{
			$('#container_ci_new').removeClass('container_ci');
			$('#new_verification').hide('slow');
			$('#home video ').hide('slow') ;
			$('#new_user').removeClass('short');
			$('#new_user').attr('maxlength', 30);
		}
	});

}

/**
 * valida el formulario de login para "olvide mi contraseña"
 */
function recover_password(){
	if (inputIsEmpty('new_user')) {
		$('#msg_error_new').html(MSG_COMPLETAR_DOCUMENTO);
		$('#new_user').focus();
	}else if (inputIsEmpty('new_typeDoc')) {
		$('#msg_error_new').html(MSG_COMPLETAR_DOCUMENTO_TIPO);
		$('#new_typeDoc').focus();
	}else{
		$('#msg_error_login').html('');
		showLoading(true);
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/recover_password.php",
			data:$('#form_recover_password').serialize(),
			async: true,
			success: function(response){ //0: no se pudo enviar el email  al usuario, 1: se envio el mail con el token para modificar sus datos, -1: el usuario no esta registrado en nuestro sistema
				hideLoading();
				if(response == '-1'){
					show_alert('', MSG_NO_SOCIO_WEB, 'goHome', false, false);
				}else if(response =='0'){
					show_alert('', MSG_ENVIO_MAIL_ERROR, 'goHome', false, false);
				}else if (response == '1'){
					show_alert('', MSG_ENVIO_MAIL, 'goHome', false, false);
				}else{
					show_alert('', MSG_SYSTEM_ERROR+" Error:#55411", 'goHome', false, false);
				}
				//window.location.href = WEB_PATH;
			}
		});
	}
}

/**
 *  procesa el formulario de modificar contraseña
 */
function formRecoverPassword(){
	if (inputIsEmpty('reg_password')) {
		$('#msg_error_password').html(MSG_COMPLETAR_PASSWORD);
		$('#reg_password').focus();
	}else if (inputIsEmpty('reg_confirm_password')) {
		$('#msg_error_password').html(MSG_CONFIRMAR_PASSWORD);
		$('#reg_confirm_password').focus();
	}else if($('#reg_password').val() != $('#reg_confirm_password').val()){
		$('#msg_error_password').html(MSG_CONFIRMACION_INVALIDA);
		$('#confirm_password').focus();
	}else{
		$('#msg_error_password').html("");
		showLoading(true);
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/new_password.php",
			data:'action=set_password&'+$('#form_set_new_password').serialize(),
			async: true,
			success: function(response){
				hideLoading();
				var v_result = response.split("|");
				if(v_result[0]=='1'){
					window.location.href = WEB_PATH + "mi_suat/";
				}else{
					//window.location.href = WEB_PATH ;
					show_alert('', MSG_SYSTEM_ERROR+" Error:1134", 'goHome', false, false);
				}
			}
		});
	}
}

/**
 *	valida y envia el formulario de registro
 */
function user_registration(){
	if (inputIsEmpty('registro_user')) {
		$('#msg_error_registro').html(MSG_COMPLETAR_DOCUMENTO);
		$('#registro_user').focus();
	}else if (inputIsEmpty('registro_typeDoc')) {
		$('#msg_error_registro').html(MSG_COMPLETAR_DOCUMENTO_TIPO);
		$('#registro_typeDoc').focus();
	}else if (  $('#registro_typeDoc').val()== 1 && inputIsEmpty('registro_verification') ) {
		$('#msg_error_registro').html(MSG_COMPLETAR_N_VERIFICACION);
		$('#registro_typeDoc').focus();
	}else if (!is_email($('#registro_email').val())) {
		$('#msg_error_registro').html(MSG_COMPLETAR_EMAIL);
		$('#registro_email').focus();
	}else{
		$('#msg_error_registro').html("");
		showLoading(true);
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/registro.php",
			data:$('#form_registro').serialize(),
			async: true,
			success: function(response){
				hideLoading();
				var v_result = response.split("|");
				// 1 se le envio un email para completar el registro| 2 se necesitan mas datos, redireccionar a formulario de registro | -1 error inesperado, no se pudo enviar el email
				if(v_result[0]=='1'){
					showRegisterSendMail();
				}else if(v_result[0]=='2'){
					window.location.href = WEB_PATH + "mi_suat/registro/form/";
				}else if(v_result[0]=='-1'){
					$('#msg_error_registro').html(MSG_USUARIO_EXISTE);
				}else {
					$('#msg_error_registro').html(MSG_REG_ERROR);
					//$('#msg_error_registro').html(MSG_SYSTEM_ERROR+" Error:#510312");
				}
			}
		});
	}
}

/**
 * inicializa el datepicker con fechas anteriores a hoy, generalmente usado para fecha de nacimiento
 *
 */
function init_datePicker_past(){
	$(".datepicker").datepicker({
			dateFormat: 'yy - mm - dd',
			changeMonth: true,
			changeYear: true,
			minDate: '-110Y' ,
            maxDate: '0Y',
			constrainInput: true,
			defaultDate: new Date(1985, 1-1, 1)
		});
		//$('#deparetamentos').change(refreshCiudad);
}

/**
 * inicializa el datepicker para seleccion de fechas posteriores a hoy
 */
function init_datePicker_future(){
	$(".datepicker").datepicker({
			dateFormat: 'yy - mm - dd',
			changeMonth: true,
			changeYear: true,
			minDate: '0d' ,
            maxDate: '2Y',
			constrainInput: true
		});
}

function init_datePicker_tomorrow(){
	$(".datepicker_tomorrow").datepicker({
			dateFormat: 'yy - mm - dd',
			changeMonth: true,
			changeYear: true,
			minDate: '+1d' ,
            maxDate: '2Y',
			constrainInput: true
	});
}

/**
 * inicializa el datepicker para seleccion de fechas tanto anteriores como posteriores a hoy
 */
function init_datePicker_single(){
	$(".single_datePicker").datepicker({
			dateFormat: 'yy - mm - dd',
			changeMonth: true,
			changeYear: true,
			constrainInput: true
		});
}

/**
 * valida y envia el formulario de registro de usuario
 */
function register_user(){


	if(document.getElementById("tutor").style.display=="none"){

	}else{

		if (inputIsEmpty('first_surname_tutor')) {
			$('#register_msg_error').html(MSG_COMPLETAR_APELLIDO_PRIMERO);
			$('#first_surname_tutor').focus();
			return;
		}else if (inputIsEmpty('second_surname_tutor')) {
			$('#register_msg_error').html(MSG_COMPLETAR_APELLIDO_SEGUNDO);
			$('#second_surname_tutor').focus();
			return;
		}else if (inputIsEmpty('first_name_tutor')) {
			$('#register_msg_error').html(MSG_COMPLETAR_NOMBRE_PRIMERO);
			$('#first_name_tutor').focus();
			return;
		}else if (inputIsEmpty('second_name_tutor')) {
			$('#register_msg_error').html(MSG_COMPLETAR_APELLIDO_SEGUNDO);
			$('#second_name_tutor').focus();
			return;
		}else if (inputIsEmpty('typeDoc_tutor')) {
			$('#register_msg_error').html(MSG_COMPLETAR_DOCUMENTO_TIPO_TUTOR);
			$('#typeDoc_tutor').focus();
			return;
		}else if ($('#typeDoc_tutor').val() == 1 && inputIsEmpty('document_tutor_verification') ) {
			$('#register_msg_error').html(MSG_COMPLETAR_N_VERIFICACION);
			$('#typeDoc_tutor').focus();
			return;
		}else if (inputIsEmpty('document_tutor')) {
			$('#register_msg_error').html(MSG_COMPLETAR_DOCUMENTO_TUTOR);
			$('#document_tutor').focus();
			return;
		}else if (inputIsEmpty('relation')) {
			$('#register_msg_error').html(MSG_RELACION);
			$('#relation').focus();
			return;
		}
	}

	if (inputIsEmpty('register_first_name')) {
		$('#register_msg_error').html(MSG_COMPLETAR_NOMBRE);
		$('#register_first_name').focus();
	}else if (inputIsEmpty('register_first_surname')) {
		$('#register_msg_error').html(MSG_COMPLETAR_APELLIDO);
		$('#register_first_surname').focus();
	}else if (inputIsEmpty('register_typeDoc')) {
		$('#register_msg_error').html(MSG_COMPLETAR_DOCUMENTO_TIPO);
		$('#register_typeDoc').focus();
	}else if (inputIsEmpty('register_document')) {
		$('#register_msg_error').html(MSG_COMPLETAR_DOCUMENTO);
		$('#register_document').focus();
	}else if (inputIsEmpty('register_datepicker')) {
		$('#register_msg_error').html(MSG_COMPLETAR_FECHA_NACIMIENTO);
		$('#register_datepicker').focus();
	}else if (!is_email($('#register_email').val())) {
		$('#register_msg_error').html(MSG_COMPLETAR_EMAIL);
		$('#register_email').focus();
	}else{
		$('#register_msg_error').html("");
		showLoading(true);

		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/form_registro_usuario.php",
			data:$('#register_user_form').serialize(),
			async: true,
			success: function(response){
				hideLoading();
				var v_result = response.split("|");
				if(v_result[0]=='0'){
					$('#msg_error_registro2').html(MSG_SYSTEM_ERROR);
				}else if(v_result[0]=='1'){
					show_alert('', MSG_ENVIO_MAIL, 'goHome', false, false);
				}else if(v_result[0]=='-1'){
					$('#register_msg_error').html(MSG_USUARIO_EXISTE);
				}else{
					$('#msg_error_registro2').html(MSG_SYSTEM_ERROR+" Error:#5597005");
				}
			}
		});
	}
}


/**
 * valida y envia el formulario con datos de confirmacion para registro de socio
 */
function register_socio(){
	if (inputIsEmpty('register_first_name')) {
		$('#register_msg_error').html(MSG_COMPLETAR_NOMBRE);
		$('#register_first_name').focus();
	}else if (inputIsEmpty('register_first_surname')) {
		$('#register_msg_error').html(MSG_COMPLETAR_APELLIDO);
		$('#register_first_surname').focus();
	}else if (inputIsEmpty('register_datepicker')) {
		$('#register_msg_error').html(MSG_COMPLETAR_FECHA_NACIMIENTO);
		$('#register_datepicker').focus();
	}else if (inputIsEmpty('register_num_socio')) {
		$('#register_msg_error').html(MSG_COMPLETAR_NUMERO_SOCIO);
		$('#register_num_socio').focus();
	}else{
		$('#register_msg_error').html("");
		showLoading(true);
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/form_registro_socio.php",
			data:$('#register_socio_form').serialize(),
			async: true,
			success: function(response){
				hideLoading();
				var v_result = response.split("|");
				if(v_result[0]=='0'){
					show_alert('', MSG_REGISTRO_EVALUAR, 'goHome',false, false);
				}else if(v_result[0]=='1'){
					show_alert('', MSG_ENVIO_MAIL, 'goHome' ,false, false);
				}else if(v_result[0]=='-2'){
					goHome(); // no se pudo validar la session, redirect to home
				}else{
					$('#register_msg_error').html(MSG_SYSTEM_ERROR+" Error:#5597005");
				}
			}
		});
	}
}

/**
 *redirecciona al home de la pagina
 */
function goHome(){
	window.location.href = WEB_PATH ;
}
/**
 * asigna el nuevo password para finalizar el registro de socios
 */
function registerNewPassword(){

	//alert($('#reg_password').val() + " - " + $('#reg_confirm_password').val());
	var new_password = $('#reg_password').val();

	if (inputIsEmpty('reg_password')) {
		$('#msg_error_password').html(MSG_COMPLETAR_PASSWORD);
		$('#reg_password').focus();

	}else if (inputIsEmpty('reg_confirm_password')) {
		$('#msg_error_password').html(MSG_CONFIRMAR_PASSWORD);
		$('#reg_confirm_password').focus();

	}else if($('#reg_password').val() != $('#reg_confirm_password').val()){
		$('#msg_error_password').html(MSG_CONFIRMACION_INVALIDA);
		$('#confirm_password').focus();

	}else{

		$('#msg_error_password').html("");
		showLoading(true);
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/registro_new_password.php",
			data:'action=set_password&'+ 'password=' + new_password,
			async: true,
			success: function(response){
				hideLoading();
				var v_result = response.split("|");
				if(v_result[0]=='0'){
					$('#msg_error_password').html(MSG_SYSTEM_ERROR+" Error:#65662");
				}else if(v_result[0]=='1'){
					window.location.href = WEB_PATH + "mi_suat/";
				}else{
					$('#msg_error_password').html(MSG_SYSTEM_ERROR +" Error:#597005");
				}
			}
		});
	}
}


function showRegisterSendMail(){
	//$('#bt_regSocio').unbind('click');
	$('#bt_regSocio').hide();
	$('#form_registro').hide();
	$('#msg_confirmation').show();
}

/**
 * guardar la informacion personal de usuario web
 */
function saveUserData(){
	if (inputIsEmpty('info_nombre')) {
		$('#msg_error').html(MSG_COMPLETAR_NOMBRE);
		$('#info_nombre').focus();
	}else if (inputIsEmpty('info_apellido')) {
		$('#msg_error').html(MSG_COMPLETAR_APELLIDO);
		$('#info_apellido').focus();
	}else if (inputIsEmpty('info_telefono') && inputIsEmpty('info_cel')) {
		$('#msg_error').html(MSG_COMPLETAR_ALGUN_TELEFONO);
		$('#info_telefono').focus();
	}else if (!is_email($('#info_email').val())) {
		$('#msg_error').html(MSG_COMPLETAR_EMAIL);
		$('#info_email').focus();
	}else{
		showLoading(true);
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/savePersonalData.php",
			data:$('#formEditPersonalData').serialize(),
			async: true,
			success: function(response){
				hideLoading();
				var v_result = response.split("|");
				if(v_result[0]=='0'){
					$('#msg_error').html(MSG_SYSTEM_ERROR+" Error:#127657");
				}else if(v_result[0]=='1'){
					window.location.href = WEB_PATH + "mi_suat/";
				}else{
					$('#msg_error').html(MSG_SYSTEM_ERROR+" Error:#52467");
				}
			}
		});
	}
}

/**
 * guardar la informacion personal de socio suat
 */
function saveSocioData(){
	if (inputIsEmpty('info_nombre')) {
		$('#msg_info_error').html(MSG_COMPLETAR_NOMBRE);
		$('#info_nombre').focus();
	}else if (inputIsEmpty('info_apellido')) {
		$('#msg_info_error').html(MSG_COMPLETAR_APELLIDO);
		$('#info_apellido').focus();
	}else if (inputIsEmpty('info_telefono') && inputIsEmpty('info_cel')) {
		$('#msg_info_error').html(MSG_COMPLETAR_ALGUN_TELEFONO);
		$('#info_telefono').focus();
	}else if (!is_email($('#info_email').val())) {
		$('#msg_info_error').html(MSG_COMPLETAR_EMAIL);
		$('#info_email').focus();
	}else{
		showLoading(true);
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/savePersonalData.php",
			data:'user=1&'+$('#formEditPersonalData').serialize(),
			async: true,
			success: function(response){
				hideLoading();
				var v_result = response.split("|");
				if(v_result[0]=='0'){
					$('#msg_info_error').html(MSG_SYSTEM_ERROR+" Error:#52461");
				}else if(v_result[0]=='1'){
					show_alert('',MSG_MODIFICAR_DATOS_OK, 'goBack', false, false);
					//window.location.href = WEB_PATH + "mi_suat/";
				}else{
					$('#msg_info_error').html(MSG_SYSTEM_ERROR+" Error:#52462");
				}
			}
		});
	}
}

function goBack(){
	history.back(-1);
}

/**
 * despliega el formulario de registro
 */
function showFormRegistro(){
	if( IS_WORST_BROWSER ){
		if($('#form_registro').is(':visible')){
			$('#form_registro').hide('slow');
			$('#form_login').show('slow');
		}else{
			$('#form_registro').show('slow');
			$('#form_login').hide('slow');
		}
		if($('#recover_password').is(':visible')){
			$('#recover_password').hide();
		}
	}else{
		$('#form_registro').slideToggle();
		$('#form_login').slideToggle();
	}


}

/**
 * despliega y contrae "mas datos" personales del usuario, (solo para socios)
 */
function moreData(){
	//$('#bt_view_more').toggle(showMoreData, hideMoreData);
	if($('#more_info').is (':hidden')){
		showMoreData();
	}else{
		hideMoreData();
	}
	return false;
}
// despliega los datos extra
function showMoreData(){
	//console.log("show");
	$('#more_info').show(); // erorr al usar $('#more_info').show("slow"); o $('#more_info').slideDown()
	//$('#more_info').slideDown();
	$('#bt_view_more').removeClass('view-more');
	$('#bt_view_more').addClass('view-less');
	$('#bt_view_more').html("ver menos");
}
//oculta los datos extra
function hideMoreData(){
	//console.log("hide");
	$('#more_info').hide();
	$('#bt_view_more').removeClass('view-less');
	$('#bt_view_more').addClass('view-more');
	$('#bt_view_more').html("ver más");
}

/**
 * expande contrae mas informacion en las facturas en las seccion, 'estado de cuenta'
 */
function expandInfo(id){
	var obj = $('#detail_'+id);
	if(obj.is (':hidden')){
		obj.slideDown();
		$('#tef-mu_'+id).addClass('open');
		//obj.parent().children(':a').removeClass('more');
		//obj.parent().children(':a').addClass('less');
	}else{
		obj.slideUp();
		$('#tef-mu_'+id).removeClass('open');
		//obj.parent().children(':a').removeClass('less');
		//obj.parent().children(':a').addClass('more');
	}
}

/**
 * abre una nueva pestaña para imprimir la factura
 */
function print_invoice(id_invoice){
	// usar window.open  una fea practica pero funciona, :(
	window.open(WEB_PATH+'mi_suat/invoice/print/'+id_invoice+'/', "_blank");
}


function pay_invoice(){

	//var chks=$("input:checkbox[name^='chk']"); // filtrar checkbox por nombre
	var chks=$("input:checkbox");
	var select = false;
	var box = new Array();

	// crear array con los valores de los comboBox
	chks.each(function() {
		if (this.checked){
			select = true;
			box.push(this.value);
		}
	});

	if(!select){
		 $('#msg_invoice_error').html(MSG_SELECCIONAR_FACTURA);
	}else{
		$('#msg_invoice_error').html("");
		if( evalFormLocation() ){
			showLoading(true);
			$.ajax({
				type:"POST",
				url: WEB_PATH + "app/ajax/pagar_factura.php",
				data:'chks='+box+'&zipCode='+$('#zipCode').val(),
				async: true,
				success: function(response){
					hideLoading();
					var v_result = response.split("|");
					if(v_result[0]=='0'){
						$('#msg_invoice_error').html(MSG_SYSTEM_ERROR+" Error:#11246");
					}else if(v_result[0]=='1'){
						$('#bd').html(v_result[1]);
						Custom.init();
					}else{
						$('#msg_info_error').html(MSG_SYSTEM_ERROR+" Error:#52126");
					}
				}
			});
		}
	}
}

function evalFormLocation(){
	var isValid = false;
	if( ($('#formLocation').length > 0) ){
			if($('#formLocation').is(':visible')){
				if(inputIsEmpty('zipCode')){
					$('#zipCode').focus();
					$('#msg_invoice_error').html(MSG_ZIPCODE_ERROR);
				}else if(inputIsEmpty('country') && $('#country').length > 0 ){
					console.log(('#country').length );
					console.log(('#country') );

					$('#country').focus();
					$('#msg_invoice_error').html(MSG_COUNTRY_ERROR);
				}else{
					isValid = true;
				}
			}else{
				$('#formLocation').show('slow');
				isValid = false;
			}
	}else{
		isValid = true;
	}

	return isValid;
}

/**
 * procesa el formulario de pago con tarjeta de credito
 */
function send_form_forma(){
	if (inputIsEmpty('type_target')) {
		$('#pay_msg_error').html(MSG_COMPLETAR_FORMA_PAGO);
		$('#type_target').focus();
	}else{
		$('#frmSolicitudPago').submit();
		/*
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/pagar_onLine.php",
			data:$('#form_pay_onLine').serialize(),
			async: true,
			success: function(response){
				hideLoading();
				if(response == '1'){
					//show_alert('', MSG_HCM_HABILITAR_OK, 'refresh_HCM', false, false);
				}else if(response == '0'){
					//show_alert('ERROR', MSG_HCM_HABILITAR_ERROR, 'goHome', false, false);
				}else{
					//show_alert('ERROR', MSG_SYSTEM_ERROR+' id:454481', 'goHome', false, true);
				}
			}
		});*/

	}
}
/**
 * agrega los eventos para los tabs de la pagina de pagar cuenta
 */
/*
function initEstadoCuenta(){
	//$("#pay_tabs").tabs();
	//init_datePicker_future();
	init_datePicker_single();
	$('#datos').click(function(){
		$('#forma').removeClass('active');
		$('#datos').addClass('active');
		$('#tabs-datos').removeClass('hidden');
		$('#tabs-forma').addClass('hidden');
	});
	$('#forma').click(function(){
		$('#datos').removeClass('active');
		$('#forma').addClass('active');
		$(this).addClass('active');
		$('#tabs-forma').removeClass('hidden');
		$('#tabs-datos').addClass('hidden');
	});
	//initTabs();
}
*/


/**
 * crea las funcionalidad de tabs, para pago on-line
 */
function initTabs(){
	$("ul.tabs-list li").click(function(){
		//this.addClass('active');
		$("ul.tabs-list li").removeClass('active');
		$(this).addClass('active');
		var li_id = $("ul.tabs-list li").index(this);
		var div_id = $("#pay_tabs").children('div').get(li_id).id;
		$('#pay_tabs').children('div').addClass('hidden');;
		$('#'+div_id).removeClass('hidden');
	});
}


/**
 * inicializa js para la pagina de Historia Clinica Multimedia
 */
function init_hcm(){
	init_datePicker_past();
	toolTipHcm();
}

/**
 * muestra-oculta tooltip para los links de HCM
 */
function toolTipHcm(){
	$('.planillas a').mouseenter(function() {
		$(this).find('span').show();
	});
	$('.planillas a').mouseleave(function() {
		$(this).find('span').fadeOut();
	});
}

/**
 * despliega el formulario para habilitar laHistoria Clinica Multimedia
 */
function show_form_HCM(){
	// window.location.href = WEB_PATH + "mi_suat/historia-clinica/habilitar";
	$('.no-service').hide('slow');
	$('.tef-md-register').show('slow');
	 //show_alert('el titulo', 'se te envio un email, bla bla bla.... ', 'goHome' ,false, false);
}

/**
 * procesa el formulario para habilitar la HCM
 */
function enable_history(){
	showLoading(true);
	$.ajax({
		type:"POST",
		url: WEB_PATH + "app/ajax/enable_history.php",
		data:$('#enable_history').serialize(),
		async: true,
		success: function(response){
			hideLoading();
			if(response == 1){
				show_alert('', MSG_HCM_HABILITAR_OK, 'refresh_HCM', false, false);
			}else if(response == 0 || response == -1){
				show_alert('ERROR', MSG_HCM_HABILITAR_ERROR, 'goHome', false, false);
			}else{
				show_alert('ERROR', MSG_SYSTEM_ERROR+' id:556456', 'goHome', false, true);
			}
		}
	});
}

/**
 * recarga la pagina de historia clinica
 */
function refresh_HCM(){
	window.location.href = WEB_PATH + "mi_suat/historia-clinica/";
}

/**
 *agrega un antecedente en HCM
 */
function add_precedent(){
	//if(!$('#container_form_precedent').is(':visible')){  //no, es visible  ?   no funciona con ie
	//if($('#container_form_precedent').is(':hidden')){ // esta oculto  ? no funciona con ie
	//if ( !($('#DivBlock').is (':visible') && $('#DivBlock').parents (':hidden').length == 0)){ // el elemento es visible y ninguno de sus padres esta oculto ?
	if($('#container_form_precedent').css("display") == 'none'){
		show_precedent();
	}else{
		if (inputIsEmpty('precedent_description')) {
			$('#msg_error_precedent').html(MSG_COMPLETAR_DESCRIPCION);
			$('#precedent_description').focus();
		}else{
			showLoading(true);
			$.ajax({
				type:"POST",
				url: WEB_PATH + "app/ajax/add_antecedente.php",
				data:$('#form_precedent').serialize(),
				async: true,
				success: function(response){
					hideLoading();
					$('#form_precedent')[0].reset();
					show_alert('', MSG_AGREGAR_ANTECEDENTE, 'NothingsGonnaChangeMyWorld', false, false);
					hide_precedent();
					/*var v_result = response.split("|");
					if(v_result[0]=='0'){
						$('#antecedente_msg_error').html(MSG_LOGIN_ERROR);
					}else if(v_result[0]=='1'){
						$('#antecedente_msg_error').html('en un rato actualizamos los datos, cualquier cosa pasa por bedelía');
						//window.location.href = WEB_PATH + "mi_suat/";
					}else{
						$('#antecedente_msg_error').html(MSG_SYSTEM_ERROR+" Error:#5885411");
					}*/
				}
			});
		}
	}
	//ajax_div(WEB_PATH+"app/ajax/form_add_antecedente.php", "reg_init");
}

/**
 * funcion que no hace nada,  se usa en caso de necesitar llamar a una funcion de callBack que no haga nada
 */
function NothingsGonnaChangeMyWorld(){
	return;
}

/**
 * despliega el formulario para agregar un nuevo antecedente
 */
function show_precedent(){
	$('#container_form_precedent').show();
	$('#bt_cancel_precedent').show()
	$('#msg_error_precedent').html("");
}

/**
 * oculta el formulario para agregar antecedentes
 */
function hide_precedent(){
	$('#container_form_precedent').hide();
	$('#bt_cancel_precedent').hide()
	$('#msg_error_precedent').html("");
}

function reg_init(){
	return false;
}


function sendForm_antecedente(){
	if (inputIsEmpty('antecedente_date')) {
		$('#antecedente_msg_error').html(MSG_COMPLETAR_FECHA);
		$('#antecedente_date').focus();
	}else if (inputIsEmpty('antecedente_type')) {
		$('#antecedente_msg_error').html(MSG_COMPLETAR_ANTECEDENTE_TIPO);
		$('#antecedente_type').focus();
	}else if (inputIsEmpty('antecedente_description')) {
		$('#antecedente_msg_error').html(MSG_COMPLETAR_DESCRIPCION);
		$('#antecedente_description').focus();
	}else{
		showLoading(true);
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/add_antecedente.php",
			data:$('#form_add_antecedente').serialize(),
			async: true,
			success: function(response){
				hideLoading();
				var v_result = response.split("|");
				if(v_result[0]=='0'){
					$('#antecedente_msg_error').html(MSG_LOGIN_ERROR);
				}else if(v_result[0]=='1'){
					$('#antecedente_msg_error').html('en un rato actualizamos los datos, cualquier cosa pasa por bedelia');
					//window.location.href = WEB_PATH + "mi_suat/";
				}else{
					$('#antecedente_msg_error').html(MSG_SYSTEM_ERROR+" Error:#5885411");
				}
			}
		});
	}
}

function init_service_seguro_viajero(){
	init_datePicker_past();
	$('#deparetamentos').change(refreshCiudad);
}

function show_info_services(id){

	var obj = $('#services_info_'+id);
	if(obj.is (':hidden')){
		obj.slideDown();
		$('#services_more_info_'+id).addClass('open');
		$('#services_more_info_'+id).html('Menos información');
	}else{
		obj.slideUp();
		$('#services_more_info_'+id).removeClass('open');
		$('#services_more_info_'+id).html('Más información');
	}

}

/**
 * redirecciona a los links para contratar servicio,  esta funcion podria eliminarce :( y directamente escribir las rutas en el html
 */
function service_contract(id){
	showLoading(true);

	var url ;
	switch(id){
		case 1:
			url = WEB_PATH + "mi_suat/servicio/form/socio_suat";
			break;
		case 2:
			url = WEB_PATH + "mi_suat/servicio/form/seguro_viaje";
			break;
		case 3:
			url = WEB_PATH + "mi_suat/servicio/form/suat_soluciones";
			break;
	}

	$.ajax({
		type:"POST",
		url: WEB_PATH + "app/ajax/check_user.php",
		data:"",
		async: true,
		success: function(response){
			if(response){
				//console.log(id);
				window.location.href = url;
			}else{
				hideLoading(function(){
					showMiSuatLogin(true, url);
				});
			}
		}
	});

}


/********** contratar servicios *******/


/**
 * valida el formulario para contratar servicio 'socio suat'
 */
function service_associate(){
	if (inputIsEmpty('surname1')) {
		$('#service_msg_error').html(MSG_COMPLETAR_APELLIDO);
		$('#surname1').focus();
	} else if (inputIsEmpty('name1')) {
		$('#service_msg_error').html(MSG_COMPLETAR_NOMBRE);
		$('#name1').focus();
	}else if (inputIsEmpty('document_type')) {
		$('#service_msg_error').html(MSG_COMPLETAR_DOCUMENTO_TIPO);
		$('#document_type').focus();
	}else if (inputIsEmpty('document_id')) {
		$('#service_msg_error').html(MSG_COMPLETAR_DOCUMENTO);
		$('#document_id').focus();
	}else if (inputIsEmpty('birthday')) {
		$('#service_msg_error').html(MSG_COMPLETAR_FECHA_NACIMIENTO);
		$('#birthday').focus();
	}else if (inputIsEmpty('phone') && inputIsEmpty('celPhone')) {
		$('#service_msg_error').html(MSG_COMPLETAR_ALGUN_TELEFONO);
		$('#phone').focus();
	}else if(!is_email($('#email').val())) {
		$('#service_msg_error').html(MSG_COMPLETAR_EMAIL);
		$('#email').focus();
	}else if ( $('#ocupaciones').prev().html() == 'seleccione una ocupación' ){
		$('#service_msg_error').html(MSG_COMPLETAR_OCUPACION);
		$('#ocupaciones').focus();
	}else if ( $('#mutualista').prev().html() == 'seleccione una mutualista') {
		$('#service_msg_error').html(MSG_COMPLETAR_MUTUALISTA);
		$('#mutualista').focus();
	}else if ( $('#emergenciaMedica').prev().html() == 'seleccione una emergencia medica') {
		$('#service_msg_error').html(MSG_COMPLETAR_EMERGENCIA);
		$('#emergenciaMedica').focus();
	}else if (inputIsEmpty('avisarName')){
		$('#service_msg_error').html(MSG_COMPLETAR_AVISAR_NOMBRE);
		$('#avisarName').focus();
	}else if (inputIsEmpty('avisarPhone') && inputIsEmpty('avisarCelPhone')) {
		$('#service_msg_error').html(MSG_COMPLETAR_AVISAR_TEL);
		$('#avisarPhone').focus();
	}else if (inputIsEmpty('street')){
		$('#service_msg_error').html(MSG_COMPLETAR_CALLE);
		$('#street').focus();
	}else if (inputIsEmpty('street_number') && inputIsEmpty('solar') && inputIsEmpty('chalet') && inputIsEmpty('complejo') ){
		$('#service_msg_error').html(' debes especificar mejor tu direccion');
		// si especifico solar, debe especificar tambien  manzana y km
	}else if( !inputIsEmpty('solar') && inputIsEmpty('manzana') && inputIsEmpty('km') ){
		$('#service_msg_error').html('si especifico solar, debe especificar tambien  manzana y km ');
	}else if( inputIsEmpty('deparetamentos') ){
		$('#service_msg_error').html(MSG_COMPLETAR_DEPARTAMENTO);
		$('#departamentos').focus();
	}else if( $('#ciudades').prev().html() == 'seleccione una ciudad' ){  // :(
		$('#service_msg_error').html(MSG_COMPLETAR_CIUDAD);
		$('#ciudades').focus();
	}else{
		$('#service_msg_error').html('');
		// verifico que el usuario ya no tenga contratado este servicio
		// verifico que el usuario ya no tenga contratado este servicio
		showLoading(true);
		var data = "action=save_data&type=socio_suat&"+$('#form_socio_suat').serialize();
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/eval_contratar_servicio.php",
			data:data,
			async: true,
			success: function(response){
				if(response){
					var v_result = response.split("|");
					data = data+'&servicePriceCurrency='+v_result[1]+'&servicePrice='+v_result[2];
					$.ajax({
						type:"POST",
						url: WEB_PATH + "app/ajax/contratar_servicio.php",
						data:data,
						async: true,
						success: function(response){
							hideLoading();
							window.location.href = WEB_PATH + "mi_suat/servicio/cons/socio_suat";
						}
					});
				}else{
					hideLoading();
					var msj = 'Según nuestros registros ya eres socio SUAT. Por más información comunicate a <a href="mailto:mensajes@suat.com.uy?subject=subject"> mensajes@suat.com.uy</a> o llamá al 2711 0 711 . ';
					show_alert('ERROR', msj, 'goBack', false, false);
				}
			}
		});
	}
}

/**
 * valida el formulario para contratar servicio 'suat soluciones'
 */
function service_solutions(){
	if (inputIsEmpty('surname1')) {
		$('#service_msg_error').html(MSG_COMPLETAR_APELLIDO);
		$('#surname1').focus();
	}else if (inputIsEmpty('name1')) {
		$('#service_msg_error').html(MSG_COMPLETAR_NOMBRE);
		$('#name1').focus();
	}else if (inputIsEmpty('document_type')) {
		$('#service_msg_error').html(MSG_COMPLETAR_DOCUMENTO_TIPO);
		$('#document_type').focus();
	}else if (inputIsEmpty('document_id')) {
		$('#service_msg_error').html(MSG_COMPLETAR_DOCUMENTO);
		$('#document_id').focus();
	}else if (inputIsEmpty('birthday')) {
		$('#service_msg_error').html(MSG_COMPLETAR_FECHA_NACIMIENTO);
		$('#birthday').focus();
	}else if(!evalBirthday($('#birthday').val(), 15 , 60)){
		$('#service_msg_error').html(MSG_ERROR_EDAD_SOLUCIONES);
	}else if (inputIsEmpty('phone') && inputIsEmpty('celPhone')) {
		$('#service_msg_error').html(MSG_COMPLETAR_ALGUN_TELEFONO);
		$('#phone').focus();
	}else if(!is_email($('#email').val())) {
		$('#service_msg_error').html(MSG_COMPLETAR_EMAIL);
		$('#email').focus();
	}else if ( $('#ocupaciones').prev().html() == 'seleccione una ocupación' ){
		$('#service_msg_error').html(MSG_COMPLETAR_OCUPACION);
		$('#ocupaciones').focus();
	}else if ( $('#mutualista').prev().html() == 'seleccione una mutualista') {
		$('#service_msg_error').html(MSG_COMPLETAR_MUTUALISTA);
		$('#mutualista').focus();
	}else if ( $('#emergenciaMedica').prev().html() == 'seleccione una emergencia medica') {
		$('#service_msg_error').html(MSG_COMPLETAR_EMERGENCIA);
		$('#emergenciaMedica').focus();
	}else if (inputIsEmpty('avisarName')){
		$('#service_msg_error').html(MSG_COMPLETAR_AVISAR_NOMBRE);
		$('#avisarName').focus();
	}else if (inputIsEmpty('avisarPhone') && inputIsEmpty('avisarCelPhone')) {
		$('#service_msg_error').html(MSG_COMPLETAR_AVISAR_TEL);
		$('#avisarPhone').focus();
	}else if (inputIsEmpty('street')){
		$('#service_msg_error').html(MSG_COMPLETAR_CALLE);
		$('#street').focus();
	}else if (inputIsEmpty('street_number') && inputIsEmpty('solar') && inputIsEmpty('chalet') && inputIsEmpty('complejo') ){
		$('#service_msg_error').html('debes especificar mejor tu direccion');
		// si especifico solar, debe especificar tambien  manzana y km
	}else if( !inputIsEmpty('solar') && inputIsEmpty('manzana') && inputIsEmpty('km') ){
		$('#service_msg_error').html('si especifico solar, debe especificar tambien  manzana y km ');
	}else if( inputIsEmpty('deparetamentos') ){
		$('#service_msg_error').html(MSG_COMPLETAR_DEPARTAMENTO);
		$('#departamentos').focus();
	}else if( $('#ciudades').prev().html() == 'seleccione una ciudad' ){  // :(
		$('#service_msg_error').html(MSG_COMPLETAR_CIUDAD);
		$('#ciudades').focus();
	}else{
		// verifico que el usuario ya no tenga contratado este servicio
		showLoading(true);
		var data = "action=save_data&type=suat_soluciones&"+$('#form_suat_soluciones').serialize();
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/eval_contratar_servicio.php",
			data:data,
			async: true,
			success: function(response){
				if(response){
					var v_result = response.split("|");
					data = data+'&servicePriceCurrency='+v_result[1]+'&servicePrice='+v_result[2];
					$.ajax({
						type:"POST",
						url: WEB_PATH + "app/ajax/contratar_servicio.php",
						data:data,
						async: true,
						success: function(response){
							hideLoading();
							window.location.href = WEB_PATH + "mi_suat/servicio/cons/suat_soluciones";
						}
					});
				}else{
					hideLoading();
					var msj = 'Según nuestros registros ya eres socio de SUAT Soluciones. Por más información comunicate a <a href="mailto:mensajes@suat.com.uy?subject=subject"> mensajes@suat.com.uy</a> o llamá al 2711 0 711 . ';
					show_alert('ERROR', msj, 'goBack', false, false);
				}
			}
		});

	}
}

/**
 * valida el formulario para contratar servicio 'seguro de viajero'
 */
function service_travel_insurance(){
	if (inputIsEmpty('surname1')) {
		$('#service_msg_error').html(MSG_COMPLETAR_APELLIDO);
		$('#surname1').focus();
	}else if (inputIsEmpty('name1')) {
		$('#service_msg_error').html(MSG_COMPLETAR_NOMBRE);
		$('#name1').focus();
	}else if (inputIsEmpty('document_type')) {
		$('#service_msg_error').html(MSG_COMPLETAR_DOCUMENTO_TIPO);
		$('#document_type').focus();
	}else if (inputIsEmpty('document_id')) {
		$('#service_msg_error').html(MSG_COMPLETAR_DOCUMENTO);
		$('#document_id').focus();
	}else if (inputIsEmpty('birthday')) {
		$('#service_msg_error').html(MSG_COMPLETAR_FECHA_NACIMIENTO);
		$('#birthday').focus();
	}else if(!evalBirthday($('#birthday').val(), 0 , 80)){
		$('#service_msg_error').html(MSG_ERROR_EDAD_SEGURO);
	}else if (inputIsEmpty('phone') && inputIsEmpty('celPhone')) {
		$('#service_msg_error').html(MSG_COMPLETAR_ALGUN_TELEFONO);
		$('#phone').focus();
	}else if(!is_email($('#email').val())) {
		$('#service_msg_error').html(MSG_COMPLETAR_EMAIL);
		$('#email').focus();
	}else if ( $('#ocupaciones').prev().html() == 'seleccione una ocupación' ){
		$('#service_msg_error').html(MSG_COMPLETAR_OCUPACION);
		$('#ocupaciones').focus();
	}else if ( $('#mutualista').prev().html() == 'seleccione una mutualista') {
		$('#service_msg_error').html(MSG_COMPLETAR_MUTUALISTA);
		$('#mutualista').focus();
	}else if ( $('#emergenciaMedica').prev().html() == 'seleccione una emergencia medica') {
		$('#service_msg_error').html(MSG_COMPLETAR_EMERGENCIA);
		$('#emergenciaMedica').focus();
	}else if (inputIsEmpty('avisarName')){
		$('#service_msg_error').html(MSG_COMPLETAR_AVISAR_NOMBRE);
		$('#avisarName').focus();
	}else if (inputIsEmpty('avisarPhone') && inputIsEmpty('avisarCelPhone')) {
		$('#service_msg_error').html(MSG_COMPLETAR_AVISAR_TEL);
		$('#avisarPhone').focus();
	}else if (inputIsEmpty('street')){
		$('#service_msg_error').html(MSG_COMPLETAR_CALLE);
		$('#street').focus();
	}else if (inputIsEmpty('street_number') && inputIsEmpty('solar') && inputIsEmpty('chalet') && inputIsEmpty('complejo') ){
		$('#service_msg_error').html(' debes especificar mejor tu direccion');
		// si especifico solar, debe especificar tambien  manzana y km
	}else if( !inputIsEmpty('solar') && inputIsEmpty('manzana') && inputIsEmpty('km') ){
		$('#service_msg_error').html('si especifico solar, debe especificar tambien  manzana y km ');
	}else if( inputIsEmpty('deparetamentos') ){
		$('#service_msg_error').html(MSG_COMPLETAR_DEPARTAMENTO);
		$('#departamentos').focus();
	}else if( $('#ciudades').prev().html() == 'seleccione una ciudad' ){  // :(
		$('#service_msg_error').html(MSG_COMPLETAR_CIUDAD);
		$('#ciudades').focus();
	}else{
		$('#service_msg_error').html('');

		// verifico que el usuario ya no tenga contratado este servicio
		showLoading(true);
		var data = "action=save_data&type=seguro_viaje&"+$('#form_seguro_viaje').serialize();
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/eval_contratar_servicio.php",
			data:data,
			async: true,
			success: function(response){
				var v_result = response.split("|");
				if(v_result[0]=='1'){ // 0 ya esta contratado el servicio
					data = data+'&servicePriceCurrency='+v_result[1]+'&servicePrice='+v_result[2];
					//envia datos a php para que los guarde en $_SESSION
					$.ajax({
						type:"POST",
						url: WEB_PATH + "app/ajax/contratar_servicio.php",
						data:data,
						async: true,
						success: function(response){
							hideLoading();
							window.location.href = WEB_PATH + "mi_suat/servicio/cons/seguro_viaje";
						}
					});
				}else{
					hideLoading();
					var msj = 'Según nuestros registros ya tienes contratado el seguro de viajero. Por más información comunicate a <a href="mailto:mensajes@suat.com.uy?subject=subject"> mensajes@suat.com.uy</a> o llamá al 2711 0 711 . ';
					show_alert('ERROR', msj, 'goBack', false, false);
					//console.log('el usuario ya tiene contratado el servicio solicitado');
				}
			}
		});
	}
}

/**
 * evalua que la persona nacida en birthday , este dentro del rango de edad comprendido entre minYear y maxYear
 *
 * @param birthday fecha de nacimiento
 * @param minYear Int edad minima
 * @param maxYear  Int edad maxima
 * @return Boolean  true si la edad es mayor a minYear y menor a maxYear, false en caso contrario
 */
function evalBirthday(birthday, minYear, maxYear){
    now = new Date();
	var arr_date = birthday.split(" - ")

	var year;
    year = parseInt(arr_date[0],10);

	var month
    month = parseInt(arr_date[1],10);

	var day
    day = parseInt(arr_date[2],10);

	//resto los años de las dos fechas
    edad = now.getFullYear() - year - 1; //-1 porque no se si ha cumplido años ya este año

    if (now.getMonth() + 1 - month > 0){
       edad = edad + 1
	}else if(now.getUTCDate() - day >= 0  && ( (now.getMonth() + 1 - month) == 0) ){
		edad =  edad + 1
	}

	if(edad < maxYear && edad >minYear) {
		return true;
	}else{
		return false;
	}
}

/**
 * recarga el select de ciudda segun el departamento seleccionado
 */
function refreshCiudad(){
	//var id = $('#departamento').val();
	var id = $('#deparetamentos').val();

	$.ajax({
		dataType:'json',
		type:"POST",
		url: WEB_PATH + "app/ajax/loadCiudad.php",
		data:"departamento_id="+id,
		async: true,
		success: function(response){
			$('#ciudades').prev().html(response['show_first']);
			$('#ciudades').html(response['options']);
		}
	});
}

/**
 * contrata un servicio ,  esta funcion es llamada al aceptar las condiciones del contrato
 */
function confirm_contract(type){
	//window.location.href = WEB_PATH + "mi_suat/pay/"+type;
	$.ajax({
		type:"POST",
		url:WEB_PATH + "app/ajax/contratar_servicio.php",
		data:'action=contratar&type='+type,
		async: true,
		success: function(response){
			var v_result = response.split("|");
			if(v_result[0]=='0'){
				show_alert('', MSG_SYSTEM_ERROR+" Error:#54878772", 'goHome', false, false);
			}else if(v_result[0]=='1'){
				window.location.href = WEB_PATH + "mi_suat/pay/"+type;
			}else  if(v_result[0]=='-1'){
				console.log('no estan los datos de session ');
			}else{
				show_alert('', MSG_SYSTEM_ERROR+" Error:#5656512", 'goHome', false, false);
			}
		}
	});
}

function acceptConcent(){
	$('.tef-md-register').show();
	$('.tef-gu').hide();
}

function cancelConcent(token){
	$('#form_registro_password').hide();
	$.ajax({
		type:"POST",
		url: WEB_PATH + "app/ajax/cancelar_registro.php",
		data:"token="+token,
		async: true,
		success: function(response){
			if(response == 1  ){
				window.location.href = WEB_PATH + "mi_suat/";
			}else{
				//console.log(MSG_SYSTEM_ERROR+" Error:#68500062");
			}
		}
	});

}

/*
function sendServiceForm(type){
	console.log("sendServiceForm , :" + type);
	$.ajax({
			type:"POST",
			url:WEB_PATH + "app/ajax/contratar_servicio.php",
			data:'action=contratar&type='+type+"&"+$('#form_'+type).serialize(),
			async: true,
			success: function(response){
				var v_result = response.split("|");
				if(v_result[0]=='0'){
					$('#service_msg_error').html(MSG_LOGIN_ERROR);
				}else if(v_result[0]=='1'){
					$('#service_msg_error').html('en un rato actualizamos los datos, cualquier cosa pasa por bedelia');
					//window.location.href = WEB_PATH + "mi_suat/";
				}else{
					$('#service_msg_error').html(MSG_SYSTEM_ERROR+" Error:#5885411");
				}
			}
		});
}*/

/********************* AGENDA MEDICA *********************************/

function init_agenda(){
	init_datePicker_future();
	init_datePicker_tomorrow();
	//$(".datepicker").change(agenda_hideForm);
	/*if( IS_WORST_BROWSER){
		//$("#libreta_tipo").css("width", "auto");
	}*/
	//$("p").slideToggle("slow");
	$('.showForm').click(agenda_showForm);
}

/**
 * oculta el formulario correspondiente para "carné de salud" o "libreta de conducir" seleccionado
 * se utiliza para hacer que el usuario seleccione buscar , asi se actualiza el formulario , con los nuevos datos
 *
 * esta funcion no se esta usando ,  en su lugar se agrega en agenda_showForm la linea input_date.change(agenda_showForm);  par que
 * el formulario se actualice al cambiar la fecha
 */
function agenda_hideForm(){
	var form = $(this).parent().parent();
	form.parent().parent().children('.form_hidden').html("");
}

/**
 * despliega el formulario correspondiente para "carné de salud" o "libreta de conducir" seleccionado
 * TODO :  esta funcion ya no se usa mas,  dado que solo pueden pedir para el usuario logeado, lo que implica que no voy
 * a necesitar datos extras
 */
function agenda_showForm(){
	var form = $(this).parent().parent();

	var agendaType = form.find('[class*=agendaType]').val();
	var anexo_id = form.find('[class*=anexo]').val();
	var input_date = form.find('[class*=datepicker]'); // datepicker

	if (inputIsEmpty(input_date.attr('id'))) {
		$('.error').html('');
		form.children('.error').html(MSG_COMPLETAR_FECHA);
		input_date.focus();
		form.parent().parent().children('.form_hidden').html("");
	}else if(anexo_id == '0'){
		form.children('.error').html(MSG_COMPLETAR_ANEXO);
		form.parent().parent().children('.form_hidden').html("");
	}else{
		form.children('.error').html("");
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/agenda_medica.php",
			data:"action=get_form&type="+agendaType+"&anexo="+anexo_id+"&date="+input_date.val(),
			async: true,
			success: function(response){
				//form.parent().parent().children('.form_hidden').hide();
				form.parent().parent().children('.form_hidden').html(response);
				input_date.change(agenda_showForm); // al modificar la fecha actualizo el formulario
				form.children('p').children('select').change(agenda_showForm);
				//form.parent().parent().children('.form_hidden').show("slow");
				//form.parent().parent().children('.form_hidden').slideDown("slow");
				Custom.init();
				init_datePicker_past();
				init_datePicker_single();
				//Custom.clear();
			}
		});
	}


}

/**
 * realiza una reserva en Agenda ( desde la seccion 'Agenda Medica')
 *
 * id: Int id de agenda
 */

function reserve_in_book(id,id_asis, hour, date, place){
	showLoading(true);
	$.ajax({
		type:"POST",
		url: WEB_PATH + "app/ajax/agenda_reservar.php",
		data:"agendaId="+id+"&id_asis="+id_asis+"&hora="+hour+"&date="+date+"&place="+place+"&"+$('#form_personal_data').serialize(),
		async: true,
		success: function(response){
			hideLoading();
			var data = response.split("|");
			if(data[0] == '0' ){
				show_alert('ATENCIÓN', data[1], 'goHome', false, false);
			}else if(data[0] == '-1' ){ // el usuario no esta loggeado
				hideLoading(function(){
					showMiSuatLogin(false,'');
				});
			}else if(data[0] == '1' ){
				//show_alert('', MSG_RESERVAR_HORA_OK, 'goHome', false, false);
				$('.detail').html(data[1]);
			}
		}
	});
}

/**
 * realiza una reserva para papanicolau
 *
 * response:
 *		-2 : usuario de genero masculino
 *		-1 : El usuario no esta loggeado
 *		 1 : Se agendo.
 *		 2 : No existe la agenda.
 *		 3 : No se puede agendar, no quedan cupos libres.
 *		 4 : El lugar, fecha y hora seleccionado ya fue reservado. Por favor reserve nueva fecha y hora.
 *		 5 : No coincide la fecha y hora con la agenda.
 *		 6 : Debe ingresar el nro. de teléfono
 *		 7 : Debe ingresar el tipo y nro. de documento de identidad
 *		 8 : Debe ingresar el nombre de la persona
 *		 9 : Debe ingresar el apellido de la persona
 *		10 : Debe seleccionar la fecha y hora del exámen
 *
 */
function reserve_pap(id, place, date, hour){
	//showLoading(true);
	$.ajax({
		type:"POST",
		url: WEB_PATH + "app/ajax/agenda_reservar_pap.php",
		data:"agendaId="+id+"&place="+place+"&date="+date+"&hour="+hour,
		async: true,
		success: function(response){
			//hideLoading();
			var data = response.split("|");
			if(data[0] == '1' ){ // se reservo la hora correctamente
				$('.detail').html(data[1]);
			}else if(data[0] == '-1' ){ // el usuario no esta loggeado
				//show_alert('ERROR', 'nop !!!', 'goHome', false, false);
				hideLoading(function(){
					showMiSuatLogin(false,'');
				});
			}else if(data[0] == '-2' ){ // el usuario es de genero masculino
				show_alert('ERROR', eval('MSG_RESERVAR_PAP_GENERO_ERR'), 'goHome', false, false);
			}else if(data[0] == '2' || data[0] == '3' || data[0] == '4' ){
				show_alert('ERROR', eval('MSG_RESERVAR_PAP_'+data[0]), 'goHome', false, false);
			}else{
				//errores del sistema :
				show_alert('ERROR', MSG_SYSTEM_ERROR+' id:5641 - e:'+data[0], 'goHome', false, true);
			}
		}
	});
}

/**
 * realiza una reserva para cursos
 * curso_type  tipo de curso,  'Curso Primeros Auxilios' | 'Curso RCP'
 */
function reserve_curso(agendaId,curso_type, hour,place,date){
	showLoading(true);
	$.ajax({
		type:"POST",
		url: WEB_PATH + "app/ajax/agenda_reservar_curso.php",
		data:"agendaId="+agendaId+"&curso_type="+curso_type+"&hour="+hour+"&place="+place+"&date="+date,
		async: true,
		success: function(response){
			var data = response.split("|");
			if(data[0] != '-1') hideLoading();
			if(data[0] == '1' ){ // se reservo la hora correctamente
				$('.detail').html(data[1]);
			}else if(data[0] == '-1' ){ // el usuario no esta loggeado
				hideLoading(function(){
					showMiSuatLogin(false,'');
				});
			}else if(data[0] == '2' || data[0] == '3' || data[0] == '4' ){
				show_alert('ERROR', MSG_RESERVAR_PAP_+data[0], 'goHome', false, false);
			}else{
				//errores del sistema :
				show_alert('ERROR', MSG_SYSTEM_ERROR+' id:564881 - e:'+data[0], 'goHome', false, true);
			}
		}
	});
}

/**
 * envia los datos de formulario para solicitar hora en agenda medica para [Papanicolau | Curso | Carné de salud |Ficha Medica| Ficha Medica ]
 * lista las horas disponibles
 * Int type tipo de servicio que se quiere reservar
 *
 * type :
 *	 pap: papanicolau
 *	 curso: curso
 *   1: Carné de salud- adulto
 *   2: Carné de salud- pediatrico
 *   3: Ficha Médica deportiva adulto
 *   4: Ficha Médica deportiva pediatrica
 */
function get_schedules(type){

	var correct_form = true;
	var typeName ;
	var gender_id =  $("#gender").val();
	if(type == 'pap' || type == 'curso' ){
		correct_form = eval('eval_form_'+type+'()');
		typeName = type;
	}else if(type == 1 ){
		typeName = 'carne';
		type = $("#carne_type").val();
		//Esto es temporal por el momento no lo quieren usar.
		if (type == 2) {
			correct_form = false;
			show_alert('ATENCIÓN', 'Este servicio por el momento sólo puede reservarse a través del 27110711 de lunes a viernes de 9 a 19 hrs. Gracias por utilizar nuestros servicios on line.', 'NothingsGonnaChangeMyWorld', false, false);

		} else {correct_form = eval_form_carne(type);}


	}else if(type == 3 ){
		correct_form = eval_form_ficha(type);
		typeName = 'fichaM';
		type = $("#fichaM_type").val();
		//gender_id =  $("input[name='gender_ficha']:checked").val();
	}else{
		typeName = type;
	}

	if(correct_form){
		showLoading(true);
		$.ajax({
			type:"POST",
			url: WEB_PATH + "app/ajax/agenda_medica.php",
			data:"action=get_list&type="+type+'&gender_id='+gender_id+'&'+$('#form_agenda_'+typeName).serialize(),
			async: true,
			success: function(response){
				if (response == '-1') {
					//Usuario no esta logueado
					var callb = "hideLoading(function(){showMiSuatLogin(false,'');});";
					showalert2('ATENCIÓN', 'Para acceder a nuestros servicios on line debes ser un usuario registrado en Mi SUAT. Gracias por utilizar nuestros servicios online', callb, false, false);
					/*hideLoading(function(){
						showMiSuatLogin(false,'');
					});*/
				} else {
					hideLoading();
					var data = response.split("|");
					if(data[0] == 1){
						$(".first").html(data[1]);
					}else{
						$('.error').html("");
						show_alert('ATENCIÓN', data[1], 'NothingsGonnaChangeMyWorld', false, false);
						//$('#msg_error_'+typeName).html(data[1]);
					}
			}
				scroll(0,0);
			}
		});
	}else{
		return;
	}
}

/**
 * valida los campos para el formulario de carne de salud
 * @return Boolean  true si el formulario es valido,  false en caso contrario
 */
function eval_form_carne(type){
	var err_display = $('#msg_error_carne');
	if (inputIsEmpty('carne_datepicker')){
		err_display.html(MSG_COMPLETAR_FECHA);
		$('#carne_datepicker').focus();
	}else if(type == 1 && evalBirthday($('#birthday').val(), 0, 14)){
		//err_display.html(MSG_ERROR_CARNE_ADULTO);
		show_alert('ATENCIÓN', MSG_ERROR_CARNE_ADULTO, 'NothingsGonnaChangeMyWorld', false, false);

	}else if(type == 2 && evalBirthday($('#birthday').val(), 14, 150)){
		//err_display.html(MSG_ERROR_CARNE_PEDIATRICO);
		show_alert('ATENCIÓN', MSG_ERROR_CARNE_PEDIATRICO, 'NothingsGonnaChangeMyWorld', false, false);

	}else{
		return true;
	}
	return false;
}

/**
 * valida los campos para el formulario de ficha medica
 * @return Boolean  true si el formulario es valido,  false en caso contrario
 */
function eval_form_ficha(type){

	var err_display = $('#msg_error_fichaM');
	if (inputIsEmpty('fichaM_datepicker')){
		err_display.html(MSG_COMPLETAR_FECHA);
		$('#fichaM_datepicker').focus();
	}else if(type == 3 && evalBirthday($('#birthday').val(), 0, 14)){
		err_display.html(MSG_ERROR_FICHA_ADULTO);
	}else if(type == 4 && evalBirthday($('#birthday').val(), 14, 150)){
		err_display.html(MSG_ERROR_FICHA_PEDIATRICO);
	}else if ($('#ficha_anexo').val() < 1){
		err_display.html(MSG_COMPLETAR_ANEXO);
		$('#ficha_anexo').focus();
	}else{
		return true;
	}
	return false;
}


/**
 * valida los campos del formulario para reserva de pap
 * @return Boolean  true si el formulario es valido,  false en caso contrario
 */
function eval_form_pap(){
	//var form = $('#form_agenda_pap');
	if (inputIsEmpty('pap_datepicker')) {
		$('#msg_error_pap').html(MSG_COMPLETAR_FECHA);
		$('#pap_datepicker').focus();
	}else if ($('#pap_anexo').val() < 1) {
		$('#msg_error_pap').html(MSG_COMPLETAR_ANEXO);
		$('#pap_anexo').focus();
	}else{
		return true;
	}
	return false;
}

/**
 * valida los campos del formulario para reserva de cursos
 * @return Boolean  true si el formulario es valido,  false en caso contrario
 */
function eval_form_curso(){
	//var form = $('#form_agenda_pap');
	if ($('#curso').val() < 1) {
		$('#msg_error_curso').html(MSG_COMPLETAR_CURSO);
		$('#curso').focus();
	}else{
		return true;
	}
	return false;
}


/**
 * oculta el div de formulario para agenda medica
 * int type  id del tipo de formulario seleccionado
 */
function reset_booking_form(type){
	//$('#form_'+type).parent().hide();
	$('#form_agenda_'+type).parent().html('');
	//$('#form_'+type).parent().slideUp("slow");
}

/****************************************************************************************/

/*
 *  ventana para alertas
 * title <String> : titulo de la alerta
 * description <String> : texto a desplegar
 * callBack <Function> :  funcion a ejecutar cuando se seleccione aceptar
 * cancelar <Boolean> : true si se muestra boton de cancelar , false en caso contrario
 * alerta <Boolean> : true si el mensaje es una alerta,  false si el mensaje es una notificacion
 */
function show_alert(title, description, callBack, cancelar, alerta){
	var c = (cancelar) ? "1" : "";
	var a = (alerta) ? "1" : "";
	var wb = (IS_WORST_BROWSER)?"1" : "";
	var url = WEB_PATH+"app/ajax/alert.php?title="+title+"&description="+description+"&a_js="+callBack+"&type="+a+"&c="+c+"&wb="+wb;
	ajax_div(url, false);
}

function showalert2(title, description, callBack, cancelar, alerta){
	var c = (cancelar) ? "1" : "";
	var a = (alerta) ? "1" : "";
	var wb = (IS_WORST_BROWSER)?"1" : "";
	var url = WEB_PATH+"app/ajax/alertLogin.php?title="+title+"&description="+description+"&a_js="+callBack+"&type="+a+"&c="+c+"&wb="+wb;
	ajax_div(url, false);
}


function hide_alert()
{
	$('#ajax_div').hide();
	if ($('#ajax_div').attr('enabled') == 'true') {
		$('#ajax_div').attr('enabled', 'false');
		$("#ajax_div").show();
	} else {
		$('#overlay').hide();
	}
}

/**
 * crea un div transparente del tamaño de la pagina
 */
function createBg(){
	var bgdiv = $('<div>').attr({
		className: 'bgtransparent',
		id: 'bgtransparent'
	});

	// agregos nuevo div a la pagina
	$('body').append(bgdiv);

	// ancho y alto de la ventana del browser
	var wscr = $(window).width();
	var hscr = $(window).height();

	//establezco las dimensiones del fondo
	$('#bgtransparent').css("width", wscr);
	$('#bgtransparent').css("height", hscr);
	$('#bgtransparent').css("position","fixed");
	$('#bgtransparent').css("left","0");
	$('#bgtransparent').css("top","0");
	$('#bgtransparent').css("background","#000");
	$('#bgtransparent').css("opacity","0.6");
	$('#bgtransparent').css("z-index","90");
	$('#bgtransparent').hide();

}

function showAnimation(){
	// ancho y alto de la ventana del browser
	var wscr = $(window).width();
	var hscr = $(window).height();
	var wcnt = $('#loader_ajax').width();
	var hcnt = $('#loader_ajax').height();

	var mleft = ( wscr - wcnt ) / 2;
	var mtop = ( hscr - hcnt ) / 2;

		// estableciendo el loader en el centro
	$('#loader_ajax').show();
	$('#loader_ajax').css("position","fixed");
	$('#loader_ajax').css("left", mleft+'px');
	$('#loader_ajax').css("top", mtop+'px');
}

/**
 * muestra el div transparente , en caso de que no este creado, llama a createBg() ,  asigna el evento resize
 */
function showBg(){
	if($('#bgtransparent').length == 0){
		createBg();
	}
	$('#bgtransparent').show();
	$('#bgtransparent').animate({opacity:0.6},0);
	//$('#bgtransparent').animate({opacity:0.8},500);
	//$(window).resize(bgResize);
}

function hideBg(cb){
	var func_cb = (cb)?cb:null;
	$('#bgtransparent').animate({opacity:0},500,function(){
		$('#bgtransparent').hide('1',func_cb);
	});
	$(window).unbind('resize');
}

/**
 * oculta el div transparente, remueve el evento resize
 */
function bgResize(){
	// dimensiones de la ventana del browser
	var wscr = $(window).width();
	var hscr = $(window).height();
	// estableciendo dimensiones de fondo
	$('#bgtransparent').css("width", wscr);
	$('#bgtransparent').css("height", hscr);
}


//Popup con Ajax
function ajax_div(url, callback){
	if (!jQuery.isReady) return;
	if ($('#ajax_div').size() == 0) {
		$("<div id='ajax_div'></div>").appendTo("body");
	}
	$.ajax({
		type: "POST",
		url: url,
		async: true,
		data:"",
		success: function(response) {
			$('#ajax_div').html(response);
			show_div("ajax_div");
		}
	});
}

/**
 * muestra el gif de loading....
 * BG indica si se debe usar cortina de fondo o no
 */
function showLoading(BG){
	if(BG){
		showBg();
	}
	showAnimation();
	//$('#bgtransparent').fadeTo(1, 0.5);
}

/**
 * oculta el gif de loading....
 */
function hideLoading( function_cb){
	var cb = (function_cb)?function_cb:null;
	hideBg(cb);
	$('#loader_ajax').hide();
	/*$('#bgtransparent').fadeTo(500,0,function(){
		$('#bgtransparent').hide();
	});
	*/
}
