$.fn.clearForm = function() {
    return this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input',this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};
	
$.fn.serializeForm = function() {
    var string = "";
    var value  = "";
    $(this).find("input,textarea,select").each(function(){
        if($(this).val()!=null){
            value = $(this).val();
            value = value.replace(/\+/g,'%2B'); //Url encode '+' symbol
        }
        else{
            value="";
        }
        if(this.type=='checkbox' && this.checked==false){
            value = "";
        }
        string += (string==''?"":"&")+($(this).attr("name")+"="+ encodeURIComponent(value) );
    });
    return string;
};
	
$.fn.serializeFormDescriptions = function() {
    var string = "";
    var value  = "";
    $(this).find("input,textarea,select").each(function(){
        if($(this).attr("title")!=null){
                value = $(this).attr("title");
                value = value.replace(/\+/g,'%2B'); //Url encode '+' symbol
        }
        else{
                value="";
        }
        string += (string==''?"":"&")+($(this).attr("name")+"_desc="+ encodeURIComponent(value) );
    });
    return string;
};
	
function stripAlphaChars(pstrSource){ 
    var m_strOut = new String(pstrSource);
    m_strOut = m_strOut.replace(/[^0-9.,]/g, '');
    return m_strOut;
}

function convertUnicodetoHtmlEntities(string){
    string = string.replace(/[\u00A0-\u2666]/g, function(c) { //Convert unicode to html entities
            return '&#'+c.charCodeAt(0)+';';
    });
    return string;
}
	
$.fn.image = function(src, f){ 
    return this.each(function(){
        var i = new Image();
        i.src = src;
        i.onload = f;
        this.appendChild(i);
    });
}; 
	 
$.clientHeight = function(){
    if(window.innerHeight){
        return window.innerHeight;
    }
    else{
        return document.documentElement.clientHeight;
    }
};
	 
$.clientWidth = function(){
    if(window.innerWidth){
        return window.innerWidth;
    }
    else{
        return document.documentElement.clientWidth;
    }
};

$.fn.addAjaxLoader=function(){
    var w = $(this).outerWidth();
    var h = $(this).outerHeight();
    var paddingLeft = parseInt($(this).css("paddingLeft"));
    var paddingTop  = parseInt($(this).css("paddingTop"));

    if(typeof(DIR_IMG_ABSOLUTE) == "undefined"){
        window.DIR_IMG_ABSOLUTE = 'images/';
    }

    if($(this).find(".ajax_loader").length==0){
        $(this).prepend('<div style="position:relative;"><div class="ajax_loader" style="z-index:9999;position:absolute;top:'+(paddingTop > 0?'-'+paddingTop+'px':"0px")+';left:'+(paddingLeft > 0?'-'+paddingLeft+'px':"0px")+';margin:0px;padding:0px;width:'+w+'px;height:'+h+'px; background: url('+DIR_IMG_ABSOLUTE.replace(/ /g,"%20")+'admin/ajax-loader.gif) no-repeat center center  #FFFFFF;filter: alpha(opacity=60);opacity:0.6"></div></div>');
    }
};

$.fn.removeAjaxLoader=function(){
    $(this).parent().find(".ajax_loader").parent().remove();
};
	 
function emailCheck (emailStr) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    return reg.test(emailStr) == false?false:true;
}
	 
function checkDate(y,m,d){
    y=document.getElementById(y);
    m=document.getElementById(m);
    d=document.getElementById(d);
    if(m.value==2){
        if(y.value % 4==0){
            if(d.value>29){
                d.value=29;
            }
        }
        else{
            if(d.value>28){
                d.value=28;
            }
        }
    }
    else{
        if(m.value==4||m.vlaue==6||m.value==9||m.value==11){
            if(d.value>30){
                d.value=30;
            }
        }
    }
}	
	 

function checkFormFields(frm,animate_fields,animate_msg){ //(formulario, array de campos a validar,idioma,animar(1|0)?,mostrar alerta(1|0)?)
    var msg="";
    var verify = true;
    var show_alert  = false;
    var lengthMessage = "";
    var required_color = "#FFFFFF";
    var required_background = "#FF0000";

    //Iterate form elements
    $("#"+frm+" input,#"+frm+" select,#"+frm+" textarea,#"+frm+" div").each(function(){

        //Save element reference
        var _this = $(this);

        //Set name attr = "" in case it's not defined
        if($(this).attr('name') == undefined || $(this).attr('name') == null)$(this).attr("name","");

        //Check if element is required
        if($(this).hasClass("required")){
            
            //Check element status. If status = 1, element is already highlighted
            if(parseInt(_this.data('status')) != 1){
               
                //If element type is hidden. Commonly used to save the selected value of a radio buttons set.
                if($(this).attr('type') == 'hidden'){

                    _this.data("color",_this.parent().css("color"));
                    _this.data("backgroundColor",_this.parent().css("backgroundColor"));
                    
                }
                else{

                    _this.data("color",_this.css("color"));
                    _this.data("backgroundColor",_this.css("backgroundColor"));
                    
                }
                
            }

            //If element is a captcha input, check if element value is correct.
            if(_this.attr('id').indexOf('captcha')!=-1){
                callback = function(el,animate_fields,animate_msg,required_background,required_color){
                    if(animate_fields==1 && parseInt(el.data("status")) != 1){
                        el.data("status",1);
                        if(animate_msg!=1){
                            el.effect("highlight", {color:required_color},1000,function(){});
                        }
                        else{
                            el.css("backgroundColor",required_background);
                            el.css("color",required_color);
                        }
                    }
                }

                isCaptchaCodeCorrect($(this),callback,[_this,animate_fields,animate_msg,required_background,required_color]);
                
            }
            //Input string length
            var valueLength = (_this.val()+"").length;
            //Input min allowed length
            var minLength = 0;
            //Input max allowed length
            var maxLength = 0;
            //Length error flag
            var lengthError = false;
            //Populate class flag
            var populate = false;
           

            //Get input max length
            if($("#"+$(this).attr("id")+"_maxLength").length > 0){
                maxLength = $("#"+_this.attr("id")+"_maxLength").val();
            }

            //Get input min length
            if($("#"+$(this).attr("id")+"_minLength").length>0){
                minLength = $("#"+_this.attr("id")+"_minLength").val();
            }

            if( (maxLength!=0 && valueLength > maxLength) || (minLength!=0 && valueLength < minLength) ){
                if(minLength>0 && maxLength>0){
                    if(minLength!=maxLength){
                        lengthMessage += "<br /><i>"+$(this).attr("title")+" "+txt_must_have+" ["+minLength+" "+txt_to_a+" "+maxLength+"] "+txt_digits+"</i>";
                    }
                    else{
                        lengthMessage += "<br /><i>"+_this.attr("title")+" "+txt_must_have+" "+maxLength+" "+txt_digits+"</i>";
                    }
                }
                else if(minLength>0){
                    lengthMessage += "<br /><i>"+_this.attr("title")+" "+txt_must_have_at_least+" "+minLength+" "+txt_digits+"</i>";
                }
                else{
                    lengthMessage += "<br /><i>"+_this.attr("title")+" "+txt_can_not_have_more_than+" "+maxLength+" "+txt_digits+"</i>";
                }
                lengthError = true;
            }

            //Has auto populated text
            if(_this.attr("title") == _this.val() && _this.attr('title')!=''){
                populate = true;
            }

            
            
            if( populate || lengthError || (jQuery.trim(_this.val())=='' || (_this.attr('name').toLowerCase().indexOf('email')!=-1 && !emailCheck(_this.val())) || (_this.attr('type')=='checkbox' && !_this.attr('checked')) ||  (_this.attr('id').lastIndexOf("_confirmation")!=-1 && _this.val()!= $("#"+_this.attr('id').replace("_confirmation","")).val())) && ( _this.parents(".no_display").length==0 ) ){

                show_alert = true;
                msg=msg+"\n"+_this.attr('title');
               
                if(_this.attr('type')=='hidden'){
                   
                    if(animate_fields==1 && parseInt(_this.data("status")) != 1){
                        _this.data("status",1);
                        if(animate_msg!=1){
                            _this.parent().effect("highlight", {color:required_background},1000,function(){
                                  _this.data("status",0);
                            });
                        }
                        else{
                            _this.parent().css("backgroundColor",required_background);
                            _this.parent().css("color",required_color);
                        }
                    }
                }
                else if(_this.attr('type')!='checkbox' && _this.attr('type')!='radio' && !populate){
                   
                    if(animate_fields==1 && parseInt(_this.data("status")) != 1){
                       
                        _this.data("status",1);
                        if(animate_msg!=1){
                            _this.effect("highlight", {color:required_background},1000,function(){
                                _this.data("status",0);
                            });
                        }
                        else{
                            _this.css("backgroundColor",required_background);
                            _this.css("color",required_color);
                        }
                    }
                }
                else if((_this.attr('type')=='checkbox') && _this.attr('checked')!=true){

                    var type = _this.attr('type');
                   
                    var w=15;
                    var	h=15;

                    var style = _this.attr("style");
                    var className = _this.attr("class");
                    var title = _this.attr("title");
                    var chk_id = "chk_"+new Date().getTime();
                    var div = '<div onclick="$(this).replaceWith(\'<input title=&quot;'+_this.attr('title')+'&quot; id=&quot;'+_this.attr('id')+'&quot;  checked=&quot;checked&quot; class=&quot;'+className+'&quot; type=&quot;'+type+'&quot;/>\');" class="'+className+'" title="'+title+'" style="background-color:#FF0000;height:'+h+'px;width:'+w+'px"></div>';

                   _this.replaceWith(div);

                   $("#"+chk_id).click(function(){
                        var chk = '<input checked="checked" type="'+type+'" class="'+className+'" style="'+style+'" title="'+title+'"/>';
                        $(this).replaceWith(chk);
                    });
                    
                }
               

                if(!populate){

                    if(_this.attr('type') == 'hidden'){
                       
                        _this.parent().find(':radio').one("click", function(){
                            $(this).data("status",0);
                            $(this).parent().css("backgroundColor",_this.data("backgroundColor"));
                            $(this).parent().css("color",_this.data("color"));
                        });

                    }
                    else{
                        
                        _this.one("click focus keypress", function(){
                            $(this).data("status",0);
                            $(this).css("backgroundColor",_this.data("backgroundColor"));
                            $(this).css("color",_this.data("color"));
                        });
                        
                    }
                   
                }
                
            }
        }
    });

    if(show_alert){
        if(animate_fields!=1){
            msg = txt_complete_required_fields+": "+msg;
            alert(msg);
        }
        else{
            if(animate_msg==1){
                lengthMessage = lengthMessage!=''?'<div style="margin:0px 0px 10px 5px;">'+lengthMessage+'</div>':'';
                showAlertMessage(txt_complete_required_fields+lengthMessage,"error",1);
            }
        }
        return false;
    }
    else{
        return true;
    }
}

function getTranslateEntry(word,callback){
    var post_url = "";
    if(typeof(DIR_AJAX_ADMIN) == "undefined"){
        post_url = RELATIVE_PATH+"ajax/_ajax_translate.php";

    }
    else{
        post_url = DIR_AJAX_ADMIN+"_ajax.php";
    }

 
    var translation="";
    $.ajax({
        async: false,
        type: "POST",
        url: post_url,
        data: "opc=translate&word="+encodeURIComponent(word),
        success: function(data){
        translation = data;
            if(callback){
                callback.apply(this,[translation]);
            }
        }
    });
    return translation;
}

function getCleanFileName(filename,callback){
    callback = callback==undefined?false:callback;
    filename = filename.replace("&","%26");
    if(typeof(DIR_AJAX_ADMIN) == "undefined"){
        window.DIR_AJAX_ADMIN = '';
    }

    var post_url = '';
    if(typeof(DIR_AJAX_ADMIN) == "undefined"){
        post_url = RELATIVE_PATH+"ajax/_ajax.php";

    }
    else{
        post_url = DIR_AJAX_ADMIN+"_ajax.php";
    }

    $.ajax({
        async: true,
        type: "POST",
        url: post_url,
        data: "opc=getCleanFilename&filename="+filename,
        success: function(data){
            filename=data;
            if(callback){
                callback.apply(this,[filename]);
            }
        }
    });
}
		
	
function showAlertMessage(message,icon,close_on_click,close_all){
    /* ICONS:ajax,info,alert,error */
    var img_icon="";
    close_on_click = close_on_click == '' || close_on_click == undefined  ? false: close_on_click;
    close_all = close_all == '' || close_all == undefined  ? false: close_all;
    if(typeof(DOCUMENT_ROOT) == "undefined"){
        window.DOCUMENT_ROOT = RELATIVE_PATH;
    }
    if(icon=='ajax'){img_icon=DOCUMENT_ROOT+"images/admin/ajax-loader.gif";}
    else if (icon=='info'){img_icon=DOCUMENT_ROOT+"images/admin/icon-dialog-info.png"; color="#000";}
	else if (icon=='error'){img_icon=DOCUMENT_ROOT+"images/admin/icon-dialog-error.png"; color="#ff0000";}
	else if (icon=='password'){img_icon=DOCUMENT_ROOT+"images/admin/icon-dialog-password.png"; color="#ff0000";}
	else if (icon=='warning'){img_icon=DOCUMENT_ROOT+"images/admin/icon-dialog-warning.png"; color="#ff0000";}
	else{img_icon=DOCUMENT_ROOT+"images/admin/icon-dialog-warning.png"; color="#bd183b";}
	
	var html ='<div id="alert_msg" style="width:400px;background-color:#FFFFFF;border: 1px solid #999999; cursor:pointer;float:left" onclick="MySimpleLightBox.close('+(close_all?"true":"false")+');">';
	html+='<p style="align:center; margin:10px 0 5px 0;"><img src="'+DOCUMENT_ROOT+'images/bg/logo_lightbox.jpg"></p>';
	html+='<p style="font-family: Verdana, Arial, \'Trebuchet MS\',  Helvetica, sans-serif; font-size: 11px; color: '+color+'; text-align:center; line-height:1.3em; display:block; margin:0 20px 20px 20px;">'+message+'</p>';
	html+='</div>';
	
	MySimpleLightBox.border='1px solid #999999';
	MySimpleLightBox.loadHTML(html);

    $("#lbox").bind("click",function(){
        if(close_on_click){
                MySimpleLightBox.close();
        }
    });
}
		
function restrictInputLength(form_id){
    var inputs=null;
    if(form_id!='' && form_id!=undefined){
        inputs = $("#"+form_id+" input[type='text'],input[type='password'], textarea");
    }
    else{
        inputs = $("input[type='text'],input[type='password'], textarea");
    }
    inputs.each(function(){
        var maxlength = 0;
        var class_name = $(this).attr("class").split(" ");
        for(var i=0; i<class_name.length;i++){
            if(jQuery.trim(class_name[i]).indexOf("maxlength_")!=-1){
                maxlength = parseInt(jQuery.trim(class_name[i]).replace("maxlength_",""));
            }
        }

        if(maxlength > 0){
            $(this).keypress(function(evt){
                textCounter(this,maxlength,evt);
            });
            $(this).change(function(evt){
                textCounter(this,maxlength,evt);
            });

            if(document.all){
                this.onpaste = function(){
                    maxLengthPaste(this,maxlength);
                };
            }
            else{
                $(this).attr("oninput",'textCounter(this,'+maxlength+',event)');
            }
        }
    });
}
		
function maxLengthPaste(field,maxChars){
    event.returnValue=false;
    if((field.value.length + window.clipboardData.getData("Text").length) > maxChars){
       return false;
    }
    event.returnValue=true;
    return true;
} 
		
function textCounter(field,maxlimit,evento) {

    var ex=new Array('8','46','37','38','39','40','116');
    if(in_array(ex,evento.keyCode)){
        return;
    }
    if (field.value.length >= maxlimit){ // if too long...trim it!
        cancelEvent(evento);
        field.value = field.value.substring(0, maxlimit);
    }
}		
		
function in_array(arr,field){
    var i;
    for(i=0;i<arr.length;i++){
        if(arr[i].toLowerCase()==new String(field).toLowerCase()){
            return true;
        }
    }
    return false;
}
		
function onlyMoneyInputAllowed(e){
    var keynum;
    var keychar;
    var numcheck;
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = /\d/;

    if(numcheck.test(keychar)==false && keynum!=8 && keynum!=undefined){
        if(keychar=='.'){
            var input = eventTrigger(e);
            if(input.value.indexOf('.')!=-1){
                cancelEvent(e);
            }
        }
        else{
            cancelEvent(e);
        }
    }
}
		
function onlyIntegerInputAllowed(e){
    var keynum;
    var keychar;
    var numcheck;
    if(window.event){ // IE
            keynum = e.keyCode;
    }
    else if(e.which){ // Netscape/Firefox/Opera
            keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = /\d/;

    if((numcheck.test(keychar)==false && keynum!=8 && keynum!=undefined)){
            cancelEvent(e);
    }
} 


function eventTrigger (e) {
    if (! e) e = event;
    return e.target || e.srcElement;
}

function cancelEvent(e){
    if(navigator.userAgent.indexOf("MSIE")!=-1){
        e.returnValue=0;
    }
    if(navigator.userAgent.indexOf("Gecko")!=-1){
        e.preventDefault();
    }
}
		
function validateExtensions(file,ext,evt){
    var auxext=new String(file);
    var extPosibles;
    for (var i=0;i<ext.length;i++){
            if(i==0){
                    extPosibles=ext[i];
            }
            else{
                    extPosibles += ","+ext[i];
            }
    }
    auxext=auxext.substring(auxext.lastIndexOf('.')+1);
    if(!in_array(ext,auxext)){
        cancelEvent(evt);
        return false;
    }
    else{
        return true;
    }
} 
		
function isPointerInside(evt,el){
    var x = evt.pageX;
    var y = evt.pageY;
    var w = el.outerWidth();
    var h = el.outerHeight();
    var elX = el.offset().left;
    var elY = el.offset().top;

    if( (elX >(x+w) || elX<(x+w)) || (elY > (y+h) || elY<(y+h)) ){
        return false;
    }
    else{
        return true;
    }
}
