/************************
Autor:Jose Luis Sagredo P
************************/

/*********** Eventos A ***********/
$(document).ready(function(){
						   
$("a[ref=pop]").bind("click", function() {
   window.open($(this).attr('href'),$(this).attr('title'),'width=520,height=340,scrollbars=yes');
   return false;
}); 

$("a[ejecutar=false]").bind("click", function(e) {
	e.preventDefault();
});

}); 

/************ CARACTERES PERMITIDOS **********/
$(document).ready(function(){
$("input[validar]").each(function(cant)
{
	$(this).keypress(function(event)
	{
		var tecla = (document.all) ? event.keyCode : event.which;
		if (tecla==8) return true;
		if (tecla==0) return true;
		var te = String.fromCharCode(tecla);
		var patron = $(this).attr('validar');
		
		for (var i=0; i < patron.length; i++)
		{
			if(patron.charAt(i)==te)
			{
				var estado=true;
			}
		}
		if(estado==true)
		{
			return true;
		}
		else
		{
			return false;
		}
	});		
});
});

/************ FORMATO PERMITIDOS **********/
$(document).ready(function(){
$("input[formato]").each(function(cant)
{
	$(this).change(function()
	{
		var patron = $(this).attr('formato');
		var formato = new RegExp(patron);
		
		if(formato.test($(this).val())==true)
		{
			return true;
		}
		else
		{
			if($(this).attr('msn')!=undefined)
			{
				alert($(this).attr('msn'));
			}
			else
			{
				alert("El valor ingresado no es valido");
			}
			$(this).val("");
			return false;
		}
	});	
});
});
jQuery.url = function(url)
{
	location.href=url;
}
/********** CODE URL ***********/
/********** URL ENCODE ************/
jQuery.encode = function(plaintext){
	var SAFECHARS = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "!~*'()";
	var HEX = "0123456789ABCDEF";
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ )
	{
		var ch = plaintext.charAt(i);
	    if (ch == " ")
		{
			encoded += "+";
		}
		else 
		{
			if (SAFECHARS.indexOf(ch) != -1)
			{
				encoded += ch;
			}
			else
			{
				var charCode = ch.charCodeAt(0);
				if (charCode > 255)
				{
					//alert( "Unicode Character '"+ ch + "' cannot be encoded using standard URL encoding.\n" + "(URL encoding only supports 8-bit characters.)\n" + "A space (+) will be substituted." );
					encoded += "+";
				}
				else
				{
					encoded += "%";
					encoded += HEX.charAt((charCode >> 4) & 0xF);
					encoded += HEX.charAt(charCode & 0xF);
				}
			}
		}
	}
	return encoded;
}
/************ URL DESCODE****************/
jQuery.decode = function(encoded)
{
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Combinacion erronea ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};
/************ COOKIE ***************/
/**

$.cookie('the_cookie', 'the_value');
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
$.cookie('the_cookie', null);

*/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*************** VALIDAR ***************/
// INPUT ->		if($.vari({id:"nombre",type:"input",msn:"El Nombre no puede estar vacio"})==false){return false;}
// FILE  ->		if($.vari({id:"img",type:"file",msn:"Debe ingresar un imagen",ex:"jpg,gif,png"})==false){return false;}
// EMAIL ->		if($.vari({id:"email",type:"email",msn:"El Mail no puede estar vacio"})==false){return false;}
// TEXTAREA ->	if($.vari({id:"mensaje",type:"textarea",msn:"El Mensaje no puede estar vacio"})==false){return false;}
// SUBMIT ->	$.vari({id:"formulario",type:"submit",action:"axn_guardar.php?accion=guardar",method:"post"});

jQuery.vari = function(opciones_root)
{
    opciones_default = {
		id:false,
		ref:false,
		type:"input",
		msn:"Falta llenar un dato",
		action:"index.php",
		method:"post",
		enctype:"multipart/form-data",
		con:"false"
    }

    opciones = jQuery.extend(opciones_default , opciones_root);


/*****************************/
if(opciones.type=="input")
{
	if($('#'+opciones.id).val() == "")
	{
		alert(opciones.msn);
		$('#'+opciones.id).focus();
		return false;
	} 
	else
	{
		return true;
	}
}
/*****************************/
if(opciones.type=="textarea")
{
	if($('#'+opciones.id).val() == "")
	{
		alert(opciones.msn);
		$('#'+opciones.id).focus();
		return false;
	} 
	else
	{
		return true;
	}
}
/*****************************/
if(opciones.type=="link")
{
	var re=/^(ht|f)tp(s?)\:\/\/(www\.|[0-9a-zA-Z\_\d]{3,1000})[0-9a-zA-Z\_\-\d]*\.[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?\/?([a-zA-Z\.\_\/\?\#\%\&\-\=\d\+]*)?$/;
	if(re.test($('#'+opciones.id).val()) == "false")
	{
		alert(opciones.msn);
		$('#'+opciones.id).focus();
		return false;
	} 
	else
	{
		return true;
	}
}
/*****************************/
if(opciones.type=="email")
{
	if($('#'+opciones.id).val() == "")
	{
		alert(opciones.msn);
		$('#'+opciones.id).focus();
		return false;
	} 
	else
	{
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($('#'+opciones.id).val()))
		{
			return true;
		}
		else
		{
			
		alert("Debes escribir un Email valido.");
			$('#'+opciones.id).focus();
			return false;
		}
	}
}
/*****************************/
if(opciones.type=="CK")
{
	var texto=CKEDITOR.instances[opciones.id].getData();
	if(texto=='<p></p>' || texto=='' || texto=='<p> </p>')
	{
		return false;
	}
	else
	{
		return true;
	}
}
/*****************************/
if(opciones.type=="submit")
{
	$('#'+opciones.id).attr('action',opciones.action);
	$('#'+opciones.id).attr('method',opciones.method);
	$('#'+opciones.id).attr('enctype',opciones.enctype);
	
	if(opciones.con=="yes")
	{
		var resp=confirm(opciones.msn);
		if (!resp)return false ;
	}
	
	$('#'+opciones.id).submit();
}
/*****************************/
if(opciones.type=="file")
{
	if(opciones.con=="yes")
	{
		if($('#'+opciones.id).val()=="")
		{
			return true;
		}
	}
	var ext=opciones.ex.split(','); 
	var ext_activa=$('#'+opciones.id).val().substring($('#'+opciones.id).val().lastIndexOf(".")+1).toLowerCase();
	var _return=''; 
	for (i=0;i<ext.length;i++)
	{
		if(ext_activa==ext[i].toLowerCase())
		{
			_return='true';
		}
	}
	if(_return!='true')
	{
			alert(opciones.msn);
			$('#'+opciones.id).attr('value','');
			$('#'+opciones.id).focus();
			return false;
	}
}
/*****************************/
}

jQuery.fn.app_var = function(opciones_root)
{
    opciones_default = {
		type:"input",
		msn:"Falta llenar un dato",
		confirmar: false,
		action:"index.php",
		method:"post"
    }

    opciones = jQuery.extend(opciones_default , opciones_root);

/********************** INPUT ***************************/
	if(opciones.type=="input")
	{
		if(this.val() == "")
		{
			alert(opciones.msn);
			this.attr('value','');
			this.focus();
			return false;
		} 
		else
		{
			return true;
		}
	}
/********************** FILE ***************************/	
	if(opciones.type=="file")
	{
		if(opciones.confirmar==true)
		{
			if(this.val()==""){return true;}
		}
		
		var ext=opciones.ex.split(','); 
		var ext_activa=this.val().substring(this.val().lastIndexOf(".")+1).toLowerCase();
		var _return='';
		
		for (i=0;i<ext.length;i++)
		{
			if(ext_activa==ext[i].toLowerCase())
			{
				_return='true';
			}
		}
		
		if(_return!='true')
		{
			alert(opciones.msn);
			this.attr('value','');
			this.focus();
			return false;
		}
	}
/********************* EMAIL **********************/
	if(opciones.type=="email")
	{
		if(this.val() == "")
		{
			alert(opciones.msn);
			this.attr('value','');
			this.focus();
			return false;
		} 
		else
		{
			if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(this.val())){return true;}
			else{alert("Debes escribir un Email valido.");this.attr('value','');this.focus();return false;}
		}
	}
/******************** TELEFONO ********************/
	if(opciones.type=="telefono")
	{
		if(this.val() == "")
		{
			alert(opciones.msn);
			this.attr('value','');
			this.focus();
			return false;
		} 
		else
		{
			if (/([0-9\s\+\(\)]+)?([\-\.0-9]{7,8})/.test(this.val())){return true;}
			else{alert("Debes escribir un Telefono valido.");this.attr('value','');this.focus();return false;}
		}
	}
/******************** SUBMIT ********************/	
	if(opciones.type=="submit")
	{
		this.attr('action',opciones.action);
		this.attr('method',opciones.method);
	
		if(opciones.confirmar==true)
		{
			var resp=confirm(opciones.msn);
			if (!resp)return false ;
		}
		
		this.submit();
	}

}


jQuery.app_load = function(opciones_root)
{
    opciones_default = {
		type:"post",
		url:false,
		data: '',
		inicio_ejecutar: function(){},
		fin_ejecucion: function(){},
		fin_ejecucion_true: function(){},
		error: function(){},
		cargar: function(html){}
    }

    opciones = jQuery.extend(opciones_default , opciones_root);

	$.ajax({
        url: opciones.url,
		data: opciones.data,
        async:true,
        beforeSend: function(objeto){opciones.inicio_ejecutar();},
        complete: function(objeto, exito){
            opciones.fin_ejecucion();
            if(exito=="success"){opciones.fin_ejecucion_true();}
        },
        error: function(objeto, quepaso, otroobj){
            opciones.error();
        },
        global: true,
        ifModified: false,
        processData:true,
        success: function(datos){
            opciones.cargar(datos);
        },
        type: opciones.type
	});

}

jQuery.fn.app_select = function(opciones_root)
{
    opciones_default = {
		id:false,
		ajax:false,
		msn:"",
		msn_pie: "",
		cargar: function(data){}
    }

    opciones = jQuery.extend(opciones_default , opciones_root);
	
	var id=this.attr('id');
	
	if(opciones.ajax!=true)
	{
		$("#"+id+" dt a").bind("click", function(e)
		{
			e.preventDefault();
			$("#"+id+" dd ul").toggle();
		});
		
		$(document).bind('click', function(e) 
		{
			var $clicked = $(e.target);
			if (! $clicked.parents().is("#"+id+"")){$("#"+id+" dd ul").hide();}
		});	
	}
	
	if(opciones.id!=false)
	{
		$('#'+opciones.id).val('');
	}
	
	$("#"+id+" dd ul li a").bind("click", function(e)
	{
		e.preventDefault();
		var text = $(this).html();
		$("#"+id+" dt a span").html(text);
		$("#"+id+" dd ul").hide();
		if(opciones.id!=false)
		{
			$('#'+opciones.id).val(opciones.msn+$(this).attr('val')+opciones.msn_pie);
		}
		opciones.cargar(opciones.msn+$(this).attr('val')+opciones.msn_pie);
	});

	
}

