(function($) {
 
    $.fn.studentNames = function(settings) {
        // default config
        var config = {
            id_prefix       : 'student_',
            student_class   : 'student_name',
            use_default     : false
        };
        
        // import config
        if (settings) $.extend(config, settings);
        
        /*
        // check for gears
        if (!hasGears()) {
            return false;   
        }
        
        // init gears db
        gearsInit();
        */

        this.each(function() {
            $(this).find('.' + config.student_class).each(function() {
                var studentId   = $(this).attr('title').substring(config.id_prefix.length);
                // if this is an option element, use the text as the value
                var origName = this.tagName == 'OPTION' ? $(this).text() : $(this).val();
                // do we use a default value if none found?
                var studentName = config.use_default ? getName(studentId, origName) : getName(studentId);
                $(this).html(studentName);
                $(this).attr('title', studentName);
            });
        });
        
        return this;
    };
    
    $.fn.studentNamesChart = function(xml, settings) {
        /*
        // check for gears
        if (!hasGears()) {
            return xml;   
        }
        
        // init gears db
        gearsInit();
        */

        var re = /studentId='(\w+)' name='(\w+)'/g;
        
        var namedXml = xml.replace(re, function(str) {
        	var parts = str.split(re);
        	return str.replace(new RegExp("name='"+parts[2]+"'"), 
        					   "name='"+getName(parts[1], parts[2])+"'", true);
        });
       
        return namedXml;
    };
    
    $.fn.studentNamesForm = function(settings) {
        // default config
        var config = {
            id_prefix       : 'student_',
            student_class   : 'student_name',
            input_name      : 'student_name'
        };
        
        // import config
        if (settings) $.extend(config, settings);
/*        
        // check for gears
        if (!hasGears()) {
            return false;   
        }
        
        // init gears db
        gearsInit();
*/        
        this.each(function() {
            // set up student name elements inside this dom element to 
            // be form elements
            $(this).find('.' + config.student_class).each(function() {
                var studentId   = $(this).attr('id').substring(config.id_prefix.length);
                var studentName = getName(studentId);
                var elem = $('<input type="text" class="'+config.student_class
                     + '" id="'+config.id_prefix+studentId+'"' 
                     + '" name="'+config.input_name+'['+studentId+']"'
                     + ' value="'+studentName+'"/>');
                
                $(this).html(elem);
            });
            
            
            // bind a submit event to this form so we capture the inputs generated
            // above.  when the form is released to the browser we'll remove the elements 
            // from the dom so they aren't even sent with the request
            $(this).submit(function() {
                $(this).find(':input[class='+config.student_class+']').each(function() {
                    var studentId = $(this).attr('id')
                        .substring(config.id_prefix.length, $(this).attr('name').length - 1);
                    var studentName = $(this).val();
                    
                    setName(studentId, studentName);
                    $(this).remove();
                });
                
                // allow the form to proceed
                return true;
            });
        });
    };
    
    $.fn.studentName = function(id, name) {
    	var fallback = id;
        if (name) {
            fallback = name;
        }
/*        
        if (!gearsInit()) {
    		return fallback;
    	}
*/    	
    	return getName(id, fallback);
    };
    
    /* has gears been initialized */
/*
    hasGears = function() {
        return (window.google && google.gears);
    };
*/    
    /* initialize gears db */
/*  
    gearsInit = function() {
        try {
            db = google.gears.factory.create('beta.database');

            if (db) {
                db.open('whitebox');
                db.execute('create table if not exists Student' + 
                    ' (Id int primary key, Name varchar(255))');

                return true;
            }
        } catch (ex) {
        	console.log('Gears is not available');
        	return false;
        }
    };
*/    
    setName = function(studentID, studentName) {
        localStorage.setItem(studentID, studentName);
        //db.execute('insert or replace into student values (?, ?)', [studentID, studentName]);
    };

    getName = function(studentID, defaultValue) {
    	if (defaultValue) {
    		var studentName = defaultValue;
    	} else {
    		var studentName = '';
    	}
    	
        //var rs = db.execute('select Name from Student where Id = ?', [studentID]);
        //if (rs.isValidRow() && rs.field(0).length > 0) {
        //    studentName = rs.field(0);
        // }
        //rs.close();
        var stored = localStorage.getItem(studentID);
        if (stored) {
            studentName = stored;
        }

        return studentName;
    };
    
    // show student names
    $('.students').studentNames();
 
 })(jQuery);

