/*prototype extensions*********************************************************/
Date.prototype.addDays = function(n) {
    this.setTime(this.getTime()+n*86400000);
    return this;
};
/******************************************************************************/



;
(function($){
    $.CMUtils={};

    $.CMUtils.log = function(message){
        if( typeof(message)=="object"){
            message = $.json.encode(message);
        }

        if( typeof(console)!="undefined"){
            console.log(message);
        }
        return;
    },

    $.CMUtils.critical = function(message,p) {
        var params = $.extend({
            callback:false
        },p);

        /*message = message.indexOf('llave duplicada viola restricción de unicidad') !== -1
        ? 'Se esta intentando crear un elemento que ya existe'
        : message;*/


        $("body").append("<div class=\"critical\" title=\":::critical:::\">message</div>");

        $(".critical").html(message).dialog({
            bgiframe: true,
            modal: true,
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
                    $(".critical").remove();

                    if( params.callback ){
                        params.callback();
                    }
                }
            }
        });
    };

    $.CMUtils.information = function(message,p) {
        var params = $.extend({
            callback:false
        },p);

        //extendMessage = typeof(extendMessage)=="undefined"?"":"<br/>"+extendMessage;

        $("body").append("<div class=\"critical\" title=\":::information:::\">message</div>");

        $(".critical").html(message).dialog({
            bgiframe: true,
            modal: true,
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
                    $(".critical").remove();
                    if( params.callback!==false ){
                        params.callback();
                    } 
                }
            }
        });
    };

    $.CMUtils.question = function(message,op){
        op = typeof(op)!="undefined"?op:{};

        $("body").append("<div class=\"cmutils-question\" title=\":::question:::\">question</div>");

        $(".cmutils-question:last").html(message).dialog({
            bgiframe: true,
            modal: true,
            resizable: false,
            overlay: {
                backgroundColor: '#000',
                opacity: 0.5
            },
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
                    $(".cmutils-question").remove();

                    if( typeof(op['ok'])!="undefined"){
                        op['ok']();
                    }
                },
                Cancel: function(){
                    $(this).dialog('close');
                    $(".cmutils-question").remove();

                    if( typeof(op['cancel'])!="undefined"){
                        op['cancel']();
                    }
                }
            }
        });

    },

    $.CMUtils.redirect = function(loc){
        window.location = loc;
    },


    $.CMUtils.center = function(){
        return;
    },

    $.CMUtils.round=function(num,dec){
        var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
        return result;
    }


})(jQuery);

//*****************************************************************************/
var CMData={};

CMData.record = function(iobj){
    $ui = $(iobj);
    var r={};

    var oname='';
    var oval=null;
    var otype='';
    var otagName='';


    jQuery.each( $ui.find(":input").get() , function(){
        var $obj = $(this);

        var name = $obj.attr("name").replace("[]","");

        if( jQuery.trim(name)==''){
            return;
        }

        var val = $obj.val();

        tagName = $obj[0].tagName.toLowerCase();
        type = $obj.attr("type").toLowerCase();

        if( $obj.attr("name").indexOf("[]") > 0 && !jQuery.isArray(r[name]) ){
            r[name]=new Array();
        }


        if( tagName=="select" && val==null && $obj.attr("multiple")==true){
            r[name]=[];
            return;
        }

        if( jQuery.isArray(r[name]) && $obj.attr("multiple")!=true ){

            if( type=="checkbox" ){
                if( $obj.attr("checked")==true){
                    r[name].push(val);
                    return;
                }
            }
            else {
                r[name].push(val);
                return;
            }
        }
        else {

            if( $obj.hasClass("cmlib-formatcurrency") ){
                r[name] = $obj.asNumber();
                return;
            }

            if( type=="checkbox" && $obj.is(':checked')==false ) {
                return;
            }

            r[name] = val;
            return;
        }
    });

    /*
    jQuery.each( $ui.find(".cmlib-token-input-field").get() , function(){
        var $obj = $(this);
        
        var name = $obj.attr("name").replace("[]","");
        
        if( $obj.attr("name").indexOf("[]") > 0  ){
            if(!jQuery.isArray(r[name])){
                r[name]=[];
            }
            
            r[name].push( $obj.CMTokenInput('val') );        
            return;
        }
        
        
        r[name] = $obj.CMTokenInput('val');
        
    });
    */

    return r;
}

/******************************************************************************/
var CMConsole = {
    log:function(target){
        try {
            console.log(target);
        }
        catch(e){

        }
    }
};

/******************************************************************************/
var CMDialogBase = {
    __constructor:function(templateName){
        var self = this;
        //var $self = $(this);
        self.m_pr = {};
        self.m_class = templateName;

        self.settings = {
            modal: true,
            width: '400px',
            resizable:true,
            draggable:true,
            closeOnEscape:false,
            close: function(event,ui){
                self.widget().remove();

                
                if( self.settings.onClose!==undefined ){
                    self.settings.onClose();
                }
            }
        };

        $(".dialog-templates > "+templateName).clone().appendTo( $('body') );
        self.m_widget = $('body').find(templateName+":last");
        self.m_widget.hide();
        self.ui = {};

        self.m_widget.find(":input").each(function(){
            $this = $(this);
            var name = $this.attr("name");

            if( name.indexOf("[]") > 0 ){
                if( !jQuery.isArray(self.ui[name]) ){
                    self.ui[name]=[];
                }

                self.ui[name].push( $this );
            }
            else {
                self.ui[name] = $this;
            }
        });

        //JConsole.log(self.ui);
        return;
    },

    setParamRecord:function(pr){
        this.m_pr = pr;
        return;
    },

    record: function(){
        var self = this;
        return CMData.record( self.m_widget );
    },

    show:function(){
        var self = this;
        self.m_widget.dialog( self.settings );
    },

    widget: function(){
        return this.m_widget;
    },

    close:function(){
        var self = this;
        self.m_widget.dialog('close');
        return;
    },

    accept:function(){
        var self = this;
        self.close();
        if( self.settings.accept!==undefined ){
            self.settings.accept();
        }



    },

    reject:function(){
        var self = this;
        self.close();
        
        if( self.settings.reject!==undefined ){
            self.settings.reject();
        }


    }
};

var CMDialog = jQuery.inherit(CMDialogBase);



/******************************************************************************/
(function($){

    $.fn.CMFormatCurrency = function(options){
        var settings = $.extend({
            decimals:2
        },options);


        return this.each(function(){
            $this = $(this);
            var className = "cmlib-formatcurrency";

            if( $this.hasClass(className) ){
                $this.formatCurrency({
                    colorize: true,
                    negativeFormat: '-%s%n',
                    roundToDecimalPlace: $this.data('decimals')
                });
                return;
            }

            $this.addClass(className);
            $this.data('decimals',settings.decimals);

            // Format while typing & warn on decimals entered, 2 decimal places
            $this.blur(function() {
                $this.formatCurrency({
                    colorize: true,
                    negativeFormat: '-%s%n',
                    roundToDecimalPlace: settings.decimals
                });
            })
            .keyup(function(e) {
                var e = window.event || e;
                var keyUnicode = e.charCode || e.keyCode;
                if (e !== undefined) {
                    switch (keyUnicode) {
                        case 16:
                            break; // Shift
                        case 17:
                            break; // Ctrl
                        case 18:
                            break; // Alt
                        case 27:
                            this.value = '';
                            break; // Esc: clear entry
                        case 35:
                            break; // End
                        case 36:
                            break; // Home
                        case 37:
                            break; // cursor left
                        case 38:
                            break; // cursor up
                        case 39:
                            break; // cursor right
                        case 40:
                            break; // cursor down
                        case 78:
                            break; // N (Opera 9.63+ maps the "." from the number key section to the "N" key too!) (See: http://unixpapa.com/js/key.html search for ". Del")
                        case 110:
                            break; // . number block (Opera 9.63+ maps the "." from the number block to the "N" key (78) !!!)
                        case 190:
                            break; // .
                        default:
                            $(this).formatCurrency({
                                colorize: true,
                                negativeFormat: '-%s%n',
                                roundToDecimalPlace: -1,
                                eventOnDecimalsEntered: true
                            });
                    }
                }
            })
            .bind('decimalsEntered', function(e, cents) {
                if (String(cents).length > settings.decimals ) {
                    var errorMsg = 'Please do not enter any cents (0.' + cents + ')';
                    //$('#formatWhileTypingAndWarnOnDecimalsEnteredNotification2').html(errorMsg);
                    log('Event on decimals entered: ' + errorMsg);
                }
            });



        });
    }

    $.fn.CMFieldNumeric = function(unsigned){
        return this.each(function(){
            $this = $(this);

            $this.keypress(function (e) {
                var dash = '-';
                if((!unsigned && e.which!=0 && e.which!=8 && e.which!=45 && (e.which<48 || e.which>57)) || (unsigned && e.which!=0 && e.which!=8 && (e.which<48 || e.which>57))) {
                    return false;
                }

                if(e.which==45) {
                    var index = this.value.search(dash);
                    if (index !== -1 || index > 0) {
                        return false;
                    }
                } 

                return true;
            });
        });
    }

    $.fn.CMFieldNumericAll = function(){
        return this.find('.cmlib-field-numeric').CMFieldNumeric(false);
    }

    $.fn.CMFieldNumericUnSignedAll = function(){
        return this.find('.cmlib-field-numeric-unsigned').CMFieldNumeric(true);
    }

})(jQuery);

/******************************************************************************/

