Login   Register  
PHP Classes
elePHPant
Icontem

File: js/jquery.reconfig-1.0.js

Recommend this page to a friend!
Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Classes of giuseppe lucarelli  >  reconfig  >  js/jquery.reconfig-1.0.js  >  Download  
File: js/jquery.reconfig-1.0.js
Role: Auxiliary data
Content type: text/plain
Description: jquery plugin
Class: reconfig
Get configuration from files, pages and databases
Author: By
Last change: changed sone .attr with .prop
Date: 1 month ago
Size: 34,924 bytes
 

Contents

Class file image Download
/*
 * @$Header: /var/cvsroot/reconfig/js/jquery.reconfig-1.0.js,v 1.4 2014/11/10 12:34:31 giuseppe Exp $
 *
 * Date: 21 Feb 2012 
 */
(function ($) {
    $.fn.reconfig = function (options) {
/** if you don't specify any 'target' option take '$reconfig' as default: to set a new object (i.e.):
    exampledata = { settings: { items: null }};
    $('#samplediv').reconfig({target:exampledata,action: ['exec','build'],.....
*/
        if(typeof options.target == 'undefined') {
            _reconfig = $reconfig;
        } else {
            _reconfig = options.target;
            delete(options.target);
        }
        if(!(_reconfig instanceof Object)) {
            _reconfig = { settings: { items: null }};
        }
        if(typeof options.items != 'undefined') {
            _reconfig.settings.items = options.items;
        } else if($.reconfig.defaults.items == null) {
            options.items = [];
            this.each(function () {
                if(this.id != 'undefined' && this.id.length > 0) {
                    options.items.push(this.id);
                } else if($(this).attr('class') != 'undefined' && $(this).attr('class') == 'is_ml') {
                    options.items.push(this);
                }
            });
            _reconfig.settings.items = options.items;
        }
        return new reconfig(options);
    };
    reconfig = function (options) {
        var obj = this;
        var settings = $.extend({}, $.reconfig.defaults, options || {});
        $.extend(obj, {
            login: function (id,msg) {
// insert a 'link/button' to close/reset form and eventually destroy session
                var el = $('#'+id).attr('id');
                if(!$('#login_form').html()) {
                    var code = '<form method="post" action="" id="login_form"><div align="center"><div class="top" >'+(typeof msg != 'undefined' ? msg : 'Login')+'</div><div><span id="lusername" class="is_ml">User Name</span><input name="username" type="text" id="username" value="" maxlength="20" style="margin-left: 5px" /></div><div><span id="lpassword" style="margin-top:5px" class="is_ml">Password</span><input name="password" type="password" id="password" value="" maxlength="20" style="margin-left: 5px"/></div><div class="buttondiv"><input name="Submit" type="submit" id="submit" value="Login" style="margin-left:-10px; height:23px"  /> <span id="msgbox" style="display:none"></span></div></div></form>';
                    $(code).appendTo('#'+id);
//settings.auth_user = '';
//settings.auth_pass = '';
                    if(typeof settings.auth_user != 'undefined' && settings.auth_user != null)
                        $("#username").val(settings.auth_user);
                    if(typeof settings.auth_pass != 'undefined' && settings.auth_pass != null)
                        $("#password").val(settings.auth_pass);
                    if(typeof settings.do_before_login === 'function') {
                        settings.do_before_login(id);
                    }
                } else {
                    $('#login_form').show();
                }
	        $("#login_form").submit(function(event) {
                    event.preventDefault();
                    settings.action[0]='exec';
                    _reconfig.settings = settings;
                    $.reconfig.defaults.auth_user=_reconfig.settings.auth_user = $('#username').val();
                    $.reconfig.defaults.auth_pass=_reconfig.settings.auth_pass = $('#password').val();
                    obj.exec(id);
                    if(_reconfig.settings.json_data !== null)
                        obj.build(settings.action[1]);
                });
            },
            exec: function (id) {
                if(id === null) {
                    alert("oops! no data, sorry");
                }
                var el = $('#'+id).attr('id'), jsdata=null;
                if(settings.controller === null) {
                    alert("oops! there is a problem executing script controller");
                    return;
                }
                if(typeof settings.do_before_exec === 'function') {
                    settings.do_before_exec(id);
                }
                $.ajax({
                    url: settings.controller,
                    type: 'POST',
                    data: settings,
                    async: false,
                    dataType: 'json',
                    beforeSend: function(){
                    },
                    success: function(data){
                        jsdata=data;
                        if(typeof data.debug != 'undefined') {
                            data.debug = null;
                        }
                        if(typeof data[id] == 'undefined' || data[id] === null) {
                            alert("oops! no data for ["+id+"], sorry");
                            return;
                        }
                        if(typeof data[id].validation != 'undefined') {
                            $("#msgbox").fadeTo(200,0.1,function() { 
                                $(this).html(data[id].validation).
                                    addClass('messageboxerror').fadeTo(900,1);
                            });             
                        } else {
                            if(typeof $("#msgbox").css('visibility') != 'undefined') {
                                $('#msgbox').html('Logging in.....').addClass('messageboxok').
                                    fadeTo(900,1,function() { 
                                    });
                                if($.inArray('nohide',settings.action) < 0)
                                    $('#login_form').hide();
                                $('#msgbox').fadeOut('slow');
                            }
                            settings.json_data = data;
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert("Exec error:\njqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown);
                    },
                    complete: function () {
                        if(typeof settings.do_after_exec === 'function') {
                            settings.do_after_exec(jsdata);
                        }
                    }
                });
            },
            /** this function will be called for 'fill' action too */
            build: function (action) {
                var json_data = settings.json_data;
                if(json_data === null) {
                    alert("oops! there is not json data");
                    return;
                }
                if(typeof settings.do_before_build === 'function') {
                    settings.do_before_build(json_data);
                }
                var type = '',name='',label='',title='',value='',attrs='',evt='',encode=false;
                var lowercase='', uppercase='', selbycode='';
                var code = '',depth=0;
                var json_el = null;
                _reconfig.settings = settings;
                _reconfig.settings.json_data = json_data;
                var display_plain_text = (typeof settings.display_plain_text != 'undefined' ?
                                          settings.display_plain_text : false);
                for(var item in settings.items) {
                    var el = $('#'+settings.items[item])[0];
                    if(typeof el == 'undefined') {
                        alert("oops! ["+settings.items[item]+"] item undefined");
                        return;
                    }
                    code='';
                    for(e in json_data[el.id]) {
                        type = '',name='',label='',title='',value='',attrs='',evt='',encode=false,
                        lowercase=uppercase=null, selbycode=false;
                        json_el = null;
                        label=title=value=attrs=evt='';
                        encode=false;
                        json_el = json_data[el.id][e];
                        if(json_el.type == 'none') continue;
                        if(json_el.type == 'html') {
                            code += json_el.code;
                            continue;
                        }
                        if(typeof json_el.lowercase != 'undefined') lowercase=json_el.lowercase;
                        if(typeof json_el.uppercase != 'undefined') uppercase=json_el.uppercase;
                        if(typeof json_el.selbycode != 'undefined') selbycode=json_el.selbycode;
                        type = json_el.type;
                        if(action != 'fill') {
                            if(typeof json_el.html != 'undefined') {
                                if(typeof json_el.html.prepend != 'undefined') {
                                    code += json_el.html.prepend;
                                }
                            }
                        }
/** if 'value' is not set use 'values'. for 'select','checkbox' and 'radio', pay attention
    because it indicates its 'selected' or 'checked' item
*/
                        if(typeof json_el.depth != 'undefined') depth = json_el.depth;
                        value = (typeof json_el.value != 'undefined'
                            && json_el.value != null
                            && json_el.value.length > 0 ?
                            json_el.value :
                                (typeof json_el.values != 'undefined'
                                && json_el.values !== null && json_el.values.length > 0 ?
                                    json_el.values : []));
                        _reconfig.settings.json_data[el.id][e].value = value;
                        if(typeof json_el.encode != 'undefined') encode = json_el.encode;
                        if(typeof json_el.encode == 'string' && encode=='true')
                            encode = true;
                        if(encode === true || lowercase !== null || uppercase !== null) {
                            if(typeof value == 'string') {
                                if(encode === true) value = unescape(value);
                                if(lowercase === true) value = value.toLowerCase();
                                if(uppercase === true) value = value.toUpperCase();
                            } else {
                                for(var e in value) {
                                    if(encode === true) value[e] = unescape(value[e]);
                                    if(lowercase === true) value[e] = value[e].toLowerCase();
                                    if(uppercase === true) value[e] = value[e].toUpperCase();
                                }
                            }
                        }
                        name = (typeof json_el.name != 'undefined' && json_el.name.length > 0 ?
                            json_el.name : e);
                        if(typeof json_el.attrs != 'undefined'
                        && json_el.attrs['class'] != 'undefined'
                        && json_el.attrs['class'] == 'is_ml') {
                            value=$().getLanguage(value,settings);
                            name=$().getLanguage(name,settings);
                        }
                        if(typeof json_el.label != 'undefined' && json_el.label.length > 0) {
                            label = json_el.label;
                            code += '<label id="l'+name+
                                '" for="'+name+'">'+label+'</label>';
                        }
                        if(typeof json_el.attrs != 'undefined'
                        && json_el.attrs['class'] != 'undefined'
                        && json_el.attrs['class'] == 'is_ml') {
                            label=$().getLanguage(label,settings);
                        }
                        if(label.length > 0 && settings.language != null
                        && typeof settings.language[label] != 'undefined')
                            label=settings.language[label];
                        attrs = '';
                        if(typeof json_el.attrs != 'undefined') {
                            for(var e in json_el.attrs) {
                                attrs += ' '+e+'="'+unescape(json_el.attrs[e])+'"';
                            }
                        }
                        if(typeof json_el.event != 'undefined') {
                            for(var e in json_el.event) {
                                evt += ' '+e+'='+unescape(json_el.event[e]);
                            }
                        }
                        switch(type) {
                            case 'function':
                                var fn = Function('id','data','parms',json_el.code);
                                //var fn = window[json_el.code];
                                fn(el.id,json_data,
                                    (typeof json_el.parms != 'undefined' ? json_el.parms : null));
                                break;
                            case 'eval':
                                    eval(json_el.code);
                                break;
                            case 'radio':
                                if(action == 'fill') {
                                    if(typeof value != 'string') value = value[0];
                                    item = (selbycode !== true ? value : json_el.values[value]);
                                    item = (lowercase !== null ? item.toLowerCase() :
                                           (uppercase !== null ? item.toUpperCase() :
                                            item));
                                    $('input:radio[name="'+name+'"]')
                                        .filter('[value="'+item+'"]').prop('checked', true);
                                    break;
                                }
                                var item = '';
                                if(typeof value == 'string') value = [value];
                                if(typeof json_el.values == 'string') json_el.values=[json_el.values];
                                for(var e in json_el.values) {
                                    if(json_el.values[e] === null) continue;
                                    item = (selbycode === true ? e : json_el.values[e]);
                                    item = (lowercase !== null ? item.toLowerCase() :
                                           (uppercase !== null ? item.toUpperCase() :
                                            item));
                                    is_checked = ($.inArray(item,value) >= 0 ? 'checked ' : '');
                                    encode=display_plain_text;
                                    code += '<input type="radio" name="'+name+'"'+attrs+' value="'+
                                        $.trim(json_el.values[e])+'" id="'+name+'-'+e+
                                        '" '+(is_checked.length > 0 ? 'checked ' : ' ')+evt+
                                        ' /><span id="span-'+escape(json_el.values[e])+'"'+
                                        '>'+(encode === true ? unescape(json_el.values[e]) :
                                            json_el.values[e])+'</span>';
                                }
                                break;
                            case 'check':
                            case 'checkbox':
                                var is_checked = '';
                                // 'value' could be array to set multiple items
                                var item = '';
                                if(typeof value == 'string') value = [value];
                                if(typeof json_el.values == 'string') json_el.values=[json_el.values];
                                for(var e in json_el.values) {
                                    if(json_el.values[e] === null) continue;
                                    item = (selbycode === true ? e : json_el.values[e]);
                                    item = (lowercase !== null ? item.toLowerCase() :
                                           (uppercase !== null ? item.toUpperCase() :
                                            item));
                                    is_checked = ($.inArray(item,value) >= 0 ? 'checked ' : '');
                                    if(action == 'fill') {
                                        $('#'+name+'-'+e).prop('checked',
                                            (is_checked.length > 0 ? true : false));
                                        continue;
                                    }
                                    encode=display_plain_text;
                                    code += '<input type="checkbox" name="'+name+'" '+
                                        'id="'+name+'-'+e+'"'+attrs+' '+' value="'+
                                        $.trim(json_el.values[e])+'" '+is_checked+
                                        evt+'><span id="span-'+json_el.values[e]+'"'+
                                        '>'+(encode === true ? unescape(json_el.values[e]) :
                                            json_el.values[e])+'</span>';
                                }
                                break;
                            case 'select':
                            case 'option':
                                if(type == 'select')
                                    code += '<select name="'+name+'" id="'+name+'"'+attrs+evt+'>';
                                
                                if(action == 'fill') code='';
                                // 'value' could be array to set multiple items
                                var item = '';
                                if(typeof value == 'string') value = [value];
                                if(typeof json_el.values == 'string') json_el.values=[json_el.values];
                                for(var e in json_el.values) {
                                    if(json_el.values[e] === null) continue;
                                    item = (selbycode === true ? e : json_el.values[e]);
                                    item = (lowercase !== null ? item.toLowerCase() :
                                           (uppercase !== null ? item.toUpperCase() :
                                            item));
                                    code += '<option name="'+name+'" value="'+e+
                                        '" id="'+name+'-'+e+'" '+
                                        ($.inArray(item,value) >= 0 ?
                                            'selected ' : '')+
                                        (type != 'select' ? attrs+evt : '')+
                                        '><span id="span-'+name+'-'+e+'"'+'>';
                                    encode=display_plain_text;
/** if defined 'display': '0'->display array index; '1'->display array item; TODO: '1,1->multiarray*/
                                    if(typeof json_el.display != 'undefined') {
                                        if(json_el.display == '0') {
                                            code += e;
                                        } else {
                                            var key = json_el.values[e];
                                            code += (encode === true ? unescape(key) : key);
                                        }
                                    } else {
                                        // include 'json2.js' into your page to use 'parse' and 
                                        // 'stringify' (for explorer)
                                        item = JSON.stringify(json_el.values[e]);
                                        code += (encode === true ? unescape(item) : item);
                                    }
                                    code += '</span></option>';
                                }
                                if(action == 'fill') {
                                    $('#'+name+' option').remove();
                                    $(code).appendTo('#'+name);
                                    break;
                                }
                                if(type == 'select')
                                    code += '</select>';
                                break;
                            case 'img':
                                if(action == 'fill') break;
                                code += '<img id="'+name+'" src="'+value+'"'+attrs+evt+' />';
                                break;
                            case 'button':
                                if(action == 'fill') break;
                                if(!value.length || value.length == 0) {
                                    value = name;
                                }
                                code += '<input type=button name="'+name+'" id="'+name+'"'+
                                       attrs+' value="'+value+'"'+evt+'>';
                                break;
                            case 'textarea':
                                if(display_plain_text === true) value=unescape(value);
                                if(action == 'fill') {
                                    $('#'+name).val(value);
                                    break;
                                }
                                code+='<textarea name="'+name+'" id="'+name+'"'+
                                    attrs+evt+'>'+value+'</textarea>';
                                break;
                            case 'input':
                                if(display_plain_text === true) value=unescape(value);
                                if(action == 'fill') {
                                    $('#'+name).val(value);
                                    break;
                                }
                                code += '<input type="'+
                                    (type == 'password' ? 'password" ' :
                                        (type == 'hidden' ? 'hidden' : 'text" '))+
                                    'name="'+name+'" id="'+name+'" value="'+value+'"'+
                                    attrs+evt+'/>';
                                break;
                            default:
                                encode=display_plain_text;
                                if(encode === true) value=unescape(value);
                                if(depth > 0) {
                                    value = json_el.values;
                                }
                                if(!(value instanceof Object)) value=[value];
                                for(var e in value) {
                                    if(encode == true) value[e]=unescape(value[e]);
                                    if(action == 'fill') {
                                        if(typeof $('#'+name+'-'+e).attr('id') != 'undefined') {
                                            $('#'+name+'-'+e).html(value[e]);
                                        } else {
                                            $('#'+name).html(value[e]);
                                        }
                                        continue;
                                    }
                                    code += '<'+type+
                                        ' name="'+name+'" id="'+name+'-'+e+'"'+
                                        attrs+evt+'>'+value[e]+'</'+type+'>';
                                }
                                break;
                        } // end switch type
                        if(action != 'fill') {
                            if(typeof json_el.html != 'undefined') {
                                if(typeof json_el.html.append != 'undefined') {
                                    code += json_el.html.append;
                                }
                            }
                        }
                    } // end foreach single item
                    if(action != 'fill') {
                        $(code).appendTo(el);
                    }
                } // end foreach items
                if(typeof settings.do_after_build === 'function') {
                    settings.do_after_build(json_data);
                }
            },
            get_data: function () {
                _reconfig.settings = settings;
                var type='',name='',value='',encode=false,type_of='',depth=0;
                for(var item in settings.items) {
                    var el = $('#'+settings.items[item])[0];
                    for(e in _reconfig.settings.json_data[el.id]) {
                        json_el = _reconfig.settings.json_data[el.id][e];
                        type = json_el.type;
                        if(typeof json_el.type_of != 'undefined') type_of = json_el.type_of;
                        if(typeof json_el.encode != 'undefined') encode = json_el.encode;
                        if(typeof json_el.depth != 'undefined') depth = json_el.depth;
                        if(type == 'none' || type == 'html' || type == 'button') {
                            continue;
                        }
                        name = json_el.name;
                        value = new Array();
                        $('[name="'+name+'"]').each(function () {
                            switch(type) {
                                case 'radio':
                                case 'check':
                                case 'checkbox':
                                    if(this.checked) {
                                        var selbycode=false;
                                        if(typeof json_el.selbycode != 'undefined')
                                            selbycode=json_el.selbycode;
                                        if(selbycode != false) {
                                            value.push(this.id.substring(
                                                this.name.length+1,this.id.length));
                                        } else {
                                            value.push(this.value);
                                        }
                                    }
                                    break;
                                case 'select':
                                case 'option':
                                    $('#'+this.id+' option:selected').each(function () {
                                        var selbycode=false;
                                        if(typeof json_el.selbycode != 'undefined')
                                            selbycode=json_el.selbycode;
                                        if(selbycode != false) {
                                            value.push(this.value);
                                        } else {
                                            value.push($(this).text());
                                        }
                                    });
                                    break;
                                default:
                                    if(typeof this.value != 'undefined') {
                                        value.push(this.value);
                                    }
                                    break;
                            }
                        });
                        // if value object is unchanged and 'all_data' != true ignore field
                        if(settings.all_data !== true
                        && obj.compare_array(json_el.value, value) === true) {
                            delete _reconfig.settings.json_data[el.id][e].value;
                            continue;
                        }
                        /** if value is empty and all_data = true, set a value to run setup */
                        _reconfig.settings.json_data[el.id][e].value = value;
                    }
                } // end foreach json_data
            },
            save: function () {
                if(typeof settings.do_before_save === 'function') settings.do_before_save(data);
                $.ajax({
                    url: settings.controller,
                    type: 'POST',
                    data: settings,
                    async: false,
                    dataType: 'json',
                    success: function(data){
                        settings.json_data = data;
                        if(typeof settings.do_after_save === 'function')
                            settings.do_after_save(data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert("Saving error:\njqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown);
                    },
                });
            },
            compare_array: function (a, b) {
                if(!(a instanceof Object)) a=[a];
                if(!(b instanceof Object)) b=[b];
                if(typeof a.length == 'undefined') a = [a];
                if(typeof b.length == 'undefined') b = [b];
                if(a.length == 1 && a[0] == '') a = [];
                if(b.length == 1 && b[0] == '') b = [];
                var equal = a.length == b.length;
                if (equal) {
                    $.each(a, function (foo, val) {
                        if (!equal) return false;
                        if ($.inArray(val, b) == -1) {
                            equal = false;
                        } else {
                            equal = true;
                        }
                    });
                }
                return equal;
            },
            run: function () {
                if(typeof(settings.action) != 'object') {
                    settings.action = [settings.action];
                }
                if(typeof(settings.items) != 'object') {
                    settings.items = [settings.items];
                }
                var action = '';
                for(var i=0; i < settings.action.length; i++) {
                    action = settings.action[i];
                    if(typeof action == 'undefined' || action == '') continue;
                    if('login' == action) {
                        obj.login(settings.items[0]);
                        return;
                    } else if('exec' == action) {
                        obj.exec(settings.items[0]);
                    } else if('save' == action) {
                        obj.get_data();
                        obj.save();
                    } else if('build' == action) {
                        obj.build();
                        settings.action[i] = '';
                    } else if('fill' == action) {
                        obj.build('fill');
                        settings.action[i] = '';
                    } else if('get_data' == action) {
                        obj.get_data();
                        settings.action[i] = '';
                    } else if($.isFunction($reconfig[action])) {
                        $reconfig[action]();
                    }
                }
            }
        });
        obj.run();
    };
    $.reconfig = {
        defaults: {
            auth_driver: null,
            auth_host: 'localhost', //null,
            auth_user: null,
            auth_pass: null,
            lang: 'en-EN',
            action: null,         /* build save */
            json_data: null,      /* build directly with no script */
            items: null,
            controller: null,     /* script to build global json_data object for building */
            do_before_exec: null, /* javascript funcion executed before posting data, ie: */
                /* function(id){ if(typeof id !== 'undefined') do_something(id); },*/
            do_after_exec: null,  /* javascript funcion executed after posting data */
                /* function(data){ if(typeof data !== 'undefined') do_something(data); },*/
            do_before_save: null, /* like do_before_exec */
            do_after_save: null,  /* like do_after_exec */
            all_data: true,       /* true>save all data, false>save only changed values   */
            language: null,       /* language:{login: 'connetti',logout: 'esci',..}*/
            display_plain_text: false, /* display always unescaped text */
        }
    };
})(jQuery);

jQuery.fn.getLanguage = function(data, options) {
    if(typeof data == 'undefined' || typeof data != 'string') return '';
    if(typeof options == 'undefined' || typeof options.language == 'undefined') return data;
    if(options.language != null && typeof options.language[data] != 'undefined') {
        return $.trim(options.language[data]);
    }
    return data;
};
jQuery.fn.setLanguage = function(options) {
    var $this=this;
    if(typeof options.items != 'undefined') {
        $this=options.items;
    }
    var target=null;
    $.each($this,function () {
        if(this.id != 'undefined' && this.id.length > 0) {
            target=$('#'+this.id);
        } else {
            target=$(this);
        }
        if(typeof target.attr != 'undefined'
        && typeof target.val() != 'undefined'
        && target.val().length > 0) {
            target.val($().getLanguage(target.val(),options));
        } else if(typeof target.text != 'undefined') {
            target.html($().getLanguage(target.text(),options));
        } else if(typeof target.html != 'undefined') {
            target.html($().getLanguage(target.html(),options));
        }
    });
};

String.prototype.trim = function (chars) {
                if(this && this.length > 0)
                    return this.ltrim(chars).rtrim(chars);
}
String.prototype.ltrim = function (chars) {
                if(this && this.length > 0) {
                    chars = chars || "\\s";
                    return this.replace(new RegExp("^[" + chars + "]+", "g"), "");
                }
}
String.prototype.rtrim = function (chars) {
                if(this && this.length > 0) {
                    chars = chars || "\\s";
                    return this.replace(new RegExp("[" + chars + "]+$", "g"), "");
                }
}