window.addEvent('domready',function(){
  if($chk($('ImmForm')))
  {
    if($('ImmForm').getElements('input[name=phone]')){
      var pn = $('ImmForm').getElements('input[name=phone]');
      pn.each(function(i){

        v = i.value;
        var val = v.replace(/[^0-9]/ig,'');
        if(val.length == 10 || val =='')
        {
          i.setStyle('display','none');
          var area = new Element('input',{
            'name':'area',
            'size':3,
            'maxlength':3,
            'class':'col pad txt inputItem',
            'style':'width:auto;margin-right:5px;',
            'type':'text'
          }).addEvent('keyup',nextSet);
          var first = new Element('input',{
            'name':'first',
            'size':3,
            'maxlength':3,
            'style':'width:auto;margin-right:5px;',
            'class':'col pad txt inputItem',
            'type':'text'
          }).addEvent('keyup',nextSet);
          var last = new Element('input',{
            'name':'last',
            'size':4,
            'maxlength':4,
            'class':'col pad txt inputItem',
            'style':'width:auto',
            'type':'text'
          }).addEvent('keyup',nextSet);
          area.injectAfter(i);
          first.injectAfter(area);
          last.injectAfter(first);
          if(val != '')
          {
            area.value = val.substring(0,3);
            first.value = val.substring(3,6);
            last.value = val.substring(6,10);
          }
        }


      })
    }
  }
  
});
var nextSet = function(eve)
{
  var e   = new Event(eve).stop();
  var si  = $(e.target).getProperty('size');
  var va  = $(e.target).value.length;
  var par = $(e.target).getParent();

  if(si == va){
    switch($(e.target).getProperty('name'))
    {
      case 'area':
        par.getElement('input[name=first]').focus();
        break;
      case 'first':
        par.getElement('input[name=last]').focus();
        break;
    }
  }
  var itms = ['area','first','last'];
  var setPhone = '';
  itms.each(function(i){
    setPhone += par.getElement('input[name='+i+']').value;
  });
  par.getElement('input[name=phone]').value = setPhone;
}
function validateCheckbox(ele) {
  var chold = $(ele).getParent();
  var btn = chold.getElements('input');
  for(i=0;i<btn.length;i++){
    if(btn[i].checked) return true;
  }
  return false;
}
function changeInputBg(ele) {
  var chold = $(ele).getParent();
  chold.addEvent('mouseover',function(){
    this.setStyle('background','#FFFFCC')
  });
  return false;
}
String.prototype.stripSpaces = function( ){
  return this.replace( /\s/g, "" );
};
String.prototype.stripDashes = function( ){
  return this.replace( /-/g, "" );
};
String.prototype.stripReturn = function( ){
  return this.replace( /\n/g,"" );
};
var ImmForm = new Class({
  initialize: function(name){
    this.name = name;
    this.stat = new Array();
    this.msgs = new Array();
    this.track = new Array();
    this.tried = 0;
    this.submitButton = '';
    this.savedSubmit  = '';
    window.addEvent('load',this.sLo.bind(this));
    var icon  = '/img/icons/ajax-loader.gif';
    this.loadIcon = new Asset.image(icon);
    $(this.name).addEvent('submit',this.waitForSubmit.bind(this));
  },
  waitForSubmit:function(eve){
    if(this.stat.length == 0){
      var e = new Event(eve);
      this.submitButton = e.target.getElement('input[type=submit]');
      this.savedSubmit = this.submitButton.value;
      this.submitButton.value = 'Please Wait...';
      this.submitButton.disabled = true;
    }
  },
  sLo: function(){
    this.pl = true;
  },
  abortUpload: function(){
    $('uploadBox').setHTML('<div class="upCount ui">Upload Aborted</div>');

    var fade = new Fx.Style($('uploadBox'),'opacity',{
      duration:1500
    }).start(1,0);
    fade.addEvent('onComplete',function(){
      $('uploadBox').remove();
      $('uploadBg').remove();
    });
  },
  uploadStatus: function(tFile){
    var jr = new XHR({
      method: "get",
      autoCancel: true,
      onFailure: this.abortUpload.bind(this),
      onSuccess: function(i) {
        var info = Json.evaluate(i);
        if(i=='') return;
        /*				if(info.cancel_upload && info.cancel_upload!=0) {
				this.abortUpload();
				return;
				}*/
        if($defined(info.current) && info.current > 0) {
          this.infoCurrent = info.current;
          var percent      = ((info.current / info.total) * 100).round();
          $('nob').setStyle('width',percent + '%');
          $('upd').setHTML(percent + '%');
          $('dataSent').value = this.bandwidthConvert(info.current) + ' / ' + this.bandwidthConvert(info.total);
          $('upCount').setHTML(this.upTotal + (this.upTotal>1?' Files <span style="color:red;">Note: Info may not update.</span>':' File'));
          /*			if(this.upTotal>1) {
					$('upd').setStyle('display','none');
					$('nob').setStyle('display','none');
					$('dataSent').value = 'Total Size: ' +this.bandwidthConvert(info.total);
					}*/
          if(0) {
            if(this.triggerUpdate()) {
              $('uploadBox').setHTML('<div class="uploadDone">Done!</div>');
            }
          } else {
            (function(){
              this.uploadStatus(tFile)
            }).delay(1000,this);
          }
        } else {
          if(this.tried < 6) {
            (function(){
              this.uploadStatus(tFile)
            }).delay(1000,this);
          } else {
            $('uploadBox').setHTML('<div class="uploadDone">Failed to monitor upload</div>');
          }
          this.tried++;
        }
      }.bind(this)
    }).send('/uprogress', 'k='+tFile);
  },
  trackUpload: function(k){
    this.track.push(k);
  },
  triggerUpdate:function(){
    if(this.track.length > 0) {
      var tFile = this.track.pop();
      this.infoCurrent = this.sChk = 0;
      (function(){
        this.uploadStatus(tFile)
      }).delay(1000,this);
      return false;
    } else return true;
  },
  triggerUpload: function(){
    this.currentFile = 0;
    this.upTotal = this.track.length;
    var uBox = '<div class="upCount ui">Uploading: <span id="upCount">&nbsp;</span></div> \
      	         <div class="upSent ui">Progress: <input id="dataSent" size="20" />	</div> \
      	         <div id="slider"><div id="nob">&nbsp;</div></div> \
      	         <img src="/design/icons/uploading.gif" id="aIcon" /> \
      	         <div id="upd">0%</div>';
    var bg  = new Element('div',{
      'id':'uploadBg'
    }).setHTML('&nbsp;').injectInside(document.body);
    var box = new Element('div',{
      'id':'uploadBox'
    }).setHTML(uBox).injectAfter(bg);
    //new Fx.Style(bg, 'opacity', {duration:500}).start(0,1);
    window.scroll(0,-1000);
    this.triggerUpdate();
  },
  uploadWait: function(){
    this.currentFile = 0;
    this.upTotal = this.track.length;
    var uBox 	= '<div class="pw"><h2>Please Wait While Your File Uploads</h2><img src="/img/icons/ajax-loader.gif" /></div>';
    var bg  	= new Element('div',{
      'id':'uploadBg'
    }).setHTML('&nbsp;').injectInside(document.body);
    var box 	= new Element('div',{
      'id':'uploadBox'
    }).setHTML(uBox).injectAfter(bg).centerElement(bg);
    window.scroll(0,-1000);
  },
  bandwidthConvert: function(n){
    var ns  = new String(n);
    var nl = ns.length;
    var num = n
    if(nl < 4) return num + 'b';
    if(nl > 3 && nl < 7) return (num / 1024).round(1) + 'kb';
    if(nl > 6 && nl < 12) return ((num / 1024) / 1024).round(2) + 'mb';
    if(nl > 11) return (((num / 1024) / 1024) / 1024).round(1) + 'gb';
    return ns.lenght;
  },
  clearPrevious: function(){
    this.stat = new Array();
    this.msgs = new Array();
  },
  checkExpdate: function(id,msg){
    if(!$(id).value.test("^((0[1-9])|(1[0-2]))\/(\\d{2})$")){
      console.log($(id).value);
      this.stat.extend([id]);
      this.msgs.extend([msg]);
    }
  },
  checkCCT1: function(id,msg){
    var n = $(id).value.stripDashes().stripSpaces();
    if(!n.test("^((\\*{12}\\d{4})|(\\d{16}))$")) {
      this.stat.extend([id]);
      this.msgs.extend([msg]);
    }
  },
  checkNumeric: function(id,msg){
    $(id).value = $(id).value.replace(',','');
    if(!IsNumeric($(id).value) || $(id).value == ''){
      this.stat.extend([id]);
      this.msgs.extend([msg]);
    }
  },
  checkEmail: function(id,msg){
    if(!validateEmail(id) || $(id).value == ''){
      this.stat.extend([id]);
      this.msgs.extend([msg]);
    }
  },
  checkMoney: function(id,msg){
    if(!$(id).value.test("^\\d*\.\\d{2}$")) {
      this.stat.extend([id]);
      this.msgs.extend([msg]);
    }
  },
  cEmp: function(req) {
    req.each(function(val){
      this.checkEmpty(val[0],val[1]);
    }.bind(this));
  },
  cEmail: function(req) {
    req.each(function(val){
      this.checkEmail(val[0],val[1]);
    }.bind(this));
  },
  checkEmpty: function(id,msg){
    var iTT = $(id).getTag();
    if(iTT == 'input') {
      var iT = $(id).getProperty('type');
    } else {
      if(iTT == 'select') {
        iT = 'text';
      } else {
        iT = iTT;
      }
    }
    if(!iT) return false;
    switch(iT){
      case 'textarea':
        var rel = $(id).getProperty('rel');
        if(rel=='ckedit') {
          var e = CKEDITOR.instances[id];
          var txtVal = e.getData();
        } else {
          var txtVal = $(id).value;
        }
        if(txtVal == '') {
          this.stat.extend([id]);
          this.msgs.extend([msg]);
        }
        break;
      case 'password':
      case 'text':
      case 'file':
        if($(id).value == '') {
          this.stat.extend([id]);
          this.msgs.extend([msg]);
        }
        break;
      case 'checkbox':
        if(!validateCheckbox(id)){
          this.stat.extend([id]);
          this.msgs.extend([msg]);
        }
        break;
      case 'radio':
        if(!validateRadio(id)){
          this.stat.extend([id]);
          this.msgs.extend([msg]);
        }
        break;
      case 'hidden':
        $(id).addEvent('domready',function(){
          var oEditor = FCKeditorAPI.GetInstance(id);
          if(oEditor.GetHTML() == ''){
            this.stat.extend([id]);
            this.msgs.extend([msg]);
          }
        }.bind(this));
        break;
      default:
        console.log('No check for ' + iT + ' Tag type ' + $(id).getTag());
        break;
    }
  },
  highlightErrors: function(){
    for(i=0;i<this.stat.length;i++){
      var iT = $(this.stat[i]).getProperty('type');
      if(!$defined(iT)) {
        var iTT = $(this.stat[i]).getTag();
        if(iTT == 'select') iT = 'select';
        if(iTT == 'textarea') iT = 'textarea';
      }
      var item = $(this.stat[i]);
      switch(iT){
        case 'select':
        case 'file':
          item.setStyle('background','pink');
          item.addEvent('click',function(){
            this.setStyle('background','white');
            this.setStyle('color','black');
          });
          break;
        case 'password':
        case 'text':
        case 'textarea':
          item.setStyle('background','pink');
          item.addEvent('focus',function(){
            this.setStyle('background','#ffffcc');
            this.setStyle('color','#000');
          });
          break;
        case 'radio':
          item.getParent().getParent().setStyle('background','pink');
          item.getParent().getParent().setStyle('color','red');
          item.getParent().getParent().addEvent('mouseover',function(){
            this.setStyle('background','#ffffcc');
            this.setStyle('color','#000');
          });
          break;
        case 'checkbox':
        case 'radio':
        case 'hidden':// mostlikely an editor of some sort
          item.getParent().setStyle('background','pink');
          item.getParent().setStyle('color','red');
          item.getParent().addEvent('mouseover',function(){
            this.setStyle('background','#ffffcc');
            this.setStyle('color','#000');
          });
          break;
        default:
          // nothing yet
          break;
      }
    }
  },
  createErrorList: function() {
    var er = '<ul>';
    this.msgs.each(function(id){
      er += '<li>' + id + '</li>';
    })
    er += '</ul>';
    return er;
  },
  displayAlert: function() {
    if($chk($('alertB'))) {
      $('alertB').remove();
    }
    // hack for early ie
    var el = this.createErrorList();
    window.scroll(0,-1000);
    var t = 'Please fix the following errors';
    var alertBox = popupBox(t,el,'alert');
  },
  showSubmit: function(text){
    if($chk($(this.name).getElement('input[type=submit]'))) {
      $(this.name).getElement('input[type=submit]').disabled = false;
      $(this.name).getElement('input[type=submit]').setProperty('value',this.text);
    }
  },
  waitLoaded: function(text){
    this.text = text;
    window.addEvent('load',this.showSubmit.bind(this));
  },
  returnStatus: function(){
    if(this.stat.length > 0) {
      this.displayAlert();
      return false;
    }
    return true;
  },
  uc: function(obj,name,file){
    alert(name+' = '+file);
    obj.done();
    $(name).value += file;
    $(name+'_status').setHTML($(name).value);
  }
});
// Load the nicEdit JS Data
if(!$defined(window.CKEDITOR)) {
  new Asset.javascript('/editors/ck/ckeditor.js', {
    id: 'ckeditor'
  });
}
ImmForm.implement(new Events);
window.addEvent('domready',function(){
  if($chk($('contentArea'))){
    $('contentArea').getElements('input[type=file]').each(function(item){

      });
  }
  if($chk(document.getElement('textarea[rel=ckedit]'))){
    document.getElements('textarea[rel=ckedit]').each(function(i){
      CKEDITOR.replace(i.getProperty('id'),{
        contentsCss:['/ecss?t='+page_info.template,'/immcss/widgetEditor.css'],
        customConfig:'/editors/ck/widgets.js'
      });
    });
  }
  if($chk(document.getElement('div[class^=timePicker]'))){
    var lp = Asset.javascript('/scripts/timePic.js');
    lp.addEvent('load',function(){
      document.getElements('div[class^=timePicker]').each(function(item){
        var tpInp = item.getElement('input');
        new TimePicker(tpInp);
      });
    })
  }
});