var CS2 = {
  version : '2.1.0',
  quickPop : 500,
  longPop : 1000,
  countDownSpeed : 400,
  schoolVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "School" : "Site"},
  districtVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "District" : "Site"},
  schoolsVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "Schools" : "SubSites"},
  schoolSubsiteVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "School" : "SubSite"},
  schoolStoreVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "School" : "Store"},
  cyberschoolVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "CyberSchool" : "eBusiness"},
  cyberschoolSiteVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "CyberSchool" : "Site"},
  teacherVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "Teacher" : "a Moderator"},
  aTeacherVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "a Teacher" : "a Moderator"},
  studentVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "Student" : "Member"},
  studentsVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "Students" : "Members"},
  studentsVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "Students" : "Members"},
  studentEmployeeVerbage: function(){return currentSchool.Type == "CyberSchool 2.0" ? "Students" : "Employees"},
  isEbusiness: function(){return currentSchool.Type == "eBusiness 2.0"},
  isCyberSchool: function(){return currentSchool.Type == "CyberSchool 2.0"},
  isCyberDesk: function(){return currentSchool.Type == "CyberDesk"}
};

Ext.Ajax.defaultHeaders = {
  'Created-By': 'da404lewzer',
  'Powered-By': 'CyberSchool v' + CS2.version
};

Ext.override(Ext.tree.TreeNode, {
  clone: function() {
    var atts = this.attributes;
    atts.id = Ext.id(null, "ynode-");
    var clone = new Ext.tree.TreeNode(Ext.apply({}, atts));
    clone.text = this.text;
    for(var i=0; i<this.childNodes.length; i++){
      clone.appendChild(this.childNodes[i].clone());
    }
    return clone;
  }
});

Ext.apply(Ext.form.VTypes, {
  username:  function(v) {
    return /^[a-zA-Z]{1}[0-9a-zA-Z_]+$/.test(v);
  },
  usernameText: 'Usernames may contain uppercase, lowercase, numbers, and underscores. Usernames must start with a letter.',
  usernameMask: /[0-9a-zA-Z_]/i,
  password:  function(v) {
    return /^[0-9a-zA-Z!@#\$%\^&\*\(\)\-_=\+]+$/.test(v);
  },
  passwordText: 'Password may contain uppercase, lowercase, numbers, or the special characters: !@#$%^&*()-_=+',
  passwordMask: /[0-9a-zA-Z!@#\$%\^&\*\(\)\-_=\+]/i
});

function getProfileImage(id){
  return "/images/getProfilePicture.cfm?id="+id+"&t="+ parseInt(new Date().getTime().toString().substring(0, 10));
}

Ext.override(Ext.layout.CardLayout, {
  renderItem: function(c){
    if(!this.deferredRender && c && c.doLayout && !c.rendered){
        c.forceLayout = true;
    }
    Ext.layout.CardLayout.superclass.renderItem.apply(this, arguments);
  }
});




/* sandbox */

function importICAL(opts){
  return new CS2.importData.iCal(opts);
}
CS2.importData = {};
CS2.importData.iCal = function(initOptions){
  var _self = this;
  this._settings = {};
  Ext.apply(this._settings, initOptions);

  this.uploadSuggestion = new Ext.XTemplate(
    '<strong>US Holidays</strong> by Google &ndash; ',
    '<a id={[this.makeImportLink(values)]} href="http://www.google.com/calendar/ical/en.usa%23holiday%40group.v.calendar.google.com/public/basic.ics">Import</a>',
    '<br />',
    '<strong>Phases of the Moon</strong> by Google &ndash; ',
    '<a id={[this.makeImportLink(values)]} href="http://www.google.com/calendar/ical/ht3jlfaac5lfd6263ulfh4tql8%40group.calendar.google.com/public/basic.ics">Import</a>',
    {
      makeImportLink: function(values, ref){
        var result = Ext.id();
        this.addListener.defer(1, this, [result, values]);
        return result;
      },
      addListener: function(id, values) {
          Ext.get(id).on('click', function(e){
            e.stopEvent();
            
            _self.uploadContainer.urlInput.setValue(this.dom.href);
            _self.uploadContainer.urlICAL.setValue(true);
            _self.checkNext();
          })
      }
    }
  );

  this.checkNext = function(type){
    if (type == "file")
      _self.uploadContainer.fileICAL.setValue(true);
    else
    _self.uploadContainer.urlICAL.setValue(true);
  
    if (_self.uploadContainer.fileInput.getValue() != '' || _self.uploadContainer.urlInput.getValue() != ''){
      _self.win.nextBtn.setDisabled(false);
    }else{
      _self.win.nextBtn.setDisabled(true);
    }
  
  };

  this.uploadContainer = new Ext.FormPanel({
                                            labelWidth: 15,
                                            region: 'center',
                                            clientValidation: true,
                                            standardSubmit:false, 
                                            fileUpload: true,
                                            isUpload: true,
                                            method: 'POST',
                                            border: true,
                                            items: [{
                                                      border: false,
                                                      xtype:'fieldset',
                                                      defaults: {
                                                        anchor: Ext.isMac ? '-20' : '-10'
                                                      },
                                                      defaultType: 'textfield',
                                                      items :[{
                                                                xtype: 'radio',
                                                                ref: '../fileICAL',
                                                                checked: true,
                                                                hideLabel: true,
                                                                boxLabel: 'I would like to upload an ICAL file...',
                                                                name: 'iCalType',
                                                                inputValue: 'file'
                                                              },{
                                                                xtype: 'fileuploadfield',
                                                                emptyText: 'Select an .ICS file',
                                                                fieldLabel: '',
                                                                name: 'iCalFile',
                                                                enableKeyEvents: true,
                                                                ref: '../fileInput',
                                                                allowBlank: true,
                                                                buttonText: '',
                                                                listeners: {
                                                                  blur: _self.checkNext.createDelegate(this, ['file'], false),
                                                                  keydown: _self.checkNext.createDelegate(this, ['file'], false),
                                                                  fileselected: _self.checkNext.createDelegate(this, ['file'], false)
                                                                },
                                                                buttonCfg: {
                                                                    iconCls: 'upload-icon'
                                                                }
                                                              },{
                                                                xtype: 'radio',
                                                                ref: '../urlICAL',
                                                                hideLabel: true,
                                                                boxLabel: 'I would like to specify a URL...',
                                                                name: 'iCalType',
                                                                inputValue: 'url'
                                                              },{
                                                                xtype: 'textfield',
                                                                ref: '../urlInput',
                                                                emptyText: 'Specify a URL',
                                                                name: 'iCalURL',
                                                                fieldLabel: '',
                                                                allowBlank: true,
                                                                enableKeyEvents: true,
                                                                listeners: {
                                                                  blur: _self.checkNext.createDelegate(this, ['url'], false),
                                                                  keydown: _self.checkNext.createDelegate(this, ['url'], false),
                                                                  change: _self.checkNext.createDelegate(this, ['url'], false)
                                                                }
                                                              },{
                                                                xtype: 'displayfield',
                                                                hideLabel: false,
                                                                fieldLabel: '',
                                                                html: this.uploadSuggestion.apply()
                                                              }]
                                                    }]
                                          });

  this.uploadIcal = function(){
    Ext.Msg.wait('Uploading iCal File', 'Please wait...');
    _self.uploadContainer.getForm().submit({
                                            clientValidation: true, 
                                            standardSubmit:false, 
                                            fileUpload:true,
                                            isUpload: true,
                                            method: 'POST',
                                            url:'/ajax/editor/uploadICAL.cfm?t=_',
                                            params: {
                                              id: 0 //_self._settings.editorDataID
                                            },
                                            reader : new Ext.data.JsonReader({
                                              success : '@success'
                                            }),
                                            success: function(form, action) {
                                              //var jsonData = Ext.util.JSON.decode(action.result.responseText);
                                              var data = action.result.events;
                                              _self.eventStore.loadData(action.result);
                                              Ext.Msg.hide();
                                              _self.winImport.show(_self);
                                              setTimeout(function(){
                                                _self.gridICAL.getSelectionModel().selectAll();
                                              }, 10);
                                            },
                                            failure: function(form, action) {
                                              Ext.Msg.hide();
                                              switch (action.failureType) {
                                                  case Ext.form.Action.CLIENT_INVALID:
                                                      Ext.Msg.alert('Failure', 'Please verify fields are correct.');
                                                      break;
                                                  case Ext.form.Action.CONNECT_FAILURE:
                                                      Ext.Msg.alert('Failure', 'Ajax communication failed');
                                                      break;
                                                  case Ext.form.Action.SERVER_INVALID:
                                                  default:
                                                      Ext.Msg.alert('Failure', action.result.msg);
                                              }
                                            }
                                          });
  }

  this.win = new Ext.Window({
    title: 'iCal Import <span class="betaText">Beta</span>',
    iconCls: 'cpi_userSettings',
    layout:'fit',
    resizable: false,
    padding: 5,
    width: 500,
    height: 280,
    modal: true,
    constrainHeader:true,
    buttons: [{
      text: 'Next...',
      ref: '../nextBtn',
      disabled: true,
      handler: this.uploadIcal
    }],
    listeners: {
      show: function(win){
        Ext.Msg.hide();
      }
    },
    items: new Ext.Panel({
      layout: 'border',
      border: false,
      items: [
                this.uploadContainer,
                new Ext.Panel({
                                region: 'south',
                                height: 50,
                                padding: 10,
                                margins: '5 0 0 0',
                                bodyStyle: 'font-size: 12px; text-align: center;',
                                html: '<strong>Notice: This module is currently in beta status and may still have bugs.</strong><br /> If you find problems or have suggestions <a href="mailto:luis@iescentral.com?subject=iCal%20Import">submit them via Email</a>.'
                              })
              ]
    })
  });

  this.newEvent = Ext.data.Record.create([
    {name:'id', type: 'id'}, 
    {name:'checked', type: 'bool'}, 
    {name:'title', type: 'string'}, 
    {name:'description', type: 'string'}, 
    {name:'start', type:'date', dateFormat:'m/d/y'},
    {name:'end', type:'date', dateFormat:'m/d/y'}
  ]);


  this.eventStore = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      api: {
        create : '/ajax/dayPlanner/events/updateEvents.cfm',
        read : '/ajax/dayPlanner/events/updateEvents.cfm',
        update: '/ajax/dayPlanner/events/updateEvents.cfm',
        destroy: '/ajax/dayPlanner/events/updateEvents.cfm'
      }
    }),
    reader: new Ext.data.JsonReader({
      root: 'events',
      idProperty: 'id',
    }, this.newEvent),
    writer: new Ext.data.JsonWriter({
      encode: true,
      listful: true,
      writeAllFields: true
    }),
  });
  var sm = new Ext.grid.CheckboxSelectionModel({
                                                  dataIndex: 'checked',
                                                  checkOnly: true,
                                                  listeners: {
                                                    selectionchange: function(sm){
                                                      _self.winImport.importBtn.setDisabled(!sm.getCount());
                                                    }
                                                  }
                                                });
  this.gridICAL = new Ext.grid.EditorGridPanel({
    store: this.eventStore,
    clicksToEdit: 1,
    autoExpandColumn: 'colIcalTitle',
    /*tbar: [
      {text: 'Filter'}
    ],*/
    cm: new Ext.grid.ColumnModel({
      defaults: {
        width: 120,
        sortable: true
      },
      columns: [
        sm,
        {header: "Title", id: 'colIcalTitle', width: 150, dataIndex: 'title',
          editor: new Ext.form.TextField({
            allowBlank: false
          })
        },
        {header: "Description", width: 200, dataIndex: 'description',
          editor: new Ext.form.TextField({
            allowBlank: true
          })
        },
        {header: "Start", width: 80, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'start',
          editor: new Ext.form.DateField({
            format: 'm/d/y'
          })
        },
        {header: "End", width: 80, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'end',
          editor: new Ext.form.DateField({
            format: 'm/d/y'
          })
        }
      ]
    }),
    sm: sm,
    columnLines: true
  });

  this.winImport = new Ext.Window({
    title: 'iCal Import <span class="betaText">Beta</span>',
    iconCls: 'cpi_userSettings',
    layout:'fit',
    resizable: false,
    padding: 5,
    width: 600,
    height: 400,
    modal: true,
    constrainHeader:true,
    buttons: [{
                text: 'Import',
                ref: '../importBtn',
                disabled: true,
                handler: function(){
                  Ext.Msg.wait('Importing Selected Data', 'Please wait...');
                  var data = _self.gridICAL.getSelectionModel().getSelections();
                  var newData = [];
                  for(var n = 0; n < data.length; n++)
                    newData.push(data[n].data);
                    
                  Ext.Ajax.request({
                    url: '/ajax/editor/applyICAL.cfm?t=_',
                    params: {
                      gcdID: _self._settings.editorGCDID,
                      calData: Ext.util.JSON.encode(newData)
                    },
                    reader : new Ext.data.JsonReader({
                      success : '@success'
                    }),
                    success: function(){
                      Ext.Msg.hide();
                      Ext.Msg.alert('Success!', 'Your data was successfully imported! You may need to refresh the page to see your changes.');
                      _self.winImport.close();
                      _self.win.close();
                    },
                    failure: function(){
                      Ext.Msg.hide();
                      Ext.Msg.alert('Error', 'There was an error storing your iCal entries.');
                    }
                  });
                  
                }
              },{
                text: 'Cancel',
                handler: function(){
                  _self.winImport.close();
                  _self.win.close();
                }
              }],
    listeners: {
      show: function(win){
        Ext.Msg.hide();
      }
    },
    items: new Ext.Panel({
                          layout: 'border',
                          border: false,
                          items: [
                                  new Ext.Panel({
                                    region: 'north',
                                    height: 35,
                                    padding: 10,
                                    margins: '0 0 5 0',
                                    bodyStyle: 'font-size: 14px; text-align: center;',
                                    html: 'Un-select items from the list you wish to ignore.'
                                  }),
                                   new Ext.Panel({
                                    region: 'south',
                                    height: 50,
                                    padding: 10,
                                    margins: '5 0 0 0',
                                    bodyStyle: 'font-size: 12px; text-align: center;',
                                    html: '<strong>Notice: This module is currently in beta status and may still have bugs.</strong><br /> If you find problems or have suggestions <a href="mailto:luis@iescentral.com?subject=iCal%20Import">submit them via Email</a>.'
                                  }),
                                  new Ext.Panel({
                                    region: 'center',
                                    border: false,
                                    layout: 'fit',
                                    items: this.gridICAL
                                  })
                                ]
                          })
  });
  
  this.win.show(this);

}

