function show_div(div_id, text){
    $('#'+div_id).html(text);
    $('#'+div_id).show();
}

function disable_imgs_rightclick(){ // llamar en document.onready
    for (var i = 0; i < document.images.length; i++)
        document.images[i].oncontextmenu = function(){return false;};
}

function is_email(str){
    var filtro = /^[A-Za-z][A-Za-z0-9_.-]*@[A-Za-z0-9_.-]+\.[A-Za-z0-9_.]+[A-za-z]$/;
    if (filtro.test(str)) return true;
    else return false;
}

function is_date(date_string){
    // matches DD/MM/Y or DD/MM/YYYY or D/M/Y or DD/M/YYYY Leap years treated.
    var reg_expr = /^(((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00|[048])))$/;
    if (!reg_expr.test(date_string))
        return false;
    return true;
}

function validate_cedula(str){
    // Valida el formato con puntos y guion (1.234.567-8), los puntos son opcionales
    // Retorna FALSE si es valida, TRUE si el formato es incorrecto
    var error = true;
    var reg_expr = /^[1-9][\.]?[0-9]{3}[\.]?[0-9]{3}[\-][0-9]$/;
    if (!reg_expr.test(str))
        error = false;
    return error;
}

function popup_locked(url, w, h){
    win = window.open(url, '', 'width='+w+',height='+h+',toolbar=no,menubar=no,scrollbars=yes,resizable=no');
    win.moveTo(window.screen.availWidth / 2 - w / 2, window.screen.availHeight / 2 - h / 2);
}

function text_optimize(str){
    // replace with unicode characters:
    str = str.replace('á', '\u00E1');
    str = str.replace('é', '\u00E9');
    str = str.replace('í', '\u00ED');
    str = str.replace('ó', '\u00F3');
    str = str.replace('ú', '\u00FA');
    return str;
}

function urlencode(str){
    var result = "";
    for (i = 0; i < str.length; i++) {
        if (str.charAt(i) == " ") result += "+";
        else result += str.charAt(i);
    }
    return escape(result);
}

function in_array(needle, haystack, argStrict){
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack)
            if (haystack[key] === needle)
                return true;
    }else{
        for (key in haystack)
            if (haystack[key] == needle)
                return true;
    }
    return false;
}

function find_position(obj){
    var curleft = curtop = 0;
    if (obj.offsetParent){
        do{
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }while (obj = obj.offsetParent);
    }
    return [curleft, curtop];
}

/**************** Efectos Inputbox ****************/
// Inicializar un input con un texto predeterminado
function _initInput(input_id, text_ini){	
    input = $("#"+input_id);
    input.val(text_ini);
    input.attr("text_ini", text_ini);
    input.focus(function(){
        if ($(this).val() == $(this).attr("text_ini")) $(this).val("");
    });
    input.blur(function(){
        if ($(this).val() == "") $(this).val($(this).attr("text_ini"));
    });
    input.getTexto = function(){
        return $(this).val();
    };
}

function inputIsEmpty(input_id){
    input = $(input_id);
    if (input.attr("type")=="radio")
        return !$('input[name='+input.attr("name")+']').is(':checked');
    else
        return (input.val() == "" || input.val() == input.attr("text_ini"));
}

// Efecto de texto que aparece y desaparece. Llamar dentro de document.ready
function text_blur_focus(input_id, default_text){
    $('#'+input_id).blur(function(){
        if ($('#'+input_id).val() == '') $('#'+input_id).val(default_text);
    });
    $('#'+input_id).focus(function(){
        if ($('#'+input_id).val() == default_text) $('#'+input_id).val('');
    });
}

//Limpiar un formulario: los input del tipo hidden NO los borra =)
function clean_form(id_form){
    var all_inputs = $("#"+id_form+" :input");
    all_inputs.each(function(){
        if ($(this).attr('type') != 'hidden') {
            $(this).val('');
            $(this).blur();
        }
    });
}

/**************** Fin Efectos Inputbox ****************/
String.prototype.trim = function() {
	return this.replace(/^\s+/, '').replace(/\s+$/, '');
};

/******************* Popup con Ajax **********************/
function ajax_div(url, callback){
    if (!jQuery.isReady) return;
    $("<div id='ajax_div'></div>").appendTo("#full");
    $.ajax({
            type: "GET",
            url: url,
            data: {PHPSESSID : PHPSESSID},
            success: function(response) {
                    $('#ajax_div').html(response);
                    show_div("ajax_div");
                    if (callback) eval(callback).call();
            },
            error: function (errorCode, textStatus, errorThrown) {
                    if (errorCode.status == 450) session_perdida();
            }
    });
}

//Lee una URL enviando los parametros por POST
//Si allmessage=FALSE, la funcion retorna el contenido json de "message"
//Si allmessage=TRUE, la funcion retorna todo el contenido json enviado por el remitente
function loadURL(url, params, allmessage){
    var globvarajax;
    $.ajax({
            type:"POST",
            dataType: "json",
            url: url,
            data: params,
            async: false,
            success: function(data){
                    if(data.error == 0 ){
                        if(allmessage)
                            globvarajax = data;
                        else
                            globvarajax = data.message;
                    }else{
                        globvarajax = false;
                    }
            }
    });
    return globvarajax;
}

function gotoPage(url){
    if (url!='')
        document.location=url;
    else
        document.location.reload();
}

//Valida de que sea un entero >0
function validID(value){
    for (i = 0 ; i < value.length ; i++) {
        if ((value.charAt(i) < '0') || (value.charAt(i) > '9')) return false;
    }
    if (value<1) return false;
    return true;
}

// Crea un formulario oculto dentro de la pagina y envia la informacion por POST
function sendPost(url, params, idobject){
    if (idobject==null) idobject='#doc';

    $("#autosendform").remove();

    var myform ='';
    myform =myform+'<form id="autosendform" method="post" action="'+url+'">';
    var arr = params.split('&');
    for(var pos in arr){
        var variable=arr[pos];
        var arr2 = variable.split('=');
        myform =myform+'<input type="hidden" name="'+arr2[0]+'" value="'+unescape(arr2[1])+'" />';
    }
    myform =myform+'</form>';
    myform =myform+'<script type="text/javascript">$("#autosendform").submit();</script>';
    $(idobject).append(myform);
}

//Esta funcion carga en la URL del navegador datos extra sin que se recarge la pagina
//Los datos que carga es mediande un anchor #...., mediante la funcion checkCargarProducto() se toman esos datos
//y se carga la url del producto.
//Todo esto es para que, en el caso de cargar detalle de productos mediante AJAX, la url cambie y el usuario puede copiarla
//y pegarla en un navegador y se vea el detalle del producto
function changeUrl(url){
    if ($.browser.msie) return true;
    var urlactual=window.location.href;
    urlactual = urlactual.replace(/(#|\?)(.*?)*/g,'');

    var suburl = url.substr(0, urlactual.length)
    if (suburl==urlactual){
        suburl = url.substr(urlactual.length)
        location.hash=suburl;
    }
}

function showTextAlert(objName, texto, tiempo, message_type){
    //Esto es por si quiero mostrar un texto justo cuando el anterior se esta acultando
    tiempo = (typeof tiempo == 'undefined') ? 5000: tiempo;

    message_type = (typeof message_type == 'undefined') ? 'error': message_type;
    if (message_type=='error'){
        $(objName).addClass('error_message');
        $(objName).removeClass('success_message');
    }else{
        $(objName).removeClass('error_message');
        $(objName).addClass('success_message');
    }
    //tiempo = tiempo || 5000;
    $('.error_message').each(function(){
        if($(this).is(':animated'))
            $(this).stop(true, true);
        $(this).hide();
    });
    $(objName).html(texto);
    $(objName).show();
    if (tiempo>0)
        $(objName).delay(tiempo).fadeOut('slow');
}

function showMessage(input_id, message_id, message, message_type){
    message_type = (typeof message_type == 'undefined') ? 'error': message_type;

    showTextAlert(message_id, message, 0, message_type);
    if (message_type=='error'){
        $(input_id).parent().addClass('error_input');
    }else{
    }
    $(input_id).focus();
}

function enviarFormularioAjax(url, objform, allmessage){
    var globvarajax;
    $.ajax({
            type:"POST",
            dataType: "json",
            url: url,
            data: $(objform).serialize(),
            async: false,
            success: function(data){
                    if(data.error == 0 ){
                        if(allmessage)
                            globvarajax = data
                        else
                            globvarajax = data.message;
                    }else{
                        globvarajax = false;
                    }
            }
    });
    return globvarajax;
}

function borrarformulario(form){
	$(form+' input[type=text]').val("");
	$(form+' input[type=password]').val("");
	$(form+' input[type=radio]').attr('checked', false);
	$(form+' textarea').val("");
	$(form+' select').val("");
	$(form+' select').parent().find('span').remove();
	Custom.init();
}

function desactivarBoton(boton){
	$(boton).removeAttr('href');
	$(boton).mouseover(function(){$(this).css("text-decoration", "none");})
}

