$(document).ready(function(){
   
    validForm();
    if(returnSubmit != null){
        returnSubmitPhp();
    }
    setMasksInputs();
    inputFocus();
    limitTextarea();

    $("#btFecha").click(function(){hideMessage()});

    $('input[control=cnpj]').blur( function() {
        if ($(this).val() == "") {
            $(this).val('CNPJ');
        }
    });

    $('input[control=cnpj]').focus( function() {
        if ($(this).val() == 'CNPJ') {
            $(this).val('');
        }
    });

    $('#cpfConvidado').blur( function() {
        if ($(this).val() == "") {
            $(this).val('CPF');
        }
    });

    $('#cpfConvidado').focus( function() {
        if ($(this).val() == 'CPF') {
            $(this).val('');
        }
    });

    $('input[control=senha]').focus( function() {
        if ($(this).val() == 'Senha') {
            $(this).val('');
        }
    });

    $("#senhaEmpresa").keypress(function(event){
        if (isCapsLock(event)) {
            $('#strongMessage').html(message.MN072);
            $('#divMessage').addClass('notice');
            $('#divMessage').show();
        }else{
            $('#divMessage').hide();
        }
    });

    $("#senhaConvidado").keypress(function(event){
        if (isCapsLock(event)) {
            $('#strongMessage').html(message.MN072);
            $('#divMessage').addClass('notice');
            $('#divMessage').show();
        }else {
            $('#divMessage').hide();
        }
    });

    $('input[control=senha]').blur( function() {
        if ($(this).val() == "") {
            $(this).val('Senha');
        }
    });

    $('#tx_email').blur( function() {
        if ($(this).val() == "") {
            $(this).val('E-mail');
        }
    });

    $('#tx_email').focus( function() {
        if ($(this).val() == 'E-mail') {
            $(this).val('');
        }
    });

});

function validA(){
    $("#form").find('input,select,textarea .required').filter(':enabled').each(function() {
        alert($(this).attr('id'));
    });
}

function validFormAjax(callbackSuccess, id_form){

    callbackSuccess = (callbackSuccess) ? callbackSuccess : null;
    id_form = (id_form) ? id_form : '#form';

   //hideMessage();

    $(id_form).validate({
        submitHandler: function(form) {
            jQuery(form).ajaxSubmit({
                success: function(response){
                    hideMessage();
                    if(callbackSuccess != null){
                        callbackSuccess(response);
                    }
                }
            });
        },
        /*
        errorPlacement: function(error, element) {
            alert($(error).html());
        },
        onfocusin: function(element) {
            return;
		},/*
		onfocusout: function(element) {
            return;
		},*//*
		onkeyup: function(element) {
            return;
		},
		onclick: function(element) {
            return;
		},
		highlight: function( element, errorClass, validClass ) {
            this.errorList = [this.errorList[0]];
            return;
		},
		unhighlight: function( element, errorClass, validClass ) {
            return;
		}*/
/*
        errorPlacement: function(error, element) {
            alert($(error).html());
        },*/
        onfocusin: function(element) {
            return;
		},/*
		onfocusout: function(element) {
            return;
		},*/
		onkeyup: function(element) {
            return;
		},
		onclick: function(element) {
            return;
		},
		highlight: function( element, errorClass, validClass ) {
            if(this.errorList.length > 1)
                this.errorList = [this.errorList[0]];
            return;
		},
		unhighlight: function( element, errorClass, validClass ) {
            if(this.errorList.length > 1)
                this.errorList = [this.errorList[0]];
            return;
		}
    });
}

function returnSubmitPhp(){
    //alert(print_r(returnSubmit.sendData));
    if(returnSubmit.message != ''){
        showMessage(returnSubmit.message, returnSubmit.type);
    }
    if(returnSubmit.sendData){
    	
        $("#form").populate(returnSubmit.sendData);
    }
}

function showMessage(message, type){
    type = (type) ? type : 'notice';
    $('#strongMessage').html(message);
    $('#divMessage').addClass(type);
    $('#divMessage').show();
    $('#divMessage').focus();
}

function hideMessage(){
    $('#strongMessage').html('');
    $('#divMessage').hide();
}

function validForm(id_form){
    id_form = (id_form) ? id_form : '#form';
    var _options = {/*
        errorPlacement: function(error, element) {
            alert($(error).html());
        },*/
        onfocusin: function(element) {
            return;
		},/*
		onfocusout: function(element) {
            return;
		},*/
		onkeyup: function(element) {
            return;
		},
		onclick: function(element) {
            return;
		},
		highlight: function( element, errorClass, validClass ) {
            if(this.errorList.length > 1)
                this.errorList = [this.errorList[0]];
            return;
		},
		unhighlight: function( element, errorClass, validClass ) {
            if(this.errorList.length > 1)
                this.errorList = [this.errorList[0]];
            return;
		}
    }
    $(id_form).validate(_options);
}

function setMasksInputs(){

    $('.date').mask("99/99/9999");
    $('.hours').mask("99:99");
    $('.cnpj').mask("99.999.999/9999-99");
    $('.cpf').mask("999.999.999-99");
    $('.phone').mask("9999-9999");
    $('.phone-ddd').mask("(99)9999-9999");
    $('.cep').mask("99.999-999");
    $('.ddd').mask("99");
    $('.ncm').mask("9999.99.99");
    $('.digits').numeric();
    $('.money').priceFormat({prefix: '',centsSeparator: ',',thousandsSeparator: ''});
    $('.datepicker').datepicker({dateFormat: 'dd/mm/yy', showOn: 'button', buttonImage: baseUrl + '/public/img/global/btCalendario.gif', buttonImageOnly: true});

    $('.url').each(function(){
        $(this).focus(function(){
            if($.trim($(this).val()) == ''){
                $(this).val('http://')
                $(this).focus();
            }
        }).blur(function(){
            if($.trim($(this).val()) == 'http://'){
                $(this).val('')
            }           
        });
    });
    
}

function inputFocus() {

	var setFocus = false;
    if($("#form").is(':visible')){
        if($("#form").attr('focus') != 'no') {
            $("#form").find('input,select,textarea').filter(':enabled').each(function() {
                if(!setFocus) {
                    switch(this.getAttribute('type')) {
                        case 'hidden':
                        case 'submit':
                            break;
                        default:
                            setFocus = true;
                            this.focus();
                            return;
                    }
                }
            });
        }
    }
}

function transfersOptions(from, to){
    var fromOptions = $("#" + from + " option:selected");
    var opts = '';
    var opt;
    for(var i = 0; i< fromOptions.length; i++){
        opt = $(fromOptions[i]);
        if(opt.val() != ''){
            opts += '<option label="'+ opt.text() + '" value="' + opt.val() + '">'+ opt.text() + '</option>'
        }
    }
    $("#" + to).append(opts);
    $("#" + from + " option:selected").remove();
}

function populateCombo(idCombo, arr){
    /*
    document.getElementById(idCombo).options.length = 0;
    for (var v in arr) {
        var lengthCombo = document.getElementById(idCombo).options.length;
        document.getElementById(idCombo).options[lengthCombo]
            = new Option (arr[v],v, true, true);
    }
    document.getElementById(idCombo).selectedIndex = 0;*/

    var html = '';
    for (var v in arr) {
        html += '<option value="'+ v +'">' + arr[v] + '</option>'
    }
    $('#' + idCombo).html(html);

}


function isCapsLock(ev) {
	var e = ev || window.event;
	codigo_tecla = e.keyCode?e.keyCode:e.which;
	tecla_shift = e.shiftKey?e.shiftKey:((codigo_tecla == 16)?true:false);
	if(((codigo_tecla >= 65 && codigo_tecla <= 90) && !tecla_shift) || ((codigo_tecla >= 97 && codigo_tecla <= 122) && tecla_shift)) {
		return true;
	}
	else {
		return false;
	}
}

function print_r( input, _indent )
{
     // Recuo

     var indent            =    ( typeof( _indent ) == 'string' ) ? _indent + '    ' : '    '
     var parent_indent    =    ( typeof( _indent ) == 'string' ) ? _indent : '';

     var output            =    '';

     // Tipo de Elemento do Array

     switch( typeof( input ) )
     {
         case 'string':
             output        =    "'" + input + "'\n";
         break;

         case 'number':
             output        =    input + "\n";
         break;

         case 'boolean':
             output        =    ( input ? 'true' : 'false' ) + "\n";
         break;

         case 'object':
             output        =    ( ( input.reverse ) ? 'Array' : 'Object' ) + "\n";

             output       +=    parent_indent + "(\n";

             for( var i in input )
             {
                 output +=    indent + '[' + i + '] => ' + print_r( input[ i ], indent );
             }

             output       +=    parent_indent + ")\n"
         break;
     }

     return output;
}

function showThis( botao ) {
	$(botao).removeClass('hide');
}

function hideThis( botao ) {
	$(botao).addClass('hide');
}

function loadMuda(url, textAba){

    $("#muda").load(url);
    
    if(textAba){
        $("#aConteudo").text(textAba);
        $("#aConteudo").attr('href', url);
        $("#liConteudo").removeClass('hide');

        $(".abaLink").removeClass('abaAtivo');
        $(".abaLink").addClass('abaInativo');
        $("#liConteudo").addClass('abaAtivo').removeClass('abaInativo');
        $("#liVazia").addClass('hide');
    }

}

function redirect(url){
    url = baseUrl + '/' + url;
    window.location = url;
}

function formatDate(date){
    var sep1 = '-';
    var sep2 = '/';
    if( date.indexOf("/") != -1 ){
        sep1 = '/';
        sep2 = '-';
    }
    date = date.split(sep1);
    date = date.reverse();
    date = date.join(sep2);
    return date;
}


function wordWrap(_str, _width){
    _width = (_width) ? _width : 100;
    var _caracter = "<br />";
    var _length = _str.length;
    if( _length > _width){
        var _quebra = (_length / _width);
        var _ini = 0;
        var _fim = _width;
        var _nova = '';
        for(var _i=0; _i <= parseInt(_quebra, 10); _i++){
            if(_i == parseInt(_quebra, 10)){
                _nova += _str.substr(_ini, _width);
            }else{
                _nova += _str.substr(_ini, _width) + _caracter;
            }
            _ini = _fim;
            _fim = (_fim + _width);
        }
        return _nova;
    } else {
        return _str;
    }
}

