Ext.namespace('SchoolDynamics');

/*************************************************
 * Cookie Code
 * INSPIRED BY: http://scripts.franciscocharrua.com/javascript-cookies.php
 */
Ext.namespace('cookie');
cookie.set = function() {
   cookie.clear();
   name = 'SchoolDynamics';
   value= Ext.util.JSON.encode(SchoolDynamics);
   document.cookie = name + '=' + value;
}

cookie.get = function() {
   name = 'SchoolDynamics';
   name_index = document.cookie.indexOf(name + '=');
   
   if(name_index == -1) return('');
   
   cookie_value =  document.cookie.substr(name_index + name.length + 1, document.cookie.length);
   
   //All cookie name-value pairs end with a semi-colon, except the last one.
   end_of_cookie = cookie_value.indexOf(';');
   if(end_of_cookie != -1) cookie_value = cookie_value.substr(0, end_of_cookie);

   //Restores all the blank spaces.
   space = cookie_value.indexOf('+');
   while(space != -1) { 
     cookie_value = cookie_value.substr(0, space) + ' ' + 
     cookie_value.substr(space + 1, cookie_value.length);
     space = cookie_value.indexOf('+');
   }

   var loadFromServer=false;
   cookie_value = Ext.util.JSON.decode(cookie_value);
   Ext.iterate(cookie_value, function(setting) {
      if (setting == 'schoolid' && SchoolDynamics[setting] != cookie_value[setting]) loadFromServer=true;
      if (setting == 'TeacherID' && SchoolDynamics[setting] != cookie_value[setting]) loadFromServer=true;
      SchoolDynamics[setting] = cookie_value[setting]; 
   });
   
   if (SchoolDynamics.schoolid == undefined || loadFromServer) siteinfo.load();
   
   return SchoolDynamics;
}

cookie.clear = function() {
   name = 'SchoolDynamics';
                     
   expires = new Date();
   expires.setYear(expires.getYear() - 1);
   document.cookie = name + '=null' + '; expires=' + expires; 		 
}
         
cookie.clearall = function() {
   Cookies = document.cookie;
   Cookie = Cookies;
   expires = new Date();
   expires.setYear(expires.getYear() - 1);

   while(Cookie.length > 0) {
        //All cookie name-value pairs end with a semi-colon, except the last one.
        Cookie = Cookies.substr(0, Cookies.indexOf(';'));
        Cookies = Cookies.substr(Cookies.indexOf(';') + 1, Cookies.length);

        if(Cookie != '')
           document.cookie = Cookie + '; expires=' + expires;
        else
           document.cookie = Cookies + '; expires=' + expires;			  			  	  
   }
}
         
//before the user leaves the site, set a cookie with all their local selects saved to it 
window.onunload = cookie.set;
/************************************************/


var siteinfo  = new Ext.data.Store({ url: 'schooldynamics_data.json.php',      baseParams: {command: 'getSiteInfo'},    async:false, autoLoad: false,  reader: new Ext.data.JsonReader({root: 'schooldynamics'}, ["schoolid","SchoolName",{name:"currentQtr",type:'int'},"TeacherID","username","homeroom","maxsize","grade","meal",{name:"lunchprice",type:'float'}]) });
siteinfo.on('load', function(store, records, options){

   var len = records[0].fields.items.length;
   for(i=0; i<len; i++) {
      var field = records[0].fields.items[i].name;
      SchoolDynamics[field] = records[0].data[field];
   }
   setSiteHeader();
});
var setSiteHeader = function() {
   document.getElementById('header_title').innerHTML = "Powering "+SchoolDynamics.SchoolName;
   document.getElementById('header_greeting').innerHTML = "Welcome, "+SchoolDynamics.username;
}

SchoolDynamics.getCurrentQtr = function () {
  if(SchoolDynamics.currentQtr == undefined){
      Ext.Ajax.request({
        url: 'schooldynamics_data.json.php',
        method: 'POST',
        async: false,
        params: {command: 'getCurrentQtr'},
        success: function(responseObject) {             
            eval("var results = "+responseObject.responseText);  
            SchoolDynamics.currentQtr=parseInt(results[0].quarter);
        },
        failure: function() {
            Ext.Msg.alert('Status', 'Unable to set all grades to zeros.');
        }
      });
    }
    return SchoolDynamics.currentQtr;
}

/***************************************************************
 *function: SchoolDynamics.isAccessible
 *parameters: formname, optional displayErrors
 *returns: false or array(formname,module,success)
 */
SchoolDynamics.isAccessible = function (form, displayErrors) {
   if (form==undefined) return false;
   var retval=false;
   Ext.Ajax.request({
     url: 'functions/privileges.json.php',
     method: 'POST',
     async:false,
     params: {command: 'getPrivileges', form:form},
     success: function(responseObject) {             
         eval("var results = "+responseObject.responseText);  
         if (!results.success && displayErrors!=undefined && displayErrors) {
            Ext.Msg.alert(results.errors.title, results.errors.message);
            retval = false;
         }
         retval = results;
     },
     failure: function() {
         return false;
     }
   });
   return retval;
}
//console.log('SchoolDynamics.isAccessible("Student Form")',SchoolDynamics.isAccessible("Student Form", true));


function PopulateGridSearch_onClick(btn) { 
      var store = Ext.getCmp(btn.searchgrid).store;
      var SearchField = Ext.getCmp(btn.searchfield);
      if (SearchField == null || SearchField == ''){
          alert ('Please type a value in the search field');
          return 0;
      }
      var Command = btn.searchfield+btn.text;//(btn.pressed?btn.text:'');
      //remove everything from the btn.text except alpha cahracters
      Command = Command.replace(/[ \`\~\!\@\#\$\%\^\&\*\(\)\_\+\{\}\|\[\]\:\;\<\>\?\,\.\/0-9]/g, "");      
      if (Command.match("SearchAll") || !btn.pressed) Command=btn.searchdefault;
      
      store.baseParams = {command: Command, searchcriteria: (btn.pressed?SearchField.getValue():'')};
      store.load();
      
      if (!btn.pressed) SearchField.setValue('');
}
//IE is missing some common javascript functions. Define missing ones here.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length;

        var from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++) {
            if (from in this && this[from] === elt)
                return from;
        }
        return -1;
    };
}


// Toggle just the group that is specified by the groupIndex (ie the array index) in the direction 
// of the expanded parameter, and toggle all the other groups in the opposite direction.
function toggleGroupingView(gv, groupIndex,expanded){
    var groups = gv.getGroups();
    if (groups.length) {
        if (groups.length >= groupIndex) {
            if (expanded) { gv.collapseAllGroups(); }
            else { gv.expandAllGroups(); }
            if (groups[groupIndex]) {
              gv.toggleGroup(groups[groupIndex], expanded);
            }
        }
    }
} 

//********** renderers
function removehtml(value) {
    return value.replace(/<\/?[^>]+(>|$)/g, "");
}
function center(value) {
    return ("<center>" + value + "</center>");
}

function bold(value){ 
    return '<strong>' + value + '</strong>'; 
} 

function italic(value) {
    return '<em>' + value + '</em>'; 
}

function formatDate(value){
   return value ? (new Date(value).format('m/j/Y')) : '';
};

function comboBoxRenderer(combo) {
  return function(value) {
    var idx = combo.store.find(combo.valueField, value);
    var rec = combo.store.getAt(idx);
    return (rec?rec.get(combo.displayField):(combo.valueNotFoundText?combo.valueNotFoundText:value));
  };
}

function pCase(s) { 
    return s.replace(/(\w)(\w*)/g,function 
    ( 
        strMatch, 
        strFirst, 
        strRest, 
        intMatchPos, 
        strSource 
    ) 
    { 
        return strFirst.toUpperCase() 
        +strRest.toLowerCase(); 
    }); 
} 

function QTipRenderer(val){
   //from: http://extjs.com/forum/showthread.php?p=312581#post312581
   return (val?String.format('<div ext:qtip="{0}" >{0}</div>', val):'');
};
function QTipRenderer2(val, altTip){
   return String.format('<div ext:qtip="{0}" >{1}</div>', altTip, val);
};
function hyperlink(txt, src){
   return String.format('<a href="{0}" >{1}</a>', src, txt);
}
//*********************** various functions

function formatPhoneExt(value, metadata, record, rowIndex, colIndex, store) { 
   return (record.data.phone?formatPhone(record.data.phone)+(record.data.ext?' x'+record.data.ext:''):'');
}
function formatPhone(num) { 
   if (num == "unlisted") {
      return num;
   }
   
   var thenum = new String(num);
   thenum = thenum.replace(/[^0-9]/g, '');
   var _return=false;
   
   if(thenum.length == 10) { 
      _return="("+thenum.substring(0,3)+") "+thenum.substring(3,6)+"-"+thenum.substring(6,10);
   } else if(thenum.length == 7) {
   _return=thenum.substring(0,3)+"-"+thenum.substring(3,7); 
      } else { 
      _return=num;
   }
   return _return; 
} 
function formatSS(num) { 
  var thenum = new String(num);
  thenum = thenum.replace(/[^0-9]/g, '');
  var _return=false;
  // 7181238748 to (718)123-8748 // 

  if(thenum.length != 9) { 
    // if user did not enter 9 digit SSN then simply print whatever user entered // 
	_return=num;
  } else { 
	_return=""+thenum.substring(0,3)+"-"+thenum.substring(3,5)+"-"+thenum.substring(5,9);
  }
  return _return; 
} 

function left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
function right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function verticalText(text) {
   return "<img src='functions/image.php?text=" + text + "' />";
}

function isnum(n) {
   return !isNaN(parseFloat(n)) && isFinite(n);
}

// This is a shared function that simulates a save action on a StatusBar.
// It is reused by most of the example panels.
var saveFn = function(btn, saveFunction, afterSaveFunc){
    btn = Ext.getCmp(btn);
        
    btn.disable();    
        
	saveFunction();
		
    (function(){      
        if ( afterSaveFunc !== undefined ) afterSaveFunc(); 
        btn.enable();
    }).defer(2000);
};

function displayField(field, bool) {
   if (bool) {
      field.show();
   } else {
      field.hide();
   }
}

function hidecolumn(grid, colIndex) { 
   grid.colModel.setHidden(colIndex, true);
   grid.getView().refresh(true);
   grid.doLayout();
}
function showcolumn(grid, colIndex) { 
   grid.colModel.setHidden(colIndex, false);
   grid.getView().refresh(true);
   grid.doLayout();
}

function setForm(form, fields){
   for (id in fields) { //loop through each field
      var val = fields[id];
      var fld = form.findField(id);
      if (fld!=null) fld.setValue(val);
	}
}

function setFieldState(form) {
   //an array of fieldnames
   var i=0, fields = new Array();
   form.items.each(function(c){
		fields[i++] = c.name;
	});
   
   //pass the fields to a server function
   var conn = new Ext.data.Connection().request({
      url: 'pages/applicant-data.json.php',
      method: 'POST',
      params: {schoolid: 'sd', fields: fields.toString(), command: 'getFormSettings'},
      success: function(responseObject) {
         eval("var results = "+responseObject.responseText);
         for (id in results) { //loop through each result
            var curResult = results[id];
            var curField = form.findField(curResult.field);
            
            if (curResult.required != undefined) {
               curField.allowBlank = (!parseInt(curResult.required)); //if !required, set allowblank=true, else false
               //format label
               curField.getEl().up('div.x-form-item').down('label').applyStyles("font-weight:" + (!parseInt(curResult.required)?'normal':'bold'));
            }
            
            if (curResult.visible == false) { // disable it, if !visible
               curField.disable();
               //format label
               curField.getEl().up('div.x-form-item').down('label').applyStyles("font-weight:normal; color:#cccccc;");
            }
      	}
      },
      failure: function() {
         //Ext.Msg.alert('ERROR!', 'Blah Blah Blah...');
      }
   });
}

//stores that are used throughout
statestore       = new Ext.data.Store({ url: 'pages/states.json',            /*no baseParams for this store*/           autoLoad: false, reader: new Ext.data.JsonReader({ root: 'states' }, ['statecd','statename']) });
religionstore    = new Ext.data.Store({ url: 'schooldynamics_data.json.php', baseParams: {command: 'getReligions'},     autoLoad: false, reader: new Ext.data.JsonReader({root: 'religions'}, ['religion','religionid'])});
churchstore      = new Ext.data.Store({ url: 'schooldynamics_data.json.php', baseParams: {command: 'getChurches'},      autoLoad: false, reader: new Ext.data.JsonReader({root: 'churches' }, ['churchid', 'churchname']) });
highschoolstore  = new Ext.data.Store({ url: 'schooldynamics_data.json.php',baseParams: {command: 'getHighSchools'},   autoLoad: false, reader: new Ext.data.JsonReader({root: 'highschools'}, ['highschid', 'highschool']) });
ethnicitystore   = new Ext.data.Store({ url: 'schooldynamics_data.json.php', baseParams: {command: 'getEthnic'},        autoLoad: false, reader: new Ext.data.JsonReader({root: 'ethnic'}, ['ethnicgroup']) });
titlestore       = new Ext.data.Store({ url: 'schooldynamics_data.json.php',baseParams: {command: 'getTitles'},        autoLoad: false, reader: new Ext.data.JsonReader({root: 'titles' }, ['title']) });
relationshipstore= new Ext.data.Store({ url: 'schooldynamics_data.json.php',baseParams: {command: 'getRelationships'}, autoLoad: false, reader: new Ext.data.JsonReader({root: 'relationships' }, ['relationship']) });
maritalstatusstore=new Ext.data.Store({ url: 'schooldynamics_data.json.php',baseParams: {command: 'getMaritalStatus'}, autoLoad: false, reader: new Ext.data.JsonReader({root: 'maritalstatus' }, ['status']) });
carrierstore     = new Ext.data.Store({ url: 'schooldynamics_data.json.php', baseParams: {command: 'getCarrier'},       autoLoad: false, reader: new Ext.data.JsonReader({root: 'carrier'}, ['carrierid', 'carriername']) });
coursebyteacheridstore = new Ext.data.Store({ url: 'schooldynamics_data.json.php', baseParams: {command: 'getcoursesbyteacherid'}, autoLoad: false, reader: new Ext.data.JsonReader({ root: 'courses', idProperty:'courseid' }, ['courseid','course', 'coursedisplay', {name:'gradetype', type:'bool'}, 'gradingmethod']) });
getgrades = new Ext.data.Store({ url: 'schooldynamics_data.json.php', baseParams: {command: 'getgrades'}, autoLoad: false, reader: new Ext.data.JsonReader({ root: 'grades' }, ['grade']) });
getrooms = new Ext.data.Store({ url: 'schooldynamics_data.json.php', baseParams: {command: 'getRooms'}, autoLoad: false, reader: new Ext.data.JsonReader({ root: 'roomno' }, ['roomno']) });
getgradesbyteacherid = new Ext.data.Store({ url: 'schooldynamics_data.json.php', baseParams: {command: 'getgradesbyteacherid'}, autoLoad: false, reader: new Ext.data.JsonReader({ root: 'grades' }, ['grade']) });
activestudentnamestore = new Ext.data.Store({ url: 'schooldynamics_data.json.php', baseParams: {command: 'getActiveStudents'}, autoLoad: false, reader: new Ext.data.JsonReader({ root: 'studentNames' }, ['studentid', 'studentname']) });
activeteachernamestore = new Ext.data.Store({ url: 'schooldynamics_data.json.php', baseParams: {command: 'getActiveTeachers'}, autoLoad: false, reader: new Ext.data.JsonReader({ root: 'teacherNames' }, ['teacherid', 'teachername']) });
coursebyteacheridViewAllstore = new Ext.data.Store({ url: coursebyteacheridstore.url, baseParams: coursebyteacheridstore.baseParams, autoLoad: false, reader: coursebyteacheridstore.reader });
coursebyteacheridViewAllstore.on('load', function(store, records, options) {store.insert(0, new Ext.data.Record({courseid:'ALL_COURSES', course: 'View All Courses'}));});
courseActivestore = new Ext.data.Store({ url: coursebyteacheridstore.url, baseParams: {command: 'getactivecourses'}, autoLoad: false, reader: coursebyteacheridstore.reader });
coursebystudentstore = new Ext.data.Store({ url: coursebyteacheridstore.url, baseParams: {command: 'getstudentcourses'}, autoLoad: false, reader: coursebyteacheridstore.reader });
reasonstore = new Ext.data.Store
({
  url: 'teacher_tools/attendance_data.json.php', baseParams: {command: 'getReasons'}, autoLoad: false, reader: new Ext.data.JsonReader({root: 'reasons'}, [{name: 'reasons'}, {name: 'reasonid'}, {name: 'type'}]),
  filter : function(property, value, anyMatch, caseSensitive){
      var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
      this.filterProperty = property;
      this.filterValue = value;
      return fn ? this.filterBy(fn) : this.clearFilter();
  },
  listeners: {
    beforeload: function(){
      if (this.loaded) { return false }
            this.loaded = true;
    },
    load: function(){
      this.filter(this.filterProperty, this.filterValue);
      this.mode = 'local';
    }
  }
}); 

//******************
// Add days to date.
// Params:
// txtDate: date as string
// days: number of days to add, -ve to subtract
// usFormat: true = US format, false = UK format
// Return: new date as string

function DateAdd(txtDate, days, usFormat)
{
    var newDateStr;
    var dateParts = txtDate.split(/[^0-9]+/);

    var year = Number(dateParts[2]);
    if (year < 50)  // so 0-49 becomes 2000-2049, 50-99 become 1950-1999 
        year += 2000;
    else if (year < 100)
        year += 1900;
    var unixDate;
    if (usFormat)
        unixDate = new Date(year.toString(), dateParts[0]-1, dateParts[1]);
    else
        unixDate = new Date(year.toString(), dateParts[1]-1, dateParts[0]);
    unixDate = new Date(unixDate.getTime() + days * 24 * 60 * 60 * 1000);

    var newDay = unixDate.getDate().toString();
    var newMonth = (unixDate.getMonth()+1).toString();
    var newYear = unixDate.getFullYear().toString();
    if (usFormat)
        newDateStr = (newMonth + "/" + newDay + "/" + newYear);
    else
        newDateStr = (newDay + "/" + newMonth + "/" + newYear);
    return newDateStr;
}

function getWeekOf(today) {
   if (!today) today = new Date();
   var day = today.getDate();
   var month = today.getMonth() + 1;
   var year = today.getYear();
   if (year < 2000)
      year = year + 1900;
   var offset = today.getDay();
   var week;
   
   
   if(offset != 0) {
      //day = day - offset; // sunday of this week
      day = day - offset +1; // monday of this week
      
      if ( day < 1) {
         if (month == 1) day = 31 + day;
         if (month == 2) day = 31 + day;
         if (month == 3) {
            if (( year == 00) || ( year == 04)) {
               day = 29 + day;
            } else {
               day = 28 + day;
            }
         }
         if (month == 4) day = 31 + day;
         if (month == 5) day = 30 + day;
         if (month == 6) day = 31 + day;
         if (month == 7) day = 30 + day;
         if (month == 8) day = 31 + day;
         if (month == 9) day = 31 + day;
         if (month == 10) day = 30 + day;
         if (month == 11) day = 31 + day;
         if (month == 12) day = 30 + day;
         if (month == 1) {
            month = 12;
            year = year - 1;
         } else {
            month = month - 1;
         }
      }
   }   
   week = month + "/" + day + "/" + year; // i.e. 10/31/99
   return week;
}


function downloadFileContents(url, baseParams) {
   var frame = Ext.get('iframe');
   var form = Ext.get('form');
   
   if(frame!=null) {
      form.remove();
      frame.remove();
   }
   
   var body = Ext.getBody();
   frame = body.createChild({tag:'iframe',cls:'x-hidden',id:'iframe',name:'iframe'});
   form = body.createChild({tag:'form',cls:'x-hidden',id:'form',action:url,target:'iframe',method:'POST'});
   
   for(param in baseParams) {
      //console.log(param+"|"+baseParams[param]);
      var field = Ext.get(param);
      if(field!=null) {
         //console.log(field);
         field.remove();
      }
      field=document.createElement('input');
      field.name=param;
      field.cls='x-hidden';
      document.forms.form.appendChild(field);
      field.value= baseParams[param];
   }
   
   form.dom.submit();
}

/***********************************************************
 * TimeZone namespace, with functions related to timezone */
Ext.namespace('TimeZone');

TimeZone.isTzSet = function() {
  var tzSet;
  Ext.Ajax.request({
     url: 'schooldynamics_data.json.php',
     params: { command: 'isTimezoneSet' },
     async : false,
     success: function(r){
        tzSet = (r.responseText.trim() == 'true');
     }
  });
  return tzSet;
  
}
//returns true, if timezone was set
TimeZone.setTimeZone = function(location) {
  var retval = false;
  Ext.Ajax.request({
    url: 'main_menu/timeclock_data.json.php',
    params: { command: 'setTZ', location:location },
    async: false,
    success: function(form) {
       retval = true;
    },
    failure: function(form, response) {
        Ext.Msg.alert('ERROR','Failure: Could not set Time Zone');
    }                  
  }); 
  return retval; 
}
TimeZone.getTimeZone = function() {
  var tz;
  Ext.Ajax.request({
     url: 'schooldynamics_data.json.php',
     params: { command: 'getTimezoneSet' },
     async : false,
     success: function(r){
        tz = Ext.util.JSON.decode(r.responseText.trim());
     }
  });
  return tz;
}
/**************** END: TimeZone namespace ****************/


function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // from: http://phpjs.org/functions/in_array:432
    // version: 1004.1212
    // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) return true;
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) return true;
        }
    }
     return false;
}
function key_exists (key, haystack, argStrict) {
    var strict = !!argStrict; 
    if (strict) {
        for (k in haystack) {
            if (k === key) return true;
        }
    } else {
        for (k in haystack) {
            if (k == key) return true;
        }
    }
     return false;
}

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}
function strpos (haystack, needle, offset) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman    
    // +   bugfixed by: Daniel Esteban
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14

    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}
/*******************************************************
 * Universally used Ext.form.fields
 */
SchoolDynamics.homeroomCombo = Ext.extend(Ext.form.ComboBox, {
   constructor: function(config){
      SchoolDynamics.homeroomCombo.superclass.constructor.apply(this, arguments);
   },
   store: new Ext.data.Store({
      url : 'schooldynamics_data.json.php',
      baseParams: {command: 'getHomerooms'},
      reader: new Ext.data.JsonReader({root: 'homerooms'}, [            
         {name: 'orderno'},
         {name: 'homeroom'},             
      ]),
      autoLoad : false
   }), 
   listWidth:50,
   xtype: 'combo',
   width: 50,
   allowBlank: false,    
   displayField: 'homeroom', 
   valueField: 'orderno', 
   valueNotFoundText:"", 
   typeAhead: true, 
   triggerAction: 'all'
});

SchoolDynamics.coursesCombo = Ext.extend(Ext.form.ComboBox, {
   constructor: function(config){
      SchoolDynamics.coursesCombo.superclass.constructor.apply(this, arguments);
      this.store.storeId = this.id+'_store';
      Ext.StoreMgr.register(this.store);
   },
   store: coursebyteacheridstore, 
   tpl: new Ext.XTemplate(
     '<tpl for="."><div class="course-item" style="overflow: hidden;height:15px">',
      '<div class="floatLeft" style=" width:100%;margin-right:-98px;">{course}</div>',
         '<div class="floatRight" style="width: 95px;">{courseid}</div>',
      
     '</div></tpl>'
   ),
   itemSelector: 'div.course-item',
   xtype: 'combo',
   width: 200,
   listWidth:300,
   editable: false, 
   allowBlank: true, 
   fieldLabel: 'Course', 
   displayField: 'coursedisplay', 
   valueField: 'courseid', 
   valueNotFoundText:'', 
   emptyText: 'Select a course...',
   typeAhead: true, 
   triggerAction: 'all'
});

SchoolDynamics.coursesViewAllCombo = Ext.extend(SchoolDynamics.coursesCombo, {
   constructor: function(config){
      SchoolDynamics.coursesViewAllCombo.superclass.constructor.apply(this, arguments);
   },
   store: coursebyteacheridViewAllstore
});


SchoolDynamics.coursesActiveCombo = Ext.extend(SchoolDynamics.coursesCombo, {
   constructor: function(config){
      SchoolDynamics.coursesActiveCombo.superclass.constructor.apply(this, arguments);
   },
   store: courseActivestore
});


SchoolDynamics.coursesStudentCombo = Ext.extend(SchoolDynamics.coursesCombo, {
   constructor: function(config){
      SchoolDynamics.coursesStudentCombo.superclass.constructor.apply(this, arguments);
   },
   store: coursebystudentstore
});
SchoolDynamics.weekofDatefield = Ext.extend(Ext.form.DateField, {
   constructor: function(config){
      //events to apply to all instances of this control
      this.on('change', function( datefield, newValue, oldValue) {
         datefield.setValue(getWeekOf(newValue));
      });
      this.on('render', function( datefield ) {
         datefield.fireEvent('change', this, new Date(), new Date());
      });
      
      SchoolDynamics.weekofDatefield.superclass.constructor.apply(this, arguments);
   }, 
   width: 100,
   allowBlank: false,   
   fieldLabel: 'Week'
});


SchoolDynamics.apprenticeCombo = Ext.extend(Ext.form.ComboBox, {
   constructor: function(config){
      //events to apply to all instances of this control
      this.on('setValue', function( combo, newValue, oldValue) {
         var cmbIndex = combo.store.find('teacher', combo.getValue());
         if (-1<cmbIndex)return; //prevent duplicate setValue
         if (oldValue!=undefined && newValue.toLowerCase()==oldValue.toLowerCase()) return; //prevent redundant setValue
         
         var apprentice = combo.store.getById(combo.getValue());
         if (apprentice==undefined) return;
         apprentice = apprentice.data.teacherid;
         Ext.each(combo.storeArray, function(storeId) {
            var store = Ext.StoreMgr.lookup(storeId);
            if (SchoolDynamics.TeacherID.toLowerCase()==apprentice.toLowerCase()) {
               Ext.destroy(store.baseParams.apprentice);
            } else {
               store.baseParams.apprentice = apprentice;
            }
            store.load();
         });
      });
      SchoolDynamics.apprenticeCombo.superclass.constructor.apply(this, arguments);
   }, 
   store: new Ext.data.Store({
      url : 'schooldynamics_data.json.php',
      baseParams: {command: 'getMentoredTeachers'},
      reader: new Ext.data.JsonReader({
         root: 'teachers',
         idProperty: 'teacherid'
      }, [
         {name: 'teacherid'},
         {name: 'teacher'}
      ]),
      autoLoad : false
   }), 
   listWidth:150,
   xtype: 'combo',
   width: 150,
   allowBlank: true,
   displayField: 'teacher', 
   valueField: 'teacherid', 
   valueNotFoundText:"", 
   typeAhead: true, 
   triggerAction: 'all'
});

SchoolDynamics.quarterCombo = Ext.extend(Ext.form.ComboBox, {
   constructor: function(config){
      this.on('render', function( combo ) {
         this.fireEvent('select', this, new Ext.data.Record({field1:SchoolDynamics.currentQtr}));
      });
      SchoolDynamics.quarterCombo.superclass.constructor.apply(this, arguments);
   }, 
   style: 'margin-left: 5px;',
   xtype: 'combo',
   listWidth:60,
   width: 60,
   allowBlank: true,    
   valueNotFoundText:"", 
   editable: false,
   typeAhead: true,
   triggerAction: 'all',
   store: [1,2,3,4,5]
});

/******************************************************/
