
var browser=navigator.appName;
if (browser=='Microsoft Internet Explorer'){var IE = true}
else {var IE = false}

/** int - Number of seconds since time was loaded incremented by {@link time_incrementer} */
var time = 0;
/** int - Last time that a cpage was submitted */
var lasttime=0;
/** string - Name of the current zone, either main or topics  */
var app_zone = '';
/** string - Name of the current page */
var pagename = '';
/** string - Scripts that currently being used, set by {@link getscript} */
var currentscript = '';
/** string - Styles that currently being used, set by {@link getscript} */
var currentstyle= 'none';
/** string - Page title, currently not changed anywhere*/
var currentptitle = 'O24uOnline';
/** string - Name of the current user */
var name = 'guest';
/** string - Usertype of the current user options are teacher,student,guest,ect.. */
var usrtype = 'guest';
/** string - Teacher name of the current student */
var teacher = '';
/** string - Name of the curriculum that we are using */
var curric_name = '';

/** int - Grade of the current student */
var grade = 0;

/** object - Object with pagename:html where html is what is retured by getpage_main ajax request, lets us cache pages we use often */
var pagehtml = new Object();


/** @ignore */var prepare_usr_dlg = function(){};
/** @ignore */var makeoptions = function(){};
/** @ignore */var ask_question = function(){};
/** @ignore */var doajax = function(){};
/** @ignore */var clickaction = function(num){} 
/** @ignore */var dropaction = function(cls,ui,dable){} 
/** @ignore */var showaction = function(i){}
/** @ignore */var getpage = function(pname){}
/** @ignore */var stageaction = function(i){}


/** Clears functions that are overwritten by page specific scrips*/
var clearscripts = function(){
    clickaction = function(num){} 
    dropaction = function(cls,ui,dable){} 
    showaction = function(i){} 
    stageaction = function(i){}
}



/** Object will teacher name:array of class names */
var teacherlist = {};
/** dialog - Dialog to add new user, made by {@link prepare_usr_dlg} */
var auser = '';

/** This is the class where we keep all the click event documentation
    @name click_handlers
    @constructor */






$(document).ready(toolbox_top)
/** Loaded in all pages, used for defining functions that are used on all pages
    @constructor */
function toolbox_top(){

    
    /** Sets up defaults for all AJAX requests used in the program*/
    $.ajaxSetup({
       url: "/rpc",
       type: "POST",
       dataType: "json",
       cache: false,
       error: function (XMLHttpRequest, textStatus, errorThrown) {
                  online_status = false;
                  confirm('Ajax request did not work');
                  }
    });



   /** Sends basic AJAX requests, if request fails reason for failure is displayed
         @param {string} action String that is used to identify request
         @param {object} args Oject containing all the variables needed by the request
         @param {function} func Function is ran on a successful request, it is passed all data returned by request
         @param {function} func2 Function is ran on failed request, else we just confirm msg, it is passed data
         @returns Nothing
     */
   doajax = function(action,args,func,func2){
        var cdata = $.toJSON(args);
        $.ajax({data:{action:action,data:cdata},
              success: function(data){
                online_status = true;
                if(data.success == true){
                    if(func){func(data);}
                }
                else{
                    if(func2){func2(data);}
                    else {confirm(data.msg);}
                    
                }
               }
        });
    }  
    
    
    /** Increments {@link time} every second
        @function
        @name time_incrementer
      */
    $.timer(1000, function (timer) {
        time++;     //every second we add one to the time variable
        $('#timer').html("<b>Time: "+time+"</b>");  //we update an object with id timer with the new time
        if(app_zone=='topics'){
            if(time-lasttime > 6000){$('#logout').click()}
            if(time%60==0){
                if(usrtype=='student'){sendcpage(updateteacher());}
                else{sendcpage()}
            }
        }
    });
    
    /** Constructs options for select elements 
         @param {array} options List of options to make
         @returns Html that can be inserted into a select element
      */
    makeoptions = function(options){
        var htm = '';
        for(var i=0,lim=options.length;i<lim;i++){ 
            htm += '<option value="'+options[i]+'">'+options[i]+'</option>';
        }
        return htm
    }

    
    /** Opens a dialog that lets people enter a msg that is sent to us for questions.  Sends email using ajax request  */
    ask_question = function(){
        var dtext = $('<div title="Ask a Question">We apprecite your comment.<br/><br/></div>');
        $('<label>Your email: </label><input type="text" id="user-email" size="20" ></input><br/><br/>').appendTo(dtext);
        $('<textarea id="user-comment" rows="20" cols="50"></textarea>').appendTo(dtext);
        dtext.dialog({
            height: 600,width:500,modal: true,overlay: {backgroundColor: '#000',opacity: 0.5},
            buttons: {
                'Send Comment': function() {
                    var cdata = {'name':name, 'usrtype':usrtype, 'tname':teacher,
                        'email':$('#user-email').val(),'content':$('#user-comment').val()}
                    doajax('send_email',cdata,function(){confirm('Email sent, we will get back to you soon.')})   
                    $(this).dialog('destroy').remove();
                },
                Cancel: function() {$(this).dialog('close');}                
            },
            close:function(){$(this).dialog('destroy').remove()}
        });          
    };
    
    /** Prepares the add user dialog using adduser function.  If it is in the main section, this function sets up a click event to #adduser.  
            If it is in the topics section, it opens the dialog if either name or usrtype is null.  This prevents people who are not signed in from 
            using the topics section.
         @param {string} pagename Either main or topics for whatever section you are in.
      */
    prepare_usr_dlg = function(pagename){
        auser = adduser();
        if(pagename=='main'){
            $('#adduser').livequery('click', function(event) {
                auser.dialog('open');
            });
        }
        else{
            if(name==null || usrtype==null){
                confirm('You are not logged on. Please log in or create a new account.');
                auser.dialog('open');
            }
        } 
    }

    /** Directs people to main breathe LA website
           @name click_handlers#logo
           @event
        */
    $('#logo').click(function(){ 
		window.location="http://www.breathela.org/";
	})
    
    
    /** Creates the dialog to add new users
         @returns Dialog that is closed, but can be opened
      */
    var adduser = function(){
        var auser = $('<div id="adduser" title="Add User"></div>'); 
        
        var sdiv = $('<div>Usertype:</div>');
        var selec = $('<select id="au-usrtype">'+makeoptions(['...','teacher','student','class'])+'</select>'); 
        selec.appendTo(sdiv);
        
        var sdiv2 = $('<div>Teacher:</div>');
        var selec2 = $('<select id="au-teacher">'+makeoptions(['...'])+'</select>');  
        selec2.appendTo(sdiv2);
        
        var sdiv3 = $('<div>Class:</div>');
        var selec3 = $('<select id="au-classname">'+makeoptions(['...'])+'</select>');  
        selec3.appendTo(sdiv3);
        
        var inpts = [
                sdiv,
                $('<div>Name<input type="text" id="au-name" size="20" ></input></div>'), 
                $('<div>Password: <input type="text" id="au-pw" size="20" ></input></div>'),  
                sdiv2,
                $('<div>Grade: <input type="text" id="au-grade" size="40" ></input></div>'),
                sdiv3,
                $('<div>School Name: <input type="text" id="au-schoolname" size="40" ></input></div>'),
                $('<div>School Address: <input type="text" id="au-schooladdress" size="40" ></input></div>'),              
                $('<div id="subadduser" class="button create">Create my account!</div>'),
                $('<div id="sublogin"></div>')]                
        for(var i=0,lim=inpts.length;i<lim;i++){ 
            inpts[i].appendTo(auser);
        }

        $(selec).change(function(){
            var ut = $(selec).val();
            $.each(inpts.slice(1), function() {this.hide()});
            var shw = [];
            if(ut=='student'){shw=[1,2,3,5];}
            else if (ut=='teacher'){shw=[1,2,6,7];}
            else if (ut=='class'){shw=[1,3,4];}
            if (shw.length!=0){
                shw.push(inpts.length-1);shw.push(inpts.length-2);
                for(var i=0;i<shw.length;i++){ inpts[shw[i]].show();}
            }
            //Loading teacher list
            if(ut=='student' || ut=='class'){
                doajax('getteachers',{},function(){teacherlist = data;});
                $(selec2).html(makeoptions(['noteacher'].concat(teacherlist.listnames)));
                $(selec2).change();
            }
        })
        $(selec2).change(function(){
            var ut = $(selec2).val();
            $(selec3).html(makeoptions(teacherlist[ut])); 
        });
        
        inpts[inpts.length-2].click(function(){
            var datan = ['name','usrtype','pw','teacher','classname','grade','schooladdress','schoolname'];
            var data = {};
            for(var i=0,lim=datan.length;i<lim;i++){ data[datan[i]]=$('#au-'+datan[i]).val();}
       
            var response = adduserajax(data,'newuser');
            if(response==true){
                //confirm('good job, data saved');
                auser.dialog( "close" );
                if(pagename=='welcome'){
                   getpage('topics');
                   $('#header').show();
                }
            }
            else{confirm(response);}
        });   

        inpts[inpts.length-1].click(function(){
            var datan = ['name','usrtype','pw','teacher'];
            var data = {};
            for(var i=0;i<datan.length;i++){ data[datan[i]]=$('#au-'+datan[i]).val();}
       
            var response = adduserajax(data,'signin');
            if(response==true){
                //confirm('good job, you are logged on');
                auser.dialog( "close" );
                $('#studentname').html(name);
                if(pagename=='welcome'){getpage('topics')};
            }
            else{confirm(response);}
        });
        
        var diaopen = function(){
            $('#au-usrtype').change();
        }
        
        
        auser.appendTo("#container").dialog({open:diaopen,autoOpen:false,modal:true,width:500,height:300,overlay:{'background-color' : '#00FF00','opacity':.5}});

        return auser
    }  

}








    /** Changes strings to TitleCase
         @returns String with start of words capitilized
      */
    String.prototype.TitleCase = function() {
		var o_split = this.split(" ");
		//this probably isn't a complete list of words that shouldn't be capitalized
		var special_words = new Array('and', 'the', 'to', 'for', 'is', 'in', 'a', 'at', 'an', 'from', 'by', 'if', 'of');
		for (var i=0;i<o_split.length;i++){
			if (i == 0) {
				//always capitalize the first word
				o_split[i] = (o_split[i].substring(0,1)).toUpperCase() + o_split[i].substring(1);
			}
			else if(special_words.indexOf(o_split[i]) < 0) { 
			  	o_split[i] = (o_split[i].substring(0,1)).toUpperCase() + o_split[i].substring(1);
			}
		}
      return o_split.join(' ');
    };


    /** Removes a selection of elements from an array 
         @param {int} from Index to start removing items
         @param {int} to Index to start stop removing items, if not present, removes all items to end of array
         @returns Array with elements removed
      */
    Array.prototype.remove = function(from, to) {
      var rest = this.slice((to || from) + 1 || this.length);
      this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
    };

    /** Looks for a value in an array 
         @param val Value to look for, loosly typed
         @returns Array, first value is true or false if value was found, second is the index, or false if not found
      */
    Array.prototype.find = function(val) {
        for(var i=0;i<this.length;i++){  
        if (this[i]==val) return new Array(true,i)
        }
        return new Array(false,false)
    };
    
    /** Creates an 2d array filled with '' 
         @param iRows Number of rows
         @param iCols Number of collums
         @returns 2d array
      */
    function MDA(iRows,iCols){ 
       var i;var j; 
       var a = new Array(iRows); 
       for (var i=0; i < iRows; i++){ 
           a[i] = new Array(iCols); 
           for (var j=0; j < iCols; j++){ 
               a[i][j] = ""; 
           } 
       } 
       return a; 
    } 
        
    
   /** Creates a new cookie.  Replaces spaces with '_' 
         @param name Name of the cookie
         @param value Value of the cookie
         @param days Number of days the cookie should last
      */
   function createCookie(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        if(value==undefined){value=''}
        name =  name.replace(' ','_');
        value =  value.replace(' ','_');
        document.cookie = name+"="+value+expires+"; path=/";
    }

    /** Reads a cookie.  Replaces '_' with spaces to recreate initial name
         @param name Name of the cookie
         @returns value from the cookie, if not found, returns null
      */
    function readCookie(name) {
        name =  name.replace(' ','_');
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length).replace('_',' ');
        }
        return null;
    }

    /** Deletes a cookie by overwriting it with one with a negative time
         @param name Name of the cookie
      */
    function eraseCookie(name) {
        createCookie(name,"",-1);
    }  



    /** Does the ajax requests for adding a user, needs work, but not enough time now
         @param udata All that data that we got from the dialog box {name,pw,usrtype,schoolname,schooladdress,teacher,grade}
         @param reqtype Type of user that we are trying to add
         @returns bool for if the request worked or not 
      */
  var adduserajax = function(udata,reqtype){ 
        var worked = true;
        if(reqtype=='signin'){
            if(!udata.name || !udata.pw ||  !udata.usrtype){return 'please complete all requried fields'}
            
           // doajax('signin',udata,function(){
            //                    name = data.name;
             //                   usrtype = data.usrtype;
              //                  teacher = data.teacher;
               //                 setcookies();
                //                }
           // )
            
            
            var cdata = $.toJSON(udata)
            $.ajax({url: "/rpc",type: "POST",async:false,dataType: "json",
                data:{action:'signin',data:cdata},cache: false,
                success: function(data){
                    if(data.success == true){
                            name = data.name;
                            usrtype = data.usrtype;
                            teacher = data.teacher;
                            setcookies();
                        //confirm('logged on')
                    }
                    else{worked = data.msg}
                  },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                  worked = 'Ajax request did not work'
                  }
            });
            
            return worked
            
        }
        else if (reqtype=='newuser'){
            if(udata.usrtype=='class'){
                if(!udata.name || !udata.grade){return 'please complete all grade fields'}
            }
            else{
            if(!udata.name || !udata.pw ||  !udata.usrtype){return 'please complete all requried fields'}
            if(udata.usrtype=='teacher' && !(udata.schoolname && udata.schooladdress)){return 'please complete all teacher fields'}
            if(udata.usrtype=='student' && !udata.teacher){return 'please complete all student fields'}    
            }
            var cdata = $.toJSON(udata)
            $.ajax({url: "/rpc",type: "POST",async:false,dataType: "json",
                data:{action:'addusr',data:cdata},cache: false,
                success: function(data){
                    if(data.success == true){
                        if(data.usrtype!='class'){
                            name = data.name;
                            usrtype = data.usrtype;
                            teacher = data.teacher;
                            setcookies();
                        }
                        //confirm('worked fine')
                    }
                    else{worked = data.msg}
                  },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                  worked = 'Ajax request did not work 1'
                  }
            });
            
            return worked
        }
    
    }

    /** Sets cookies based on global variables name,usrtype and teacher, all are set for one day.  */
    setcookies = function(){
        createCookie('name',name,1);
        createCookie('usrtype',usrtype,1);
        createCookie('teacher',teacher,1);
        createCookie('curric',curric_name,1);
    }
    
    

    /** Creates a sortable table from a data set 
         @param {array} header Contains all the header values for the data, should be same length as data rows
         @param {array} data Either an array of text, or an array of arrays.  If each element is text, the separator parameter is used to split the data up
         @param {string} separator If true, this is used to split up rows of data
         @param {function} rowfunc Function that is triggered every time a row is clicked, passed [first col, second col] for that row 
         @param {function} cellfunc Function that is triggered every time a cell is clicked, passed [second col, first col, cell idx] for that row
         @param {string} sfx Text that is added to the end of every cell depending on sfxstart
         @param {int} sfxstart Index after which the suffix is added to the cell value
         @returns Jquery element of a table
      */
    var MakeTable = function(header,data,separator,rowfunc,cellfunc,sfx,sfxstart){
        if(!sfx){sfx='';sfxstart=100;}
        var ndata =  new Array();
        if(separator){
            for(var i=0,lim=data.length;i<lim;i++){
                ndata.push(data[i].split(separator));
            }
        }
        else{ndata = data}
        
        var tab = $('<table class="tablesorter teachertable" border="0" cellpadding="0" cellspacing="1"></table>');
        var head = $('<thead></thead>');
        var hrow = $('<tr></tr>');
        for(var i=0,lim=header.length;i<lim;i++){
            $('<th>'+header[i]+'</th>').appendTo(hrow);    
        }
        hrow.appendTo(head);
        head.appendTo(tab);
        var rows = new Array;
        for(var i=0,lim=ndata.length;i<lim;i++){
            var row = $('<tr id="'+ndata[i][0]+'" id2="'+ndata[i][1]+'"></tr>');
            for(var j=0,lim2=ndata[i].length;j<lim2;j++){ 
                if(j<sfxstart){var sufx = '';}
                else{var sufx = sfx;}
                var cell = $('<td sname="'+ndata[i][1]+'" tname="'+ndata[i][0]+'" cnum="'+j+'">'+ndata[i][j]+sufx+'</td>');
                cell.appendTo(row);
                cell.click(function(){cellfunc($(this).attr('sname'),$(this).attr('tname'),$(this).attr('cnum'))})
            }
             row.appendTo(tab);
             row.click(function(){rowfunc($(this).attr('id'),$(this).attr('id2'))})
        }
        return tab
    }

    /** Returns all the keys of a object 
         @param {object} o Object to get the keys from
         @returns Array of keys
      */
    function keys(o) {
        var accumulator = [];
        for (var propertyName in o) {
          accumulator.push(propertyName);
          }
        return accumulator;
    }

    /** Randomizes an array 
         @param {array} myArray Array that you would like to randomize
         @returns Randomized array
      */
    var rize = function( myArray ) {
      var i = myArray.length;
      if ( i == 0 ) return false;
      while ( --i ) {
         var j = Math.floor( Math.random() * ( i + 1 ) );
         var tempi = myArray[i];
         var tempj = myArray[j];
         myArray[i] = tempj;
         myArray[j] = tempi;
       }
       return myArray
    }
