(function($){
    $.fn.log = function (msg)
    {
      console.log("%s: %o", msg, this);
      return this;
    };
})(jQuery);


$.strPadLeft = function(i,l,s) {
    var o = i.toString();
    if (!s) {s = '0';}
    while (o.length < l) {
            o = s + o;
    }
    return o;
};



String.prototype.trim = function()
{
    string = this.replace(/^\s+/, '');
    for (var i = string.length; i > 0; i--) {
            if (/\S/.test(string.charAt(i))) {
                    string = string.substring(0, i);
                    break;
            }
    }
    return string;
};

function ajaxLoadingBUI()
{
	$.blockUI({ 
		message: '<div class="ajaxLoader">Aguarde un momento por favor...</div>',
		onUnblock: null,
		css: { 
			border: 'none', 
			padding: '15px', 
			backgroundColor: '#000', 
			'-webkit-border-radius': '10px', 
			'-moz-border-radius': '10px', 
			opacity: '1', 
			color: '#fff'
		}		
	});	
}


function bindBtnCloseBUI()
{
	$('.btnCloseBUI').click(function(){
		$.unblockUI();
		$(this).unbind('click');
	});
}


function loadModulo(obj, idContainer)
{
    $(obj).addClass('active');
    loadModuloFNC($(obj).attr('data-Url'), idContainer);
}


function loadModuloFNC(modulo, idContainer)
{
    ajaxLoadingBUI();
    $.get( modulo,
              {  },
              function(data){
                    $('#' + idContainer).html(data);
                    $.unblockUI();
    });
}


function ajaxError(idContainer)
{
	$('#' + idContainer).ajaxError(function(event, request, settings)
	{
            $.get('/includes/ajaxError.php',
                      {
                       url: settings.url
                      },
                      function(data){
                              $('#' + idContainer).html(data);
            });

	});
	$.unblockUI();
}


function bloquearPantalla(mensaje, autoClose)
{

	if(!autoClose)
		mensaje = mensaje + '<br /><input type="button" class="btnCloseBUI" value="Cerrar" />';

    $.blockUI({
        message: mensaje,
        onUnblock: null,
        css: {
            top: '10%',
            left: '25%',
            width: '50%',
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: '1',
            color: '#fff'
        }
    });

	if(!autoClose)
		bindBtnCloseBUI();
}



function habilitarPantalla()
{
    var pos = $("#wrapper").offset();
    $("html").animate(
    {
        scrollTop: pos.top + "px"
    },

    {
        duration: 1000
    }, setTimeout($.unblockUI, 1100)
        );
	
}


function jqGridFixWidth()
{
    $('div.GridHeader').width('100%');
    $('div.userdata').width('100%');
    $('div.grid_hdiv').width('100%');
    $('div.grid_bdiv').width('100%');
    $('div[id^=tbl].scroll').width('100%');
}


function jqRowSelected(jqGridID)
{
    var s;
    s = $('#' + jqGridID).getGridParam('selrow');
    return s;
}

function jqGridUniqueRow(jqGridID)
{
    var s = ($('#' + jqGridID).getGridParam('multiselect') == true) ? $('#' + jqGridID).getGridParam('selarrrow') : new Array($('#' + jqGridID).getGridParam('selrow'));
    if(($(s).length != 1) || s[0] == null)
    {
        bloquearPantalla('<div align="right" class="buiError"><h1>Seleccione un &uacute;nico registro</h1></div>', false);
        return false;
    }

    return true;
}

function jqGridSelected(jqGridID)
{
    var s = $('#' + jqGridID).getGridParam('selarrrow');
    if($(s).length <= 0)
    {
        bloquearPantalla('<div align="right" class="buiError"><h1>Seleccione registros</h1></div>', false);
        return false;
    }

    return true;
}



function doDow(dow)
{
    for(var i = 0; i < dow.length; i++)
    {
    //console.log(dow[i]);
    eval(dow[i]);

    }
}


function ckEditorOverLoad()
{
    delete CKEDITOR;
}

function ckEditorBeforeSend()
{
    /*
    try
    {
        // Remove old non-existing editors from memory
        for(var name in CKEDITOR.instances)
        {
            //console.log(name);
            if($('#' + name).length==0)
                delete CKEDITOR.instances[name];
        };

        // loop through editors
        for(var name in CKEDITOR.instances)
        {
            var instancia = CKEDITOR.instances[name];
            var data = instancia.getData(true);//this.content(name);
            $('#' + name).text( data );
        };
    }
    catch(e)
    {
        //console.log(e);
        alert(e);
        return(false);
    }
    */

}


function ckFinderBrowseServer( startupPath, functionData, selectFunction, selectThumbnailFunction )
{
	// You can use the "CKFinder" class to render CKFinder in a page:
	var finder = new CKFinder() ;

	// The path for the installation of CKFinder (default = "/ckfinder/").
	finder.BasePath = '../includes/ckfinder/' ;

	//Startup path in a form: "Type:/path/to/directory/"
	finder.StartupPath = startupPath ;

	// Name of a function which is called when a file is selected in CKFinder.
	finder.SelectFunction = selectFunction ;

	// Additional data to be passed to the SelectFunction in a second argument.
	// We'll use this feature to pass the Id of a field that will be updated.
	finder.SelectFunctionData = functionData ;

	// Name of a function which is called when a thumbnail is selected in CKFinder.
	finder.SelectThumbnailFunction = selectThumbnailFunction ;

	// Launch CKFinder
	finder.Popup() ;
}

// This is a sample function which is called when a file is selected in CKFinder.
function ckFinderSetFieldValue( fileUrl, data )
{
    $('#' + data['selectFunctionData']).val(fileUrl);

    var sFileName = decodeURIComponent( fileUrl.replace( /^.*[\/\\]/g, '' ) ) ;
    $('div#thumb' + data['selectFunctionData']).append('<img class="thumb" src="' + fileUrl + '" />' + '<div class="caption">' + '<a href="' + data["fileUrl"] + '" target="_blank">' + sFileName + '</a> (' + data["fileSize"] + 'KB)');

    return false;

}

// This is a sample function which is called when a thumbnail is selected in CKFinder.
function ckFinderShowThumbnails( fileUrl, data )
{
    var sFileName = decodeURIComponent( fileUrl.replace( /^.*[\/\\]/g, '' ) ) ;
    $('div#' + data['selectFunctionData']).append('<img src="' + fileUrl + '" />' + '<div class="caption">' + '<a href="' + data["fileUrl"] + '" target="_blank">' + sFileName + '</a> (' + data["fileSize"] + 'KB)');
    // It is not required to return any value.
    // When false is returned, CKFinder will not close automatically.
    return false;
}


function ckFinderAppendFieldValue( fileUrl, data )
{
    var fld = $('#' + data['selectFunctionData']);
    var $contenedor = $('#' + $(fld).attr('data-IdContenedor'));
    var fldName = $(fld).attr('data-FieldName');
    
    var sFileName = decodeURIComponent( fileUrl.replace( /^.*[\/\\]/g, '' ) );
    
    $contenedor.append('<div class="contenedorThumb"><input type="hidden" name="' + fldName + '" value="' + fileUrl + '"><img class="thumbAdmin" src="' + fileUrl + '" />' + '<div class="caption">' + '<a href="' + fileUrl + '" target="_blank">' + sFileName + '</a> (' + data['fileSize'] + 'KB) <img class="rem" src="' + CONF_URL_DIR_IMG + '/cross.png"></div>');
    $('img.rem', $contenedor).click(function(){
        $(this).parent().parent().fadeOut('normal', function(){
            $(this).remove();
        })
    });
    return false;

}

