/* Immprove 1.0 */
var prevCli;
var windowLoaded = false;
var bkup  = new Object();
var saBar = [];
window.addEvent('load',function(){
  windowLoaded = true;
});
window.addEvent('domready', function(){
  var Tips2 = new Tips($$('.tips'), {
    offsets:{
      x:-50,
      y:30
    },
    initialize:function(){
      this.fx = new Fx.Style(this.toolTip, 'opacity', {
        duration: 500, 
        wait: false
      }).set(0);
    },
    onShow: function(toolTip) {
      this.fx.start(1);
    },
    onHide: function(toolTip) {
      this.fx.start(0);
    },
    hideDelay: 400,
    fixed: false 
  });
  Cookie.set('jsChk', 'true');
});
if(!$chk(console)) {
  var console = {};
  console.dir = function(){};
  console.log = function(){};
}
function setAk(k){
  if(!k) return;
  Cookie.remove('akey');
  Cookie.set('akey',k,{
    path:"/"
  });
}
function toggleBox(ele,content) {
  if($(ele).style.display == "block"){
    $(ele).style.display= 'none';
  } else {
    $(ele).style.display='block';
  }
  if(content != '') $(ele).innerHTML= content;
}
function show(ele) {
  if($(ele) != null) {
    if($(ele).style.display == "block") {
      $(ele).style.display= 'none';
    }	else {
      $(ele).style.display='block';
    }
    return false;
  }
};
function IsNumeric(sText) {
  var ValidChars = "0123456789.$";
  var IsNumber=true;
  var Char;
  for (i = 0; i < sText.length && IsNumber == true; i++){
    Char = sText.charAt(i);
    if (ValidChars.indexOf(Char) == -1)	IsNumber = false;
  }
  return IsNumber;
};
function changeClass(elem, myClass) {
  $(elem).addClass(myClass);
};
function changeBackground(Elem, Back) {
  try {
    var type = $(Elem).getProperty('type');
  } catch(err) {
    return false;
  }
  if(type == 'radio') {
    if($(Elem + 'Label')) $(Elem + 'Label').setStyle('background',Back);
  } else {
    $(Elem).setStyle('background',Back);
  }

};
function toClipboard(t) {
  var p   = t.getParent().getElement('input');
  p.setStyle('background','red');
//var txt = p.getElement('input').createTextRange();
//txt.execCommand('Copy');
}
function watchChange(ele) {
  $(ele).addEvent('focus',function(){
    $(ele).setStyle('background','#FFF');
    $(ele).setStyle('color','#000');
  });
}
function toggleCb(ele) {
  $$(ele).each(function(item){
    item.checked = (item.checked) ? false:true;
  });
};
function toggleChecks(c){
  $$(c).each(function(item){
    item.checked = (item.checked) ? false:true;
  });
}
function validateCheckbox(ele) {
  var btn = $$('#' + ele);
  for(i=0;i<btn.length;i++){
    if(btn[i].checked) return true;
  }
  return false;
}
function uncheckAll(field) {
  for (i = 0; i < field.length; i++)	field[i].checked = false ;
};
function splitFrames() {
  document.write('<HTML><HEAD><TITLE>Immerse Support</TITLE></HEAD><FRAMESET COLS="*, 300"><FRAME SRC="');
  document.write(top.location.href);
  document.write('" NAME="leftcolumn"><FRAME SRC="http://support.immersegraphics.com" NAME="leftcolumn"></FRAMESET></HTML>');
  return false;
};
function confirmRedirect(t,l){
  if(confirm(t)) {
    window.location = l;
  }
}
function closeConfirm(al) {
  al.parentNode.removeChild(al);
};
function validateEmail(ele){
  var x = $(ele).value;
  if(x != '') {
    var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(x)) {
      return true;
    }	else {
      return false;
    }
  }
};
function clearTxt(ele) {
  $(ele).value = '';
}
function clearExpand(ele,sz) {
  clearTxt(ele);
  $(ele).setProperty('size',sz);
}
var expSaved ;
var tFx = {};
function expandTextarea(id) {
  if(!expSaved) {
    var ot = $(id).getCoordinates();
    expSaved = new Array(ot.width,ot.height);
    if(!$defined(tFx[id])) tFx[id] = new Fx.Styles($(id),{
      'duration':1000,
      transition: Fx.Transitions.Bounce.easeOut
      });
    tFx[id].start({
      'height':[expSaved[1],400]
      });
  } else {
    tFx[id].start({
      'height':expSaved[1]
      });
    expSaved = false;
  }
}
function strobeBg(id) {
  var myFx = new Fx.Style($(id), 'opacity');
  myFx.start(1,0).chain(function(){
    myFx.start(0,1);
  });
}
function strobeThenFade(id) {
  var myFx = new Fx.Style($(id), 'opacity',{
    'duration':1500
  });
  myFx.start(1,.5).chain(function(){
    myFx.start(.5,1)
    }).chain(function(){
    myFx.start(1,.2)
    }).chain(function(){
    myFx.start(.2,1)
    }).chain(function(){
    myFx.start(1,.2)
    }).chain(function(){
    myFx.start(.2,1)
    }).chain(function(){
    myFx.start(1,.0)
    }).chain(function(){
    $(id).setStyle('display','none')
    });
}
function clickObjElement(obj, ele) {
  if(prevCli) $(prevCli).setStyle('background', '#FFFFFF');
  $E('input',obj).checked = true;
  $(obj).setStyle('background', '#F3F3F3');
  prevCli = obj;
}
function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
function disableEnterKey(e) {
  var key;
  if(window.event)key = window.event.keyCode;     //IE
  else key = e.which;     //firefox
  if(key == 13) return false;
  else return true;
}
function popupNoteClose(msg) {
  popupNote(msg);
}
function popupNote(msg) {
  window.addEvent('domready',function(){
    window.scroll(0,-5000);
    var bg = new Element('div',{
      'id':'popupNote'
    }).setStyle('opacity','.5').injectBefore($('container'));
    var inf = new Element('div',{
      'id':'popupContainer'
    }).setHTML(unescape(msg)).injectBefore(bg);
    var close = new Element('div',{
      'id':'popupClose'
    }).setHTML('close').injectInside($('popupContainer'));
    close.onclick = closePopupNote;
    bg.onclick    = closePopupNote;
  });
}
function popupNoteLarge(msg) {
  var bg = new Element('div',{
    'id':'popupNote'
  });
  var inf = new Element('div',{
    'id':'popupWide'
  });
  inf.setHTML(msg);
  bg.injectBefore($('container'));
  inf.injectBefore(bg);
}
function fadeThenRemove(id){
  if($chk($(id))) {
    var f = new Fx.Style($(id), 'opacity',{
      'duration':1000
    }).start(0);
    f.addEvent('onComplete',function(){
      $(id).removeEvents().remove();
    });
  }
}
var statBox = function(txt, s) {
  var b = new Element('div',{
    'class':'sBox '+s
    }).setHTML('<p>'+txt+'</p>');
  return b;
}
function popupBox(title,text,type){
  var ph  = new Element('div').setStyles({
    'cursor':'pointer',
    'opacity':0
  }).injectInside(document.body);
  var bg  = new Element('div',{
    'class':'opaqueBackground'
  }).injectInside(ph).centerScreen();
  var box = new Element('div',{
    'class':'sBox ' + type
    }).setStyle('z-index',10000);

  new Element('h1').setHTML(title).injectInside(box);
  new Element('p').setHTML(text).injectInside(box);
  box.setStyles({
    'width':300
  });
  box.injectInside(ph).centerScreen();

  var f = new Fx.Style(ph, 'opacity',{
    'duration':500
  }).start(1);
  ph.addEvent('click',function(){
    fadeThenRemove(this);
  });
}
var closePopupNote = function(){
  fadeThenRemove('popupNote');
  fadeThenRemove('popupWide');
  fadeThenRemove('popupContainer');
}
function popupLoading(ele) {
  var bg = new Element('div',{
    'id':'popupLoading',
    'class':'opaqueBackground'
  });
  var inf = new Element('div',{
    'id':'popupBar'
  });
  inf.setHTML('Working.. Please Wait...<br><img src="/design/icons/ajax-loader.gif">');
  bg.injectBefore(ele);
  inf.injectBefore(bg);
}
function ajaxLoading(ele) {
  return loIcon(ele,'lg')
  }
function loIcon(ele, s) {
  if($type(ele) != 'elememt') ele = $(ele);
  ele.empty();
  var icon = '/design/icons/' + (s == 'sm' ? 'loadSm.gif':'ajax-loader.gif');
  var i = new Asset.image(icon, {
    id: 'loIcon', 
    onload: function(){
      this.injectInside(ele).centerElement();
    }
  });
  return i;
}
function popupLoadingFs() {
  var bg 	 = new Element('div',{
    'id':'popupLoading',
    'class':'opaqueBackground'
  });
  var lTxt = 'Loading Data.. Please Wait...<br><img src="/design/icons/ajax-loader.gif" />';
  var inf  = new Element('div',{
    'id':'popupBar'
  }).setHTML(lTxt);
  window.addEvent('domready',function(){
    bg.injectInside(document.body);
    inf.injectAfter(bg).centerScreen();
  });
  window.addEvent('load',function(){
    removeLoading.delay(3000);
  });
}
var popupAlert = function(txt) {
  if($chk($('alertB'))) {
    $('alertB').remove();
  }
  var alertBox = new Element('div',{
    id: 'alertB'
  })
  .addClass('alertBox').setHTML('<h1>Please fix the following errors</h1>');
  alertBox.setStyle('opacity','0');
  var sty = 'cursor:pointer;position:absolute;bottom:0px;right:0px;padding:4px;';
  alertBox.innerHTML += txt + '<div style="'+sty+'"><a href="#" onclick="return false"><strong>Close</strong></a></div>';
  window.scroll(0,-1000);
  alertBox.injectInside(document.body).centerScreen();
  var ef = new Fx.Style(alertBox, 'opacity', {
    duration:1000
  }).start(0,1);
  alertBox.addEvent('click',function() {
    alertBox.removeEvents();
    fadeThenRemove('alertB')
  });
}
var removeLoading = function() {
  window.removeEvent('load',removeLoading);
  fadeThenRemove('popupLoading');
  fadeThenRemove('popupBar');
}
function popupRedirect(text, loc){
  var bg = new Element('div',{
    'class':'opaqueBackground'
  }).injectInside(document.body);
  var box = new Element('div',{
    'class':'popupBox'
  }).setHTML(fullDecode(text));
  var red = new Element('input',{
    'type':'button',
    'value':'continue',
    'class':'popupButton'
  }).injectInside(box);
  red.addEvent('click',function(){
    window.location = loc
    });
  box.injectAfter(bg).centerScreen();

}
function btoa(input) {
  return Base64.encode(input);
}

var expand = function(ele) {
  if(!$chk($(ele))) return false;
  var icon = $(ele).getElement('img');
  var par = $(ele).getParent();
  if(par.getTag() != 'div') {
    var par = par.getParent();
  }
  var con = ['div','fieldset','tr']
  if(!con.contains(par.getTag())) {
    return false;
  }
  var h = par.getElement('.hidden');
  if(!h) alert('no hidden areas');
  if(h.getStyle('display') == 'none') {
    h.setStyles('display:block;overflow:hidden;height:0px;');
  }
  var hid = h.getFirst().getCoordinates();
  var ef = new Fx.Style(h,'height',{
    duration:500
  });
  if(h.getStyle('height').toInt() > 0) {
    icon.setProperty('src','/design/icons/expand.png');
    ef.start(0);
  } else {
    icon.setProperty('src','/design/icons/contract.png');
    ef.start(hid.height+20);
  }
}
function validateRadio(ele) {
  var btn = document.getElementsByName(ele);
  for(i=0;i<btn.length;i++){
    if(btn[i].checked) return true;
  }
  return false;
}
function dump(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;
  var level_padding = "";
  for(var j=0;j<level+1;j++) level_padding += "    ";
  if(typeof(arr) == 'object') { //Array/Hashes/Objects
    for(var item in arr) {
      var value = arr[item];
      if(typeof(value) == 'object') { //If it is an array,
        dumped_text += level_padding + "'" + item + "'=>\"\"\n";
        dumped_text += dump(value,level+1);
      } else {
        dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
      }
    }
  } else {
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
}
var Base64 = {
  _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;
    input = Base64._utf8_encode(input);
    while (i < input.length) {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }

      output = output +
      this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
      this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

    }

    return output;
  },
  decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

      enc1 = this._keyStr.indexOf(input.charAt(i++));
      enc2 = this._keyStr.indexOf(input.charAt(i++));
      enc3 = this._keyStr.indexOf(input.charAt(i++));
      enc4 = this._keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }

    }

    output = Base64._utf8_decode(output);

    return output;

  },
  _utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

      var c = string.charCodeAt(n);

      if (c < 128) {
        utftext += String.fromCharCode(c);
      }
      else if((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      }
      else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }

    return utftext;
  },
  _utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

      c = utftext.charCodeAt(i);

      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      }
      else if((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i+1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      }
      else {
        c2 = utftext.charCodeAt(i+1);
        c3 = utftext.charCodeAt(i+2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
    }
    return string;
  }
}
function fullEncode(s) {
  return encodeURIComponent(Base64.encode(s));
}
function fullDecode(s) {
  return decodeURIComponent(Base64.decode(s));
}
function insertAtCursor(myField, myValue) {
  if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }
  //MOZILLA/NETSCAPE support
  else if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)
    + myValue
    + myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += myValue;
  }
}
String.extend({
  fullEncode: function(){
    return encodeURIComponent(Base64.encode(this));
  }
})
function makehtml(s) {
  var ss = new String();
  for( i = 0; i < s.length; i++) {
    var fs = s.charCodeAt(i);
    ss += '&#' + fs + ';';
  }
  return ss;
}

var playerControls = function(pre) {
  var mp 	= pre.getParent();
  mp.setStyle('position','relative');
  var tp 	= new Element('div',{
    'class':'playerControls'
  }).addEvent('click',stopProp).injectInside(mp);
  var pl  = new Element('img',{
    'src':'/img/icons/play.png'
  }).addEvent('mousedown',playMovie.bind(pre)).injectInside(tp);
  var li  = new Element('img',{
    'src':'/img/icons/stop_play.png'
  }).addEvent('mousedown',stopMovie.bind(pre)).injectInside(tp);
}
var stopProp = function(eve){
  new Event(eve).stop();
}
var playMovie = function(){
  this.Play();
}
var stopMovie = function(){
  this.StopPlay();
}


if(window.ie6) {
  new Asset.javascript('/scripts/fixPng.js', {
    id: 'pngFIX'
  });
}

Element.extend({
  centerScreen: function(){
    var ele = this.getCoordinates();
    var y = window.getScrollTop() + ((window.getHeight()/2)-(ele.height/2));
    var x = ((window.getWidth()/2) - (ele.width/2));
    var styles = {};
    styles.position = (this.getStyle('position') != 'fixed' ? 'absolute':'fixed');
    styles.top  		= y+'px';
    styles.left 		= x+'px';
    this.setStyles(styles);
  },
  centerElement: function(){
    var par = this.getParent();
    var ps 	= par.getStyle('position');
    if(ps != 'absolute' && ps != 'relative') {
      this.getParent().setStyle('position','relative');
    }
    var c = this.getCoordinates();
    var sty = {
      'top':'50%',
      'left':'50%',
      'position':'absolute',
      'margin-top':'-'+(c.height.toInt() / 2)+'px',
      'margin-left':'-'+(c.width.toInt() / 2)+'px'
    };
    this.setStyles(sty);
  },
  toJsonStringEncoded:function(){
    var queryString = [];
    this.getFormElements().each(function(el){
      var name  = el.name;
      var v = el.getValue();
      if(typeof v == 'string'){
        var value = fullEncode(v);
      } else {
        var value = v;
      }
      if (value === false || !name || el.disabled) return;
      var qs = function(val){
        queryString.push('"' + name.replace(/(["\\])/g, '\\$1') + '":"' + val.replace(/(["\\])/g, '\\$1') + '"');
      };
      if ($type(value) == 'array') value.each(qs);
      else qs(value);
    });
    return '{' + queryString.join(',') + '}';
  },
  toJsonString:function(){
    var queryString = [];
    this.getFormElements().each(function(el){
      var name = el.name;
      var value = el.getValue();
      if (value === false || !name || el.disabled) return;
      value.urlEncode();
      var qs = function(val){
        queryString.push('"' + name.replace(/(["\\])/g, '\\$1') + '":"' + val.replace(/(["\\])/g, '\\$1') + '"');
      };
      if ($type(value) == 'array') value.each(qs);
      else qs(value);
    });
    return '{' + queryString.join(',') + '}';
  },
  formToJson:function(){
    return Json.evaluate(this.toJsonString());
  },
  formToJsonEncoded:function(){
    var e = this.toJsonStringEncoded();
    return Json.evaluate(e);
  }
});
var TimePicker = new Class({
  initialize: function(field){
    this.field = $(field);
    this.field.setStyle('display','none');
    this.showPicker();
  },
  showPicker: function(){
    var ps = {
      'border':'1px solid #000',
      'padding':'0px',
      'position':'absolute',
      'width':'160px'
    };
    this.picker = new Element('div').setStyles(ps);
    var ts = 'padding:4px;border:0px solid #FFF !important;width:20px;float:left;';

    this.hours = new Element('input',{
      'class':'hours',
      'type':'text',
      'value':'00',
      'size':2,
      'maxlength':2
    }).setStyles(ts).injectInside(this.picker);
    this.hours.addEvent('keydown',this.numOnly.bind(this));
    this.hours.addEvent('mousedown',this.editItem.bind(this));

    this.tSelector(this.hours).injectBefore(this.hours);

    this.dots = new Element('div').setStyles('float:left;padding:13px 2px;font-size:20px;line-height:0px;font-weight:bolder;').setHTML(':').injectInside(this.picker);

    this.minutes = new Element('input',{
      'class':'minutes',
      'type':'text',
      'value':'00',
      'size':2,
      'maxlength':2
    }).setStyles(ts).injectInside(this.picker);
    this.tSelector(this.minutes).injectBefore(this.minutes);

    this.ampm = new Element('input',{
      'class':'ampm',
      'type':'text',
      'value':'am',
      'size':2,
      'maxlength':2
    }).setStyles(ts).injectInside(this.picker);
    this.tSelector(this.ampm).injectBefore(this.ampm);

    this.picker.injectAfter(this.field);
  },
  editItem: function(eve){
    var e = new Event(eve);
    e.target.value = '';
    e.target.focus();
  },
  chkVal: function(eve){
    var e = new Event(eve);
    var val = new Number(e.target.value);
    if(e.target.hasClass('hours')) {
      alert(val);
      if(val > 12) {
        alert(val);
        e.stop();
        return false;
      }
    }
  },
  numOnly: function(eve){
    var e = new Event(eve);
    if(!IsNumeric(e.key)) {
      e.stop();
      return false;
    }

  },
  tSelector: function(target){
    var style = 'float:left;margin:0px 3px;padding-top:7px;';
    var ts = new Element('div').setStyles(style);
    var as = 'margin:0px;padding:0px;line-height:0px;height:10px;';
    var up = new Element('div').setStyles(as).setHTML('<img src="/img/time/selUp.png" width="10">').injectInside(ts);
    var down = new Element('div').setStyles(as).setHTML('<img src="/img/time/selDown.png"  width="10">').injectInside(ts);
    up.addEvent('click',function(){
      if(target.hasClass('hours')) this.changeHour('up');
      if(target.hasClass('minutes')) this.changeMinute('up');
    //if(target.hasClass('ampm')) this.changeAmpm('up');
    }.bind(this));
    down.addEvent('click',function(){
      if(target.hasClass('hours')) this.changeHour('up');
      if(target.hasClass('minutes')) this.changeMinute('up');
    //if(target.hasClass('ampm')) this.changeAmpm('up');
    }.bind(this));
    return ts;

  },
  changeHour: function(d){
    var hour = new Number(this.hours.value);
    var ne;
    if(d=='up') {
      ne = ((hour==12) ? 1 : (hour+1));
    } else {
      ne = ((hour==1) ? 12 : (hour-1));
    }
    this.hours.value = ne;
  },
  changeMinute: function(d){
    var minute = new Number(this.minutes.value);
    var ne;
    if(d=='up') {
      ne = ((minute==59) ? 1 : (minute+1));
    } else {
      ne = ((minute==1) ? 59 : (minute-1));
    }
    if(ne<10) ne = '0'+ne;
    this.minutes.value = ne;
  }

});

/*
MooCal v0.2 - A simple and easy to use calendar control built upon mooTools
by Chris Martin (http://www.redantdesign.com/) - MIT-style license.

The draw function is modified from a date picker control written by David Kelly
* Copyright 2007 David Kelly for CJD Systems Limited
* version 0.1 - 21st May 2007
* url - http://ng100.cjdsystems.co.uk/moo/dates/DateTimePicker.htm

*/

var MooCal = new Class({
  initialize: function(){
    this.setOptions({
      base: 1,
      x:0,
      y:0,
      calendarClass: "calendar",
      todayClass: "today",
      selectedClass: "selected",
      dayNames: ["Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sun"],
      monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    });
    this.sqlCompatable = true;
    this.calendarID = null;
    this.visible = false;
    this.displayTimer = 0;
    this.minYear = '2000';
    this.maxYear = '2020';
  },
  showCal: function(ele,value) {
    this.elementID   = ele;
    this.chosenDate = new Date();
    if(value=='' || value == "0000-00-00") {
      var d = new Date();
      value = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();
    }
    if(value.test(' ')) {
      var dat = value.split(' ');
      var parts = dat[0].split('-');
      this.times = dat[1].split(':');
    } else {
      var parts = value.split('-');
    }

    this.chosenDate.setYear(parts[0]);
    var month = new Number(parts[1]);
    this.chosenDate.setMonth(month-1);
    this.chosenDate.setDate(parts[2]);
    this.currentDate = this.chosenDate;
    this.monthAndYear = null;
    var c = $(ele).getCoordinates();
    this.show(c.left,c.top);
  },
  setTimeSelect:function(){
    this.displayTime = true;
  },
  show: function(x, y) {
    if(!this.visible){
      this.calendarID = "calendar_" + Date.parse(new Date());
      this.draw($pick(x, this.options.x), $pick(y, this.options.y));
    }
    this.visible = true;
  },
  hide: function() {
    if(this.visible){
      $(this.calendarID).remove();
      this.visible = false;
      clearTimeout(this.displayTimer);
    }
  },
  setValue: function(d){
    this.currentDate.setDate(d);
    this.chosenDate = this.currentDate;
    var day = this.currentDate.getDate().toString();
    if(day.length == 1) day = '0' + day;
    var month = this.currentDate.getMonth()+1;
    month = month.toString();
    if(month.length == 1) month = '0' + month;


    if(!this.displayTime) {
      $(this.elementID).setProperty("value", this.currentDate.getFullYear() + '-' + month + '-' + day);
      this.hide();
    } else {
      var hrs = this.hoursSelect.value;
      if(this.ampmSelect.value == 'pm' && hrs!=12) {
        var it = new Number(this.hoursSelect.value);
        var hrs =  it+12;
      }
      if(hrs == 12 &&this.ampmSelect.value == 'am') hrs = '00';
      var time = hrs+':'+this.minutesSelect.value+':00';
      $(this.elementID).setProperty("value", this.currentDate.getFullYear() + '-' + month + '-' + day + ' ' + time);
      this.redraw();
    }
  },
  selectDate: function(e,d) {
    new Event(e).stop();
    if($type(d) != "number")return;
    this.setValue(d);
  },
  dispTime: function(){
    var dDate = this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getDate() + " " +  this.currentDate.getFullYear();
    var time = this.hoursSelect.value+':'+this.minutesSelect.value+' '+this.ampmSelect.value;
    this.ct.setHTML(dDate+' '+time);
    this.setValue(this.currentDate.getDate());
  },
  setDates: function(){
    this.lastMonth = new Date(this.currentDate).setMonth(this.currentDate.getMonth() - 1);
    this.nextMonth = new Date(this.currentDate).setMonth(this.currentDate.getMonth() + 1);
    this.lastYear = new Date(this.currentDate).setFullYear(this.currentDate.getFullYear() - 1);
    this.nextYear = new Date(this.currentDate).setFullYear(this.currentDate.getFullYear() + 1);
    this.today = new Date();
  },

  repaint: function(e,d) {
    new Event(e).stop();
    var dateToCheck = new Date(d);
    if(dateToCheck.getFullYear() < this.minYear || dateToCheck.getFullYear() > this.maxYear){
      return;
    }
    this.currentDate = dateToCheck;
    this.setDates();
    this.redraw();
  },

  mouseOver: function() {
    clearTimeout(this.displayTimer);
  },

  mouseOut: function() {
    this.displayTimer = this.hide.delay(500, this);
  },

  draw: function(x, y) {
    var tableContainer, table, thead, tbody, row, td;
    tableContainer = new Element("div",{
      "class": this.options.calendarClass,
      "id": this.calendarID,
      "events": {
        "mouseover": this.mouseOver.bind(this),
        "mouseout": this.mouseOut.bind(this)
        }
      }).setStyles({
    "position":"absolute",
    "left": x,
    "top": y
  });
  table = new Element("table", {
    "id": this.calendarID + "-table",
    "class": this.calendarID + "-table"
    });
  thead = new Element("thead").injectInside(table);

  row = new Element("tr").injectInside(thead);
  new Element("a", {
    "href":"#",
    "events":{
      "click": (function(e){
        this.repaint(e, this.lastYear);
      }).bindWithEvent(this)
      }
    }).setHTML("&laquo;").injectInside(new Element("th", {
  "class": this.options.calendarClass + "-yearswitch"
  }).injectInside(row));
  new Element("a", {
    "href":"#",
    "events":{
      "click": (function(e){
        this.repaint(e, this.lastMonth);
      }).bindWithEvent(this)
      }
    }).setHTML("&#139;").injectInside(new Element("th", {
  "class": this.options.calendarClass + "-monthswitch"
  }).injectInside(row));

this.monthAndYear = new Element("th", {
  "colSpan": 3,
  "class" : this.options.calendarClass + "-monthandyear"
  }).appendText(this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getFullYear()).injectInside(row);
new Element("a", {
  "href":"#",
  "events":{
    "click": (function(e){
      this.repaint(e, this.nextMonth);
    }).bindWithEvent(this)
    }
  }).setHTML("&#155;").injectInside(new Element("th", {
  "class": this.options.calendarClass + "-monthswitch"
  }).injectInside(row));
new Element("a", {
  "href":"#",
  "events":{
    "click": (function(e){
      this.repaint(e, this.nextYear);
    }).bindWithEvent(this)
    }
  }).setHTML("&raquo;").injectInside(new Element("th", {
  "class": this.options.calendarClass + "-yearswitch"
  }).injectInside(row));

row = new Element("tr").injectInside(thead);
for (i = 0; i < 7; i++)	{
  new Element("th").appendText(this.options.dayNames[i]).injectInside(row);
}

tbody = new Element("tbody").injectInside(table);
for(r=0;r<6;r++){
  row = new Element("tr").injectInside(tbody);
  for(c=0;c<7;c++){
    td = new Element("td",{
      'class':'cday'
    }).injectInside(row);
    new Element("a",{
      "href": "#"
    }).setHTML("&nbsp;").injectInside(td);
  }
}
table.injectInside(tableContainer);
if(this.displayTime) {
  row = new Element('tr',{
    'class':'cDT'
  }).injectInside(table);
  td = new Element("td").setProperty('colspan',7).injectInside(row);
  var dDate = this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getDate() + " " +  this.currentDate.getFullYear() + ' 12:00 AM';
  this.ct = new Element('div',{
    'id':'ct'
  }).setHTML(dDate).injectInside(td);
  row = new Element('tr',{
    'class':'timePicker'
  }).injectInside(table);
  td = new Element("td").setProperty('colspan',7).injectInside(row);
  //setStyles('margin:0px;padding:5px;').setHTML('Time: ');
  this.hoursSelect = new Element('select',{
    'name':'chours',
    'id':'chours'
  }).addEvent('change',this.dispTime.bind(this)).injectInside(td);
  var ampm;
  if(this.times) {
    if(this.times[0] == '00') {
      this.times[0] = 12;
      ampm = 'am';
    }
    if(this.times[0] > 12) {
      var ti = new Number(this.times[0]);
      this.times[0] =  ti-12;
      ampm = 'pm';
    } else if(this.times[0] == 12 && ampm!='am') {
  var ampm = 'pm';
  }
  }
  for(i=1;i<=12;i++){
    var hr = new Element('option',{
      'value':i
    }).setHTML(i).injectInside(this.hoursSelect);
    if(this.times) {
      if(this.times[0] == i) hr.selected = true;
    }
  }
  this.minutesSelect = new Element('select',{
    'name':'cminutes',
    'id':'cminutes'
  }).addEvent('change',this.dispTime.bind(this)).injectInside(td);
  for(h=0;h<=59;h++){
    minute = new String(h);
    if(minute.length < 2) {
      mi = "0"+minute;
    } else mi = minute;
    var min = new Element('option',{
      'value':mi
    }).setHTML(mi).injectInside(this.minutesSelect);
    if(this.times) {
      if(this.times[1] == mi) min.selected = true;
    }
  }
  this.ampmSelect = new Element('select',{
    'name':'campm',
    'id':'campm'
  }).addEvent('change',this.dispTime.bind(this)).injectInside(td);
  var am = new Element('option',{
    'value':'am'
  }).setHTML('AM').injectInside(this.ampmSelect);
  var pm = new Element('option',{
    'value':'pm'
  }).setHTML('PM').injectInside(this.ampmSelect);
  if(ampm=='pm') pm.selected = true;
  if(ampm=='am') am.selected = true;
//holder.injectAfter(table);
}
tableContainer.injectInside(document.body);
this.redraw();
},
redraw: function() {
  this.setDates();
  this.monthAndYear.setText(this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getFullYear());
  var firstDay = new Date(this.currentDate);
  firstDay.setDate(1);

  if (firstDay.getDay() > 0) {
    firstDay.setDate(-firstDay.getDay() + 1);
  }

  var currentDay = new Date(firstDay);
  var today = new Date();
  $ES("tbody a", $(this.calendarID)).each(function(item,i){
    var txt = "&nbsp;";
    if (currentDay.getMonth() == this.currentDate.getMonth()) {
      txt = currentDay.getDate();
    }
    item.removeClass(this.options.todayClass);
    item.getParent().removeClass(this.options.selectedClass);

    item.removeEvents();
    item.addEvent("click", (function(e, day){
      this.selectDate(e, day);
    }).bindWithEvent(this, txt));
    item.setHTML(txt);
    if (currentDay.getDate() == today.getDate() && currentDay.getMonth() == today.getMonth() && currentDay.getFullYear() == today.getFullYear()) {
      item.addClass(this.options.todayClass);
    }
    if (currentDay.getMonth() == this.chosenDate.getMonth() &&
      currentDay.getDate() == this.chosenDate.getDate() &&
      currentDay.getMonth() == this.chosenDate.getMonth() &&
      currentDay.getFullYear() == this.chosenDate.getFullYear()) {
      item.getParent().addClass(this.options.selectedClass);
    }
    currentDay.setDate(currentDay.getDate() + 1);
  }.bind(this));
}
});

MooCal.implement(new Options);
window.addEvent('domready',function(){
  $ES('.dpick',document.body).each(function(item){
    item.addEvent('click',dSelect);
  });
  $ES('.dtpick',document.body).each(function(item){
    item.addEvent('click',dtSelect);
  });
});
var dSelect = function(eve){
  var e = new Event(eve).stop();
  var item = $(e.target);
  var date = item.value;
  var DTCalendar = new MooCal();
  DTCalendar.showCal(item,date);
};
var dtSelect = function(eve){
  var e = new Event(eve).stop();
  var item = $(e.target);
  var date = item.value;
  var DTCalendar = new MooCal();
  DTCalendar.setTimeSelect();
  DTCalendar.showCal(item,date);
};

