_UND = typeof _UND != "undefined"?_UND:"undefined";

// Converts a date into '12-Oct-1984' format
function getDateString(dt) {
  return dt.getDate() + '-' + 
    ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][dt.getMonth()] + 
    '-' + dt.getFullYear();
}

// Converts a date into 'July 2010' format
function getMonthYearString(dt) {
  return ['January','February','March','April','May','June','July',
          'August','September','October','November','December'][dt.getMonth()] +
         ' ' + dt.getFullYear();
}

// This is the function called when the user clicks any button
function chooseDate(e) {
  var targ; // Crossbrowser way to find the target (http://www.quirksmode.org/js/events_properties.html)
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
  tod =targ.Data('today');
  tod = tod==null?"":tod;
  var div = targ.parentNode.parentNode.parentNode.parentNode.parentNode; // Find the div
  
  var idOfTextbox = div.getAttribute('datepickertextbox'); // Get the textbox id which was saved in the div
  
  var textbox = getTextBox(document.getElementById(idOfTextbox)); // Find the textbox now
 // alert(textbox.outerHTML);
  if (targ.classList.contains('cntr')) { // Do they want the change the month?
    // || targ.classList.contains('nxt')  || targ.classList.contains('pprev')  || targ.classList.contains('nnxt') 
   // alert(new Date(targ.getAttribute('date')));
    createCalendar(div, new Date(targ.getAttribute('date')),tod);
    return;
  }
  if(typeof textbox.value != "undefined"){
    textbox.value = targ.getAttribute('date'); // Set the selected date
  }else{
    textbox.textContent = targ.getAttribute('date'); // Set the selected date
  }
  
  if(textbox.Data("action")){
    eval(textbox.Data("action"));
  }
  //div.remove();
  closeonly = true;
  div.parentNode.removeChild(div); // Remove the dropdown box now
}

// Parse a date in d-MMM-yyyy format
function parseMyDate(d) {
  
  if (typeof d=="undefined" || d=="") return new Date('NotADate'); // For Safari
  var a = d.split('-');
  if (a.length!=3) return new Date(d); // Missing 2 dashes
  var m = -1; // Now find the month
  if (a[1]=='Jan') m=0;
  if (a[1]=='Feb') m=1;
  if (a[1]=='Mar') m=2;
  if (a[1]=='Apr') m=3;
  if (a[1]=='May') m=4;
  if (a[1]=='Jun') m=5;
  if (a[1]=='Jul') m=6;
  if (a[1]=='Aug') m=7;
  if (a[1]=='Sep') m=8;
  if (a[1]=='Oct') m=9;
  if (a[1]=='Nov') m=10;
  if (a[1]=='Dec') m=11;
  if (m<0) return new Date(d); // Couldn't find the month
  return new Date(a[2],m,a[0],0,0,0,0);
}

// This creates the calendar for a given month
function createCalendar(div, month, tod) {
 //alert(tod);
  var idOfTextbox = div.getAttribute('datepickertextbox'); // Get the textbox id which was saved in the div
  var toggleobj = document.getElementById(idOfTextbox); // Find the textbox now
  var textbox = getTextBox(toggleobj);
  var tbl = document.createElement('table');
  var topRow = tbl.insertRow(-1);
  var td = topRow.insertCell(-1);
 // var lastYearBn = document.createElement('input');
  var lastYearBn = document.createElement('button');
  lastYearBn.type='button'; // Have to immediately set the type due to IE
  lastYearBn.className = "btn btn-default cntr";
  td.appendChild(lastYearBn);
  //lastYearBn.value='›';
 lastYearBn.innerHTML = Icon('angle-double-left');
 lastYearBn.setAttribute('data-today',tod);
  lastYearBn.onclick=chooseDate;
  lastYearBn.setAttribute('date',new Date(month.getFullYear(),month.getMonth()-12,1,0,0,0,0).toString());
  var td = topRow.insertCell(-1);
  var lastMonthBn = document.createElement('button');
  lastMonthBn.type='button'; // Have to immediately set the type due to IE
  td.appendChild(lastMonthBn);
  lastMonthBn.className = "btn btn-default cntr";
  lastMonthBn.setAttribute('data-today',tod);
  lastMonthBn.innerHTML= Icon('angle-left');
  lastMonthBn.onclick=chooseDate;
  lastMonthBn.setAttribute('date',new Date(month.getFullYear(),month.getMonth()-1,1,0,0,0,0).toString());
  var td = topRow.insertCell(-1);
  td.colSpan=3;
  var mon = document.createElement('input');
  mon.type='text';
  td.appendChild(mon);
  //alert(getMonthYearString(month));
  mon.value = getMonthYearString(month);
  mon.size=15;
  mon.disabled='disabled';
  mon.className='monthDsp';
  var td = topRow.insertCell(-1);
  var nextMonthBn = document.createElement('button');
  nextMonthBn.type='button';
  nextMonthBn.className = "btn btn-default cntr";
  nextMonthBn.setAttribute('data-today',tod);
  td.appendChild(nextMonthBn);
  //nextMonthBn.value = '>';
  nextMonthBn.innerHTML= Icon('angle-right');
  nextMonthBn.onclick=chooseDate;
  nextMonthBn.setAttribute('date',new Date(month.getFullYear(),month.getMonth()+1,1,0,0,0,0).toString());
  var td = topRow.insertCell(-1);
  var nextYearBn = document.createElement('button');
  nextYearBn.type='button'; // Have to immediately set the type due to IE
   nextYearBn.className = "btn btn-default cntr";
   nextYearBn.setAttribute('data-today',tod);
  td.appendChild(nextYearBn);
  //nextYearBn.value='>>';
   nextYearBn.innerHTML= Icon('angle-double-right');
  nextYearBn.onclick=chooseDate;
  nextYearBn.setAttribute('date',new Date(month.getFullYear(),month.getMonth()+12,1,0,0,0,0).toString());  
  var daysRow = tbl.insertRow(-1);
  daysRow.insertCell(-1).innerHTML="Mo";  
  daysRow.insertCell(-1).innerHTML="Tu";
  daysRow.insertCell(-1).innerHTML="We";
  daysRow.insertCell(-1).innerHTML="Th";
  daysRow.insertCell(-1).innerHTML="Fr";
  daysRow.insertCell(-1).innerHTML="Sa";
  daysRow.insertCell(-1).innerHTML="Su";
  daysRow.className='daysRow';  
  // Make the calendar
  var selected = parseMyDate(textbox.value); // Try parsing the date
  var today = new Date();
  date = new Date(month.getFullYear(),month.getMonth(),1,0,0,0,0); // Starting at the 1st of the month
  var extras = (date.getDay() + 6) % 7; // How many days of the last month do we need to include?
  
  date.setDate(date.getDate()-extras); // Skip back to the previous monday
  while (1) { // Loop for each week
    
    var tr = tbl.insertRow(-1);
    
    for (i=0;i<7;i++) { // Loop each day of this week
      var tdayseen = false;
      var td = tr.insertCell(-1);
      var inp = document.createElement('input');
      inp.type = 'button';
      td.appendChild(inp);
      inp.value = date.getDate();
     
      inp.setAttribute('date',getDateString(date));
      
      if (date.getDate()==today.getDate() && date.getMonth()==today.getMonth() && date.getFullYear()==today.getFullYear()) {
        if (inp.className) inp.className += ' ';
        inp.className+='today';
        //tdayseen = true;
      }
       var nmonth = Number(date.getMonth()),nday = Number(date.getDate()), nyear = Number(date.getFullYear()), tmonth = Number(today.getMonth()), tday = Number(today.getDate()), tyear = Number(today.getFullYear());
       //alert(nday+"-"+nmonth+"-"+nyear+"    "+tday+"-"+tmonth+"-"+tyear+"    "+tod);
       if(tod != ""){
      if((tod == "<" && (nyear > tyear || (nyear == tyear && nmonth > tmonth) || (nyear == tyear && nmonth == tmonth && nday >= tday))) || (tod == ">" && (nyear < tyear || (nyear == tyear && nmonth < tmonth) || (nyear == tyear && nmonth == tmonth && nday <= tday)))){
        tdayseen = true;
        //alert('enabled');
      }
    }else{
      tdayseen = true;
      //alert('All Enabeled');
    }
      if (date.getMonth() != month.getMonth() || tdayseen == false) {
        if (inp.className) inp.className += ' ';
        inp.className+='othermonth';
      }
      if(tdayseen){
        //alert('Function Set');
      inp.onclick = chooseDate;
      }
      if (!isNaN(selected) && date.getDate()==selected.getDate() && date.getMonth()==selected.getMonth() && date.getFullYear()==selected.getFullYear()) {
        if (inp.className) inp.className += ' ';
        inp.className+='btn btn-primary';
      }
      date.setDate(date.getDate()+1); // Increment a day
    }
    // We are done if we've moved on to the next month
    if (date.getMonth() != month.getMonth()) {
      break;
    }
  }
  
  // At the end, we do a quick insert of the newly made table, hopefully to remove any chance of screen flicker
 
  if (div.hasChildNodes()) { // For flicking between months
    // alert(tbl.outerHTML)
    div.replaceChild(tbl, div.childNodes[0]);
  } else { // For creating the calendar when they first click the icon
    div.appendChild(tbl);
  }
}

//function to get the input element incase id is not an input and input exist inside
function getTextBox(toggleobj){
   var textbox = toggleobj;
  if(textbox.tagName.toUpperCase() != "INPUT"){
    var childr = textbox.children;
    if(childr.length > 0){
      for(var aa=0,lenaa=childr.length;aa<lenaa;aa++){
        var childd = childr[aa];
        if(childd.tagName.toUpperCase() == "INPUT"){
          textbox = childd;
          break;
        }
      }
    }
  }
  return textbox;
}
var closeonly = false;
function removeCalender(){
  var dtpicker = _('datepickerdropdown');
  if(dtpicker != null){ //if exist
     if(IsArray(dtpicker)){
       dtpicker.Walk(function(k,v){
         v.remove();
       })
     }else{
       dtpicker.remove();
     }
     
  }
}
// This is called when they click the icon next to the date inputbox
function showDatePicker(idOfTextbox,clickobj) {
  //alert(idOfTextbox);
 style = clickobj.Data('style')
  var toggleobj = document.getElementById(idOfTextbox);
  var textbox = getTextBox(toggleobj);
  // See if the date picker is already there, if so, remove it
  removeCalender();

  /*x = textbox.parentNode.getElementsByTagName('div');
  for (i=0;i<x.length;i++) {
    if (x[i].getAttribute('class')=='datepickerdropdown') {
      textbox.parentNode.removeChild(x[i]);
      return false;
    }
  }*/

 // var internalStyle =  toggleobj.Data('css');
  

  // Grab the date, or use the current date if not valid
  var dval = typeof textbox.value != _UND?textbox.value:textbox.textContent;
  //alert(dval);
  var date = parseMyDate(dval);
  if (isNaN(date)) date = new Date();

  // Create the box
  var div = document.createElement('div');
  div.className='datepickerdropdown';
  div.SetStyle(style);
  div.setAttribute('datepickertextbox', idOfTextbox); // Remember the textbox id in the div
  var td = clickobj.Data("today");
  td = (td == null)?"":td;
  createCalendar(div, date, td); // Create the calendar
  insertAfter(div, toggleobj); // Add the box to screen just after the textbox
  return div;
}

// Adds an item after an existing one
function insertAfter(newItem, existingItem) {
  if(existingItem.children.length > 0){
    existingItem.appendChild(newItem);
    return;
  }
  if (existingItem.nextSibling) { // Find the next sibling, and add newItem before it
    existingItem.parentNode.insertBefore(newItem, existingItem.nextSibling); 
  } else { // In case the existingItem has no sibling after itself, append it
    existingItem.parentNode.appendChild(newItem);
  }
}



onDOMReady(function(){
    document.body.addEventListener("click",function(ev){
      //alert(elem);
     // alert(ev.target.outerHTML);
     /* if(ev.target.classList.contains("DatePicker")){
       //alert('aaa');
       return showDatePicker(ev.target.Data('input'),ev.target);
     }else{
      if(!ev.target.classList.contains("cntr")){
        removeCalender();        
      }
     } */
//alert(ev.target.className);
     if(ev.target.classList.contains("Calendar")){
       //get atributes
       var elem = ev.target;
        var param = {};
        var target = elem.Data("target");
        //Math.floor(Math.random() * len);
        if(target != null){
            param.Target = target
        }else{
            //var curdt = new Date();
            //elem.id = "calen_"+curdt.getTime + Math.floor(Math.random() * 1000);
            param.Target =  elem;
        }
         
          var dis = elem.Data("container");
          param.Display = dis != null?dis:'';

          var rng = elem.Data("range");
          param.Range = rng != null?(rng.toLowerCase() == "true"?true:false):false;
          var bcl = elem.Data("body-class");
          param.BodyClass = bcl != null?bcl:'calender-displaycont';

          var bsty = elem.Data("body-style");
          //alert(elem.outerHTML);
          param.BodyStyle = bsty != null?bsty:'';

          var tbcl = elem.Data("table-class");
          param.TableClass = tbcl != null?tbcl:"tables";

          var incl = elem.Data("in-class");
          param.InTransition = incl != null?incl:"inanim";

          var outcl = elem.Data("out-class");
          param.OutTransition = outcl != null?outcl:"outanim";

          var tdcl = elem.Data("today-class");
          param.TodayClass = tdcl != null?tdcl:"today";

          var selcl = elem.Data("selected-class");
          param.SelectedClass = selcl != null?selcl:"selected";
          var cap = elem.Data("caption");
          param.Caption = cap != null?cap:'';

          var to = elem.Data("to")
          param.SelectTo = to != null?to:'';

      // console.log(JSON.stringify(param));
          var calend = new Calendar(param);
          calend.Create();

  
     }

    });
    
}) 

// This is called when the page loads, it searches for inputs where the class is 'datepicker'

/* DOM.Ready(function(){
    document.body.Assign("click",function(ev,elem){
      //alert(elem);
     // alert(ev.target.outerHTML);
     if(ev.target.classList.contains("DatePicker")){
       //alert('aaa');
       return showDatePicker(ev.target.Data('input'),ev.target);
     }else{
      if(!ev.target.classList.contains("cntr")){
        removeCalender();        
      }
     }
//alert(ev.target.className);
     if(ev.target.classList.contains("Calendar")){
       //get atributes
       var elem = ev.target;
        var param = {};
        var target = elem.Data("target");
          param.Target = target != null?target:elem.id;
         
          var dis = elem.Data("container");
          param.Display = dis != null?dis:'';

          var rng = elem.Data("range");
          param.Range = rng != null?(rng.toLowerCase() == "true"?true:false):false;
          var bcl = elem.Data("body-class");
          param.BodyClass = bcl != null?bcl:'calender-displaycont';

          var bsty = elem.Data("body-style");
          param.BodyStyle = bsty != null?bsty:'';
          var tbcl = elem.Data("table-class");
          param.TableClass = tbcl != null?tbcl:"tables";

          var incl = elem.Data("in-class");
          param.InTransition = incl != null?incl:"inanim";

          var outcl = elem.Data("out-class");
          param.OutTransition = outcl != null?outcl:"outanim";

          var tdcl = elem.Data("today-class");
          param.TodayClass = tdcl != null?tdcl:"today";

          var selcl = elem.Data("selected-class");
          param.SelectedClass = selcl != null?selcl:"selected";
          var cap = elem.Data("caption");
          param.Caption = cap != null?cap:'';

          var to = elem.Data("to")
          param.SelectTo = to != null?to:'';

      // console.log(JSON.stringify(param));
          var calend = new Calendar(param);
          calend.Create();

  
     }

    });
    
});
 */

//New Calendar from AIM
var Calendar = function(param){
  this.TargetID = param.Target;
  this.Display = typeof param.Display != "undefined" ? param.Display : '';
  
  this.Target = typeof param.Target == "string" ? document.getElementById(param.Target) : param.Target;
  //this.Target = typeof this.Target == "object" ? document.getElementById(param.Target) : param.Target;
  if(this.Target != null){
      if(typeof this.Target.value == _UND){
        Object.defineProperty(this.Target,"value",{
            set:function(val){this.textContent = val},
            get:function(){return this.textContent}
        });
      }
  }
  //alert(this.Target)
  this.Range = typeof param.Range != "undefined" ? param.Range : false;
  this.RangeStart = null;
  this.BodyClass = typeof param.BodyClass != "undefined" ? param.BodyClass : "calender-displaycont";
  this.BodyStyle = typeof param.BodyClass != "undefined" ? param.BodyStyle : "";
  this.TableClass = typeof param.TableClass != "undefined" ? param.TableClass : "tables";
  this.InTransition = typeof param.InTransition != "undefined" ? param.InTransition : "inanim";
  this.OutTransition = typeof param.OutTransition != "undefined" ? param.OutTransition : "outanim";
  this.TodayClass = typeof param.TodayClass != "undefined" ? param.TodayClass : "today";
  this.SelectedClass = typeof param.SelectedClass != "undefined" ? param.SelectedClass : "selected";
  this.Caption = typeof param.Caption != "undefined" ? param.Caption : "";
  this.SelectTo = typeof param.SelectTo != "undefined" ? param.SelectTo : "";
  if(this.SelectTo != "" && this.Range == false){ //if selectto is set and range not set, set it
      this.Range = true;
  }

  this.AutoRemove = false;

  // Converts a date into '12-Oct-1984' format
  this.getDateString = function (dt) {
      return dt.getDate() + '-' +
          ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][dt.getMonth()] +
          '-' + dt.getFullYear();
  }

  // Converts a date into 'July 2010' format
  this.getMonthYearString = function (dt) {
      return ['January', 'February', 'March', 'April', 'May', 'June', 'July',
          'August', 'September', 'October', 'November', 'December'][dt.getMonth()] +
          ' ' + dt.getFullYear();
  }
  var calobj = this;

  this.Remove = function () {
     // alert('remove')
      // if(this.AutoRemove){
      var cont = document.getElementsByClassName(this.BodyClass);

      if (cont != null) {
          var cont = Array.prototype.slice.call(cont);
          // alert(cont.length);
          for (var x = 0,lenx=cont.length; x <lenx ; x++) {
              // alert(cont[x])
              if (cont[x].classList.contains('aim-maincont-popup')) {
                  cont[x].parentElement.removeChild(cont[x]);
              }

          }

          //alert('removed');
      }
      // }

  }

  //trim spaces
  this.Clean = function (val) {
      return val.replace(/^\s+|\s+$/g, '');
  }

  this.ClearTarget = function(){
    if(calobj.Target != null)calobj.Target.value = "";
    calobj.Target.focus();//make the target element receive focus for further editing
}

  this.Destroy = function (e) {
      var targ; // Crossbrowser way to find the target (http://www.quirksmode.org/js/events_properties.html)
      if (!e) var e = window.event;
      if (e.target) targ = e.target;
      else if (e.srcElement) targ = e.srcElement;
      if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
      if (typeof targ.classList != _UND && !targ.classList.contains("aim-calender-ctr")) {
          if(calobj.RangeStart != null){
              if(calobj.Target != null)calobj.Target.value = calobj.Clean(calobj.Target.value.replace("-",""));
              calobj.RangeStart = null;
          }
          calobj.Remove();
      }
  }

  //function to select range
  this.SelectRange = function (MinDate, MaxDate) {
      var loopMinDate = new Date(MinDate.getFullYear() + "-" + (MinDate.getMonth() + 1)+ "-" + MinDate.getDate());
      var loopMaxDate = new Date(MaxDate.getFullYear() + "-" + (MaxDate.getMonth() + 1)+ "-" + MaxDate.getDate());
      if (loopMinDate.getTime() > loopMaxDate.getTime()) {
          var temp = loopMinDate;
          loopMinDate = loopMaxDate;
          loopMaxDate = temp;
      } else if (loopMinDate.getTime() == loopMaxDate.getTime()) {
          //id
          var btn = this.WeekDisplay.getElementsByClassName(loopMinDate.getDate() + "_" + (loopMinDate.getMonth() + 1) + "_" + loopMinDate.getFullYear());
          if (btn != null) btn[0].classList.add(this.SelectedClass);
          return;
      }
      
      while (1) {
          var btn = this.WeekDisplay.getElementsByClassName(loopMinDate.getDate() + "_" + (loopMinDate.getMonth() + 1) + "_" + loopMinDate.getFullYear());
          if (btn != null && btn.length > 0) btn[0].classList.add(this.SelectedClass);

          if (loopMinDate.getDate() == loopMaxDate.getDate() && loopMinDate.getMonth() == loopMaxDate.getMonth() && loopMinDate.getFullYear() == loopMaxDate.getFullYear()) {
              break;
          }

          loopMinDate.setDate(loopMinDate.getDate() + 1);
      }
  }

  this.SelectRangeMonth = function (MinDate, MaxDate) {
      var loopMinDate = new Date(MinDate.getFullYear() + "-" + (MinDate.getMonth() + 1));
      var loopMaxDate = new Date(MaxDate.getFullYear() + "-" + (MaxDate.getMonth() + 1));
      if (loopMinDate.getTime() > loopMaxDate.getTime()) {
          var temp = loopMinDate;
          loopMinDate = loopMaxDate;
          loopMaxDate = temp;
      } else if (loopMinDate.getTime() == loopMaxDate.getTime()) {
          //id
          var btn = this.MonthDisplay.getElementsByClassName((loopMinDate.getMonth() + 1) + "_" + loopMinDate.getFullYear());
          if (btn != null) btn[0].classList.add(this.SelectedClass);
          return;
      }
      
      while (1) {
          var btn = this.MonthDisplay.getElementsByClassName((loopMinDate.getMonth() + 1) + "_" + loopMinDate.getFullYear());
          if (btn != null && btn.length > 0) btn[0].classList.add(this.SelectedClass);

          if (loopMinDate.getMonth() == loopMaxDate.getMonth() && loopMinDate.getFullYear() == loopMaxDate.getFullYear()) {
              break;
          }

          loopMinDate.setMonth(loopMinDate.getMonth() + 1);
      }
  }

  this.SelectRangeYear = function (MinDate, MaxDate) {
      var loopMinDate = new Date(MinDate.getFullYear()+"-1");
      var loopMaxDate = new Date(MaxDate.getFullYear()+"-1");
      if (loopMinDate.getTime() > loopMaxDate.getTime()) {
          var temp = loopMinDate;
          loopMinDate = loopMaxDate;
          loopMaxDate = temp;
      } else if (loopMinDate.getTime() == loopMaxDate.getTime()) {
          //id
          var btn = this.YearDisplay.getElementsByClassName(loopMinDate.getFullYear());
          if (btn != null) btn[0].classList.add(this.SelectedClass);
          return;
      }
      
      while (1) {
          var btn = this.YearDisplay.getElementsByClassName(loopMinDate.getFullYear());
         // _.Log(loopMinDate.getFullYear());
          if (btn != null && btn.length > 0) btn[0].classList.add(this.SelectedClass);

          if (loopMinDate.getFullYear() == loopMaxDate.getFullYear()) {
              break;
          }

          loopMinDate.setFullYear(loopMinDate.getFullYear() + 1);
      }
  }

  //check validity
  this.DateIsValid = function(dateobj){
      return isNaN(dateobj.getTime())?false:true;
  }


  //create the week calender *****************************************************
  this.Create = function (tbvalue) {
      //alert('jdjd');
      targetval = this.Target == null ? '' : this.Target.value;
      if (typeof tbvalue == "undefined") {
          tbvaluearr = this.Clean(targetval).split("-");
          tbvalue = tbvaluearr[0];

      }

      var tbvaluemax = null;
      //check if range selection
      if (this.Range) {
          tbvaluearr = this.Clean(targetval).split("-");
          if (tbvaluearr.length > 0) {
              tbvaluemin = this.Clean(tbvaluearr[0]);
              if (typeof tbvaluearr[1] != 'undefined') {
                  tbvaluemax = this.Clean(tbvaluearr[1]);
                  tbvaluemax = tbvaluemax == "" ? null : tbvaluemax;
              }
          }

      }

      //get the current date
      //tbvalue = typeof tbvalue == "undefined"?event.target.getAttribute('data-date'):tbvalue
      // alert(tbvalue);
      var curdatestr = this.ParseMyDate(tbvalue);
      // alert(curdatestr);
      var CurDate = new Date(curdatestr);
      // alert(CurDate);
      var CurDateMax = null, CurDateMin = null;
      if (this.Range) {
          //alert(tbvaluemax);
          if (tbvaluemin != null) CurDateMin = new Date(this.ParseMyDate(tbvaluemin));
          if (tbvaluemax != null) CurDateMax = new Date(this.ParseMyDate(tbvaluemax));
      }
      var TodayDate = new Date();

      //create the main table
      var maintb = document.createElement('table');

      if(this.Caption != ""){
  //add the caption
          var caption = maintb.createCaption();
          caption.textContent = this.Caption;
          caption.className = 'aim-calender-ctr';
      }
      
      //maintb.cellPadding = "10px";
      //maintb.cellSpacing ="0px";
      //maintb.border ="1px";
      maintb.className = 'maintb aim-calender-ctr ' + this.TableClass;
      var thead = maintb.createTHead();

      //add the header row ************************

      var headerrw = thead.insertRow();
      headerrw.className = ' aim-calender-ctr';
      //insert the header text cell
      var htxt = headerrw.insertCell();
      htxt.className = ' aim-calender-ctr';
      htxt.style.textAlign = "left";
      htxt.colSpan = 4;
      var btn = document.createElement('button');
      //alert(CurDate);
      btn.className = 'aim-calender-ctr';
      btn.textContent = this.getMonthYearString(CurDate);
      btn.title="View Month Calendar";
      btn.setAttribute('data-date', CurDate.getDate() + '/' + (CurDate.getMonth() + 1) + '/' + CurDate.getFullYear());
      btn.onclick = this.CreateMonthCalender;
      btn.type = "button";
      htxt.appendChild(btn);
      //htxt.textContent = this.getMonthYearString(CurDate);
      //htxt.textContent = CurDate.getMonth();
      //insert the prev / next control
      var prevctr = headerrw.insertCell();
      prevctr.className = ' aim-calender-ctr';
      prevctr.title = "Previous";
      var pbtn = document.createElement('button');
      pbtn.className = 'aim-calender-ctr';
      pbtn.innerHTML = '&#10094';
      pbtn.style.transform = "rotate(90deg)";
      pbtn.type = "button";
      prevctr.appendChild(pbtn);
      //prevctr.innerHTML = '&#10094';
      var prvdate = new Date(CurDate.getFullYear() + '-' + (CurDate.getMonth() + 1) + '-' + CurDate.getDate());
      prvdate.setMonth(prvdate.getMonth() - 1);
      //prvdate = new Date(CurDate.getFullYear()+'-'+CurDate.getMonth()+"-"+CurDate.getDate());
      pbtn.setAttribute('data-date', this.FormatDate(prvdate));
      pbtn.onclick = this.ReCreate;

      var nextctr = headerrw.insertCell();
      nextctr.className = ' aim-calender-ctr';
      nextctr.title = "Next";
      var nbtn = document.createElement('button');
      nbtn.className = 'aim-calender-ctr';
      nbtn.innerHTML = '&#10095';
      nbtn.style.transform = "rotate(90deg)";
      nbtn.type = "button";
      nextctr.appendChild(nbtn);
      //nextctr.innerHTML = '&#10095';
      var nextdate = new Date(CurDate.getFullYear() + '-' + (CurDate.getMonth() + 1) + '-' + CurDate.getDate());
      nextdate.setMonth(nextdate.getMonth() + 1);
      nbtn.setAttribute('data-date', nextdate.getDate() + '/' + (nextdate.getMonth() + 1) + '/' + nextdate.getFullYear());
      nbtn.onclick = this.ReCreate;

      var cleartd = headerrw.insertCell();
      cleartd.title = "Clear";
        //cleartd.className = ' aim-calender-ctr';
        var clbtn = document.createElement('button');
        //clbtn.className = 'aim-calender-ctr';
        clbtn.innerHTML = '&#9974';
        clbtn.type = "button";
        cleartd.appendChild(clbtn);
        clbtn.onclick = this.ClearTarget;

      //add the header row ************************

      //add the week days row ************************
      var tbody = maintb.createTBody();
      var wkd = tbody.insertRow();
      wkd.className = ' aim-calender-ctr';
      var weekdayarr = ['Su', 'Mo', 'Te', 'We', 'Th', 'Fr', 'Sa'];
      for (var w = 0,lenw=weekdayarr.length; w < lenw; w++) {
          /* var sp = document.createElement('span');
             sp.className = 'aim-calender-ctr';
             sp.textContent = weekdayarr[w]; */
          var wkdk = wkd.insertCell();
          wkdk.className = 'aim-calender-ctr';
          wkdk.innerHTML = '<div class="aim-calender-ctr">' + weekdayarr[w] + '</div>';
          //wkd.insertCell().appendChild(btn);
      }
      /* wkd.insertCell().textContent = 'Su';
      wkd.insertCell().textContent = 'Mo';
      wkd.insertCell().textContent = 'Te';
      wkd.insertCell().textContent = 'We';
      wkd.insertCell().textContent = 'Th';
      wkd.insertCell().textContent = 'Fr';
      wkd.insertCell().textContent = 'Sa'; */
      //add the week days row ************************

      // get the first day of the curDate month
      var date = new Date(CurDate.getFullYear(), CurDate.getMonth(), 1, 0, 0, 0, 0);

      //get the week day the month starts with
      var wkday = date.getDay();
      //get the previous month days that will enter this month calendar
      var prevmontDays = wkday;

      //let the day start from the prev month day that enters this month
      var date = new Date(CurDate.getFullYear(), CurDate.getMonth(), 1 - prevmontDays, 0, 0, 0, 0);

var totalwk = this.Caption != ""?2.5:2;
      //loop to form each week of the month
      while (1) {
          //create the week row
          var wkrw = tbody.insertRow();
          wkrw.className = ' aim-calender-ctr';
          totalwk++;
          //loop through all days of the week
          for (var d = 0; d < 7; d++) {
              //get the current day
              var curday = date.getDate();
              //insert to the week row
              var dtb = wkrw.insertCell();
              dtb.className = 'aim-calender-ctr';
              var btn = document.createElement('button');
              btn.className = (TodayDate.getDate() == date.getDate() && TodayDate.getMonth() == date.getMonth() && TodayDate.getFullYear() == date.getFullYear()) ? 'aim-calender-ctr ' + this.TodayClass : 'aim-calender-ctr';
              btn.textContent = curday;
              btn.setAttribute('data-date', date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear());
              btn.className += " " + date.getDate() + '_' + (date.getMonth() + 1) + '_' + date.getFullYear();
              if (date.getMonth() != CurDate.getMonth()) {
                  btn.style.opacity = "0.4";
              }
              btn.type = "button";
              btn.onmouseout = function(){
                  var dts = this.getAttribute('data-date');
                  if (calobj.Range == true) {
                      if (calobj.RangeStart != null) {
                          var maxDatess = new Date(calobj.ParseMyDate(dts));
                          //exclude class name
var exclclsnm = calobj.RangeStart.getDate() + '_' + (calobj.RangeStart.getMonth() + 1) + '_' + calobj.RangeStart.getFullYear();
                          var des = calobj.DeselectAll(calobj.WeekDisplay,exclclsnm);
                      }
                  }
              }
              btn.onmouseover = function(){
                  var dts = this.getAttribute('data-date');
                  if (calobj.Range == true) {
                      if (calobj.RangeStart != null) {
                          var maxDatess = new Date(calobj.ParseMyDate(dts));
                          //exclude class name
//var exclclsnm = calobj.RangeStart.getDate() + '_' + (calobj.RangeStart.getMonth() + 1) + '_' + calobj.RangeStart.getFullYear();
                         // var des = calobj.DeselectAll(calobj.WeekDisplay,exclclsnm);
                         // _.Log("Start Deselection Date: "+calobj.FormatDate(calobj.RangeStart));
                         if(maxDatess.getTime() > calobj.RangeStart.getTime()){
                             calobj.SelectRange(calobj.RangeStart, maxDatess);
                         }else{
                          calobj.SelectRange(maxDatess, calobj.RangeStart);
                         }
                          
                          //_.Log("End Deselection Date: "+calobj.FormatDate(calobj.RangeStart));
                      }
                  }
              }
              btn.onclick = this.SetDate;
              dtb.appendChild(btn);
              //increment the date
              date.setDate(curday + 1); // Increment a day
          }

          //if the date is not the current month terminate
          if (date.getMonth() != CurDate.getMonth()) break;

      }
      //get the container
      if (this.Display != "") {
          var maincont = document.getElementById(this.Display);
          //maincont.className = "";
          //this.AutoRemove = false;
      } else {
          //geet the target next sibling
          var sibling = this.Target.nextSibling;
          if (sibling != null && typeof sibling.classList != "undefined" && sibling.classList.contains('aim-calender-ctr')) {
              sibling.parentElement.removeChild(sibling);
          }

          //create the display box (popup)
          var maincont = document.createElement('div');
          maincont.id = 'mc_' + Math.random() + CurDate.getTime();
          maincont.className = "aim-maincont-popup ";
          //maincont.className = ;
          maincont.style.position = "absolute";
          this.Target.parentNode.insertBefore(maincont, this.Target.nextSibling);
          this.Display = maincont.id;
          ///this.AutoRemove = true;
          // this.Target.insertAdjacentHTML('afterend'.)
      }
      maincont.className += this.BodyClass + ' aim-calender-ctr';
      maincont.style.minHeight = (totalwk * 50) + "px";
      //set the dynamic style
      maincont.style.cssText += "; "+ this.BodyStyle;
      //maincont.style.height = "200px";
      //get all generated calender
      var allcal = document.getElementsByClassName("aim-calender-maincont");
      if (allcal.length > 0) {
          for (var s = 0,lens=allcal.length; s < lens; s++) {
              mtb = allcal.item(s);
              if (mtb.parentElement == maincont) {
                  maincont.removeChild(mtb);
              }

          }
      }

      //add the display opjects to the main object
      this.MainDisplay = maincont;
      //create the Caption div
      
      
      //create calendar container if not exist
      var calcont = document.createElement('div');
      calcont.className = "aim-calender-maincont";
      //create weekcalendar
      var weekcal = document.createElement('div');
      weekcal.className = "weekcalendar " + this.InTransition;
      weekcal.style.cssText = "position:absolute;z-index:4";
      this.WeekDisplay = weekcal;
      //add the week calender
      weekcal.appendChild(maintb)
      //create monthcalendar
      var monthcal = document.createElement('div');
      monthcal.className = "monthcalendar " + this.OutTransition;
      monthcal.style.cssText = "position:absolute;z-index:3;display:none";
      this.MonthDisplay = monthcal;

      //create yearcalendar
      var yearcal = document.createElement('div');
      yearcal.className = "yearcalendar " + this.OutTransition;
      yearcal.style.cssText = "position:absolute;z-index:2;display:none";
      this.YearDisplay = yearcal;

      calcont.appendChild(weekcal);
      calcont.appendChild(monthcal);
      calcont.appendChild(yearcal);
      maincont.appendChild(calcont);

      if (this.Range) {
          //get the target
          if (CurDateMax != null) {
              this.SelectRange(CurDateMin, CurDateMax);
          } else {
              var clname = CurDateMin.getDate() + '_' + (CurDateMin.getMonth() + 1) + '_' + CurDateMin.getFullYear();
              var sobj = this.WeekDisplay.getElementsByClassName(clname);
              if (sobj != null && typeof sobj[0] != "undefined"){
                  sobj[0].classList.add(this.SelectedClass);
              if(this.RangeStart != null){
                  sobj[0].classList.add('startblink');
              }
                  
              }
          }
      } else {
          var tdate = new Date(this.ParseMyDate(targetval));
          var clname = tdate.getDate() + '_' + (tdate.getMonth() + 1) + '_' + tdate.getFullYear();
          var sobj = this.WeekDisplay.getElementsByClassName(clname);
          if (sobj != null && typeof sobj[0] != "undefined"){
              sobj[0].classList.add(this.SelectedClass);
          }
          
      }
  }

  //function to handule date button click
  this.SetDate  = function (dt) {
      //alert(dt);
      var dt = typeof dt != "string"?this.getAttribute('data-date'):dt;
      if (calobj.Range != true) {
          calobj.Target.value = dt;
          calobj.DeselectAll(calobj.WeekDisplay);
          this.classList.add(calobj.SelectedClass);
          calobj.Remove();
          calobj.Target.focus(); //give the set target the focus
      } else { //if range selection
          if (calobj.RangeStart == null) { //if range start not set meaning first selection
              calobj.RangeStart = new Date(calobj.ParseMyDate(dt));
              calobj.Target.value = dt + " - ";
             // _.Log("Start Range: "+dt);
              calobj.DeselectAll(calobj.WeekDisplay);
              this.classList.add(calobj.SelectedClass);
              this.classList.add('startblink');
              
              //alert(calobj.SelectTo);
              if(calobj.SelectTo != ""){
                  //alert('selectto')
                  //check if increamental
                  //var fchar = calobj.SelectTo.substr(0,1);
                  //if(fchar == "+"){
                     // var selectto = _.Engine.Proccessor.GetAttr(calobj.SelectTo);
                     var selectto = calobj.SelectTo;
                      if(calobj.Clean(selectto) != ""){
                          var num = Number.parseInt(selectto);
                          //alert(num);
                          if(!isNaN(num)){ //if increament
                              var ndate = new Date(calobj.RangeStart.getFullYear() + "-" + (calobj.RangeStart.getMonth() + 1) + "-" + calobj.RangeStart.getDate());
                              ndate.setDate(ndate.getDate() + num);
                              
                              calobj.SetDate(ndate.getDate() + "/" +(ndate.getMonth() + 1)+"/"+ndate.getFullYear());
                          }else{ //if to date
                              var ndate = new Date(calobj.ParseMyDate(selectto));
                              if(calobj.DateIsValid(ndate)){
                                  calobj.SetDate(ndate.getDate() + "/" +(ndate.getMonth() + 1)+"/"+ndate.getFullYear());
                              }
                          }
                      }
                      
                  //}
              }
          } else {
             // _.Log("End Range: "+dt);
              var maxDate = new Date(calobj.ParseMyDate(dt));
              //_.Log("Start RangeDate: "+calobj.FormatDate(calobj.RangeStart));
              //_.Log("End RangeDate: "+calobj.FormatDate(maxDate));
              var rtnstr = '';
              if (calobj.RangeStart.getTime() < maxDate.getTime()) {
                  rtnstr = calobj.FormatDate(calobj.RangeStart) + " - " + calobj.FormatDate(maxDate);
              } else if (calobj.RangeStart.getTime() > maxDate.getTime()) {
                  rtnstr = calobj.FormatDate(maxDate) + " - " + calobj.FormatDate(calobj.RangeStart);
              } else {
                  rtnstr = calobj.FormatDate(maxDate);
              }

              calobj.Target.value = rtnstr;
              calobj.DeselectAll(calobj.WeekDisplay);
              calobj.SelectRange(calobj.RangeStart, maxDate);
              calobj.RangeStart = null;
          calobj.RemoveBlink();
              //this.classList.add(calobj.SelectedClass);
              calobj.Remove();
              calobj.Target.focus();//make the target element receive focus for further editing
          }
      }

  }

  this.ReCreate = function (e) {
      var targ; // Crossbrowser way to find the target (http://www.quirksmode.org/js/events_properties.html)
      if (!e) var e = window.event;
      if (e.target) targ = e.target;
      else if (e.srcElement) targ = e.srcElement;
      if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
      tod = targ.getAttribute('data-date');

      calobj.Create(tod);
  }

  this.DeselectAll = function (calendar,exclude) {
      //get all selected in  the supplied calendar
      var sels = calendar.getElementsByClassName(this.SelectedClass);
      if (sels != null) {
          //alert(sels.length)
          var arrRtn = Array.prototype.slice.call(sels);
          for (var ee = 0,lenee=arrRtn.length; ee < lenee; ee++) {
              var el = arrRtn[ee];
              if(typeof exclude == "undefined" || !el.classList.contains(exclude)){
                el.classList.remove(this.SelectedClass);
              }
              
          }
      }
      return true;
  }

  this.RemoveBlink = function(){
      var sels = this.WeekDisplay.getElementsByClassName('startblink');
      if (sels != null) {
          //alert(sels.length)
          var arrRtn = Array.prototype.slice.call(sels);
          for (var ee = 0,lenee=arrRtn.length; ee < lenee; ee++) {
              var el = arrRtn[ee];
              el.classList.remove('startblink');
          }
      }
  }

  //parse my date format
  this.ParseMyDate = function (dt) {
      var today = new Date();
      if (dt == '') {
          return this.Today();
      }
      var dtarr = dt.split("/");
      var day=today.getDate(),month=today.getMonth() + 1,year = today.getFullYear();
     if(dtarr.length > 2){ //day/month/year
      day = Number.parseInt(dtarr[0]);
      day = Number.isNaN(day)?1:day;
      month = Number.parseInt(dtarr[1]);
      month = Number.isNaN(month)?(today.getMonth()+1):month;
      year = Number.parseInt(dtarr[2]);
      year = Number.isNaN(year)?today.getFullYear():year;
     }else if(dtarr.length == 2){
         day = 1;
      month = Number.parseInt(dtarr[0]);
      month = Number.isNaN(month)?(today.getMonth()+1):month;
      year = Number.parseInt(dtarr[1]);
      year = Number.isNaN(year)?today.getFullYear():year; 
     }else if(dtarr.length == 1){
      day = 1;
      month = today.getMonth()+1;
      year = Number.parseInt(dtarr[0]);
      year = Number.isNaN(year)?today.getFullYear():year;
     }

     //get the last day of the date supplied
     var newdate = new Date(year,month,0,0,0,0,0);
     var lastday = newdate.getDate();
     day = day > lastday?lastday:day;
      return year + '-' + month + '-' + day;
  }

  //get todays date
  this.Today = function () {
      var dt = new Date();
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate();
  }

  this.FormatDate = function (dateobj) {
      return dateobj.getDate() + '/' + (dateobj.getMonth() + 1) + '/' + dateobj.getFullYear();
  }

  this.Init = (function (param, obj) {
      //alert(obj.Destroy);
      if(obj.Target != null)obj.Target.classList.add('aim-calender-ctr');
      obj.Remove();
      document.addEventListener("click", obj.Destroy);
  })(param, this);

  //Create the Month Calender *************************************
  this.CreateMonthCalender = function () {
      var formbtn = function (txt) {
          var nbtn = document.createElement('button');
          nbtn.className = 'aim-calender-ctr';
          nbtn.innerHTML = txt;
          nbtn.type = "button";
          return nbtn;
      }
      var cdate = this.getAttribute('data-date');
      //process range value
      var targetval = calobj.Target == null ? '' : calobj.Target.value;
      var tbvaluemax = null, tbvaluemin = null;
      var CurDateMax = null, CurDateMin = null;
      //check if range selection
      if (calobj.Range) {
          tbvaluearr = calobj.Clean(targetval).split("-");
          if (tbvaluearr.length > 0) {
              tbvaluemin = calobj.Clean(tbvaluearr[0]);
              if (typeof tbvaluearr[1] != 'undefined') {
                  tbvaluemax = calobj.Clean(tbvaluearr[1]);
                  tbvaluemax = tbvaluemax == "" ? null : tbvaluemax;
              }
          }

          if (tbvaluemin != null) CurDateMin = new Date(calobj.ParseMyDate(tbvaluemin));
          if (tbvaluemax != null) CurDateMax = new Date(calobj.ParseMyDate(tbvaluemax));

      }
      //alert(cdate);
      //get the date object
      var CdateObj = new Date(calobj.ParseMyDate(cdate))

      var TodayDate = new Date();

      //get date from target
      var targetval = calobj.Target == null ? '' : calobj.Target.value;
      if (calobj.Range) {
          //if(targetval != ""){
          var targetvalarr = targetval.split("-");
          targetval = calobj.Clean(targetvalarr[0]);

      }
      var targetDate = targetval == "" ? CdateObj : new Date(calobj.ParseMyDate(targetval))

      //get the content box
      var contbx = calobj.MonthDisplay;

      //create the main table
      var wktable = document.createElement('table');
      wktable.className = 'aim-calender-ctr ' + calobj.TableClass;

      if(calobj.Caption != ""){
          //add the caption
                  var caption = wktable.createCaption();
                  caption.textContent = calobj.Caption;
                  caption.className = 'aim-calender-ctr';
              }
      //wktable.cellPadding = "10px";
      //wktable.cellSpacing ="0px";
      //wktable.border ="1px";

      wkthead = wktable.createTHead();
      //add the header row
      var wkheadrw = wkthead.insertRow();
      wkheadrw.className = 'aim-calender-ctr';

      var headertxt = wkheadrw.insertCell();
      headertxt.colSpan = 1;
      var hbtn = formbtn(CdateObj.getFullYear());
      hbtn.title="View Year Calendar";
      hbtn.setAttribute('data-date', CdateObj.getDate() + '/' + (CdateObj.getMonth() + 1) + '/' + CdateObj.getFullYear());
      hbtn.onclick = calobj.CreateYearCalender;
      headertxt.appendChild(hbtn);

      var prevbtn = formbtn('&#10094');
      prevbtn.style.transform = "rotate(90deg)";
      prevbtn.setAttribute('data-date', CdateObj.getDate() + '/' + (CdateObj.getMonth() + 1) + '/' + (CdateObj.getFullYear() - 1));
      prevbtn.onclick = calobj.CreateMonthCalender;
      wkheadrw.insertCell().appendChild(prevbtn);

      var nxtbtn = formbtn('&#10095');
      nxtbtn.style.transform = "rotate(90deg)";
      nxtbtn.setAttribute('data-date', CdateObj.getDate() + '/' + (CdateObj.getMonth() + 1) + '/' + (CdateObj.getFullYear() + 1));
      nxtbtn.onclick = calobj.CreateMonthCalender;
      wkheadrw.insertCell().appendChild(nxtbtn);

      var cleartd = wkheadrw.insertCell();
        cleartd.title = "Clear";
          //cleartd.className = ' aim-calender-ctr';
          var clbtn = document.createElement('button');
          //clbtn.className = 'aim-calender-ctr';
          clbtn.innerHTML = '&#9974';
          clbtn.type = "button";
          cleartd.appendChild(clbtn);
          clbtn.onclick = calobj.ClearTarget;

      wktbody = wktable.createTBody();
      //add the month  row
      var wkmth = wktbody.insertRow();
      var mtharr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr'];
      var totrw = 4;
      var cnt = 0;
      for (var d = 0,lend=mtharr.length; d < lend; d++) {
          var mnt = mtharr[d];
          if (cnt == totrw) {
              var wkmth = wktbody.insertRow();
              cnt = 0;
          }
          mntcell = wkmth.insertCell();
          //mntcell.colSpan = 2;

          var mbtn = formbtn(mnt);
          var y = CdateObj.getFullYear();
          var m = d + 1
          if (d > 11) { //new year
              mbtn.style.opacity = "0.4";
              y++;
              m = m - 12;
          }
          mbtn.setAttribute('data-date', CdateObj.getDate() + '/' + m + '/' + y);
          mbtn.classList.add(m+"_"+y);
          //selected
          if (targetDate.getMonth() == d && targetDate.getFullYear() == y) {
              mbtn.classList.add(calobj.SelectedClass);
          }

          //today
          if (TodayDate.getMonth() == d && TodayDate.getFullYear() == y) {
              mbtn.classList.add(calobj.TodayClass);
          }
          mbtn.onmouseout = function(){
              var dts = this.getAttribute('data-date');
              if (calobj.Range == true) {
                  if (calobj.RangeStart != null) {
                      var maxDatess = new Date(calobj.ParseMyDate(dts));
                      //exclude class name
var exclclsnm = (calobj.RangeStart.getMonth() + 1) + '_' + calobj.RangeStart.getFullYear();
                      var des = calobj.DeselectAll(calobj.MonthDisplay,exclclsnm);
                  }
              }
          }

          mbtn.onmouseover = function(){
              var dts = this.getAttribute('data-date');
              if (calobj.Range == true) {
                  if (calobj.RangeStart != null) {
                      var maxDatess = new Date(calobj.ParseMyDate(dts));
                      //exclude class name
/* var exclclsnm = (calobj.RangeStart.getMonth() + 1) + '_' + calobj.RangeStart.getFullYear();
                      var des = calobj.DeselectAll(calobj.MonthDisplay,exclclsnm); */
                     // _.Log("Start Deselection Date: "+calobj.FormatDate(calobj.RangeStart));
                     if(maxDatess.getTime() > calobj.RangeStart.getTime()){
                         calobj.SelectRangeMonth(calobj.RangeStart, maxDatess);
                     }else{
                      calobj.SelectRangeMonth(maxDatess, calobj.RangeStart);
                     }
                      
                      //_.Log("End Deselection Date: "+calobj.FormatDate(calobj.RangeStart));
                  }
              }
          }
          mbtn.onclick = calobj.ReCreate;
          mntcell.appendChild(mbtn);
          cnt++;
      }

      contbx.innerHTML = '';
      contbx.appendChild(wktable);

      calobj.WeekDisplay.style.display = 'none';
      calobj.YearDisplay.style.display = 'none';
      calobj.MonthDisplay.style.display = 'block';
      contbx.style.zIndex = "200";
      calobj.MainDisplay.style.minHeight = calobj.Caption != ""?(5.5 * 70) + "px":(5 * 70) + "px";

      //select all range month
      if (calobj.Range) {
          //get the target
          if (CurDateMax != null) {
              calobj.SelectRangeMonth(CurDateMin, CurDateMax);
          } else {
              var clname = (CurDateMin.getMonth() + 1) + '_' + CurDateMin.getFullYear();
              var sobj = calobj.MonthDisplay.getElementsByClassName(clname);
              if (sobj != null && typeof sobj[0] != "undefined"){
                  sobj[0].classList.add(calobj.SelectedClass);
              if(calobj.RangeStart != null){
                  sobj[0].classList.add('startblink');
              }
                  
              }
          }
      }

  }

  //Create the Month Calender **********************************
  this.CreateYearCalender = function () {
      var formbtn = function (txt) {
          var nbtn = document.createElement('button');
          nbtn.className = 'aim-calender-ctr';
          nbtn.innerHTML = txt;
          nbtn.type = "button";
          return nbtn;
      }
      var cdate = this.getAttribute('data-date');

      //proccess range value
      var targetval = calobj.Target == null ? '' : calobj.Target.value;
      var tbvaluemax = null, tbvaluemin = null;
      var CurDateMax = null, CurDateMin = null;
      //check if range selection
      if (calobj.Range) {
          tbvaluearr = calobj.Clean(targetval).split("-");
          if (tbvaluearr.length > 0) {
              tbvaluemin = calobj.Clean(tbvaluearr[0]);
              if (typeof tbvaluearr[1] != 'undefined') {
                  tbvaluemax = calobj.Clean(tbvaluearr[1]);
                  tbvaluemax = tbvaluemax == "" ? null : tbvaluemax;
              }
          }

          if (tbvaluemin != null) CurDateMin = new Date(calobj.ParseMyDate(tbvaluemin));
          if (tbvaluemax != null) CurDateMax = new Date(calobj.ParseMyDate(tbvaluemax));

      }

      //get the date object
      var CdateObj = new Date(calobj.ParseMyDate(cdate));

      //get target date
      //get date from target
      var targetval = calobj.Target == null ? '' : calobj.Target.value;
      if (calobj.Range) {
          //if(targetval != ""){
          var targetvalarr = targetval.split("-");
          targetval = calobj.Clean(targetvalarr[0]);

      }
      var targetDate = targetval == "" ? CdateObj : new Date(calobj.ParseMyDate(targetval))

      var TodayDate = new Date();

      //get the content box
      var contbx = calobj.YearDisplay;

      //current Year
      var year = CdateObj.getFullYear();
      var minyear = year - (year % 12);
      var maxyear = minyear + 11;

      //create the main table
      var wktable = document.createElement('table');
      wktable.className = 'aim-calender-ctr ' + calobj.TableClass;

      if(calobj.Caption != ""){
          //add the caption
                  var caption = wktable.createCaption();
                  caption.textContent = calobj.Caption;
                  caption.className = 'aim-calender-ctr';
              }
      //wktable.cellPadding = "10px";
      //wktable.cellSpacing ="0px";
      //wktable.border ="1px";
      var wkthead = wktable.createTHead()
      //add the header row
      var wkheadrw = wkthead.insertRow();
      wkheadrw.className = 'aim-calender-ctr';

      var headertxt = wkheadrw.insertCell();
      headertxt.colSpan = 1;
      headertxt.appendChild(formbtn(minyear + '-' + maxyear));

      var prevbtn = formbtn('&#10094');
      prevbtn.style.transform = "rotate(90deg)";
      prevbtn.setAttribute('data-date', CdateObj.getDate() + '/' + (CdateObj.getMonth() + 1) + '/' + (minyear - 1));
      prevbtn.onclick = calobj.CreateYearCalender;
      wkheadrw.insertCell().appendChild(prevbtn);

      var nxtbtn = formbtn('&#10095');
      nxtbtn.style.transform = "rotate(90deg)";
      nxtbtn.setAttribute('data-date', CdateObj.getDate() + '/' + (CdateObj.getMonth() + 1) + '/' + (maxyear + 1));
      nxtbtn.onclick = calobj.CreateYearCalender;
      wkheadrw.insertCell().appendChild(nxtbtn);

      var wktbody = wktable.createTBody()
      //add the month  row
      var wkmth = wktbody.insertRow();

      var cleartd = wkheadrw.insertCell();
        cleartd.title = "Clear";
          //cleartd.className = ' aim-calender-ctr';
          var clbtn = document.createElement('button');
          //clbtn.className = 'aim-calender-ctr';
          clbtn.innerHTML = '&#9974';
          clbtn.type = "button";
          cleartd.appendChild(clbtn);
          clbtn.onclick = calobj.ClearTarget;
      //var mtharr = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
      var totrw = 4;
      var cnt = 0;
      var plusextrayear = maxyear + 4
      for (var d = minyear; d <= plusextrayear; d++) {
          //var mnt = mtharr[d];
          if (cnt == totrw) {
              var wkmth = wktbody.insertRow();
              cnt = 0;
          }
          mntcell = wkmth.insertCell();
          //mntcell.colSpan = 2;
          var mbtn = formbtn(d);
          if (d > maxyear) {
              mbtn.style.opacity = "0.4";
          }
          mbtn.classList.add(d);
          mbtn.setAttribute('data-date', CdateObj.getDate() + '/' + (CdateObj.getMonth() + 1) + '/' + d);
          if (targetDate.getFullYear() == d) { //if current year select it
              mbtn.classList.add(calobj.SelectedClass);
          }

          if (TodayDate.getFullYear() == d) { //if current year select it
              mbtn.classList.add(calobj.TodayClass);
          }

          mbtn.onmouseout = function(){
              var dts = this.getAttribute('data-date');
              if (calobj.Range == true) {
                  if (calobj.RangeStart != null) {
                      var maxDatess = new Date(calobj.ParseMyDate(dts));
                     
                      //exclude class name
var exclclsnm =  calobj.RangeStart.getFullYear();
                      var des = calobj.DeselectAll(calobj.YearDisplay,exclclsnm);
                  }
              }
          }


          mbtn.onmouseover = function(){
              var dts = this.getAttribute('data-date');
              if (calobj.Range == true) {
                  if (calobj.RangeStart != null) {
                      var maxDatess = new Date(calobj.ParseMyDate(dts));
                     
                      //exclude class name
/* var exclclsnm =  calobj.RangeStart.getFullYear();
                      var des = calobj.DeselectAll(calobj.YearDisplay,exclclsnm); */
                     // _.Log("Start Deselection Date: "+calobj.FormatDate(calobj.RangeStart));
                     if(maxDatess.getTime() > calobj.RangeStart.getTime()){
                         calobj.SelectRangeYear(calobj.RangeStart, maxDatess);
                     }else{
                      calobj.SelectRangeYear(maxDatess,calobj.RangeStart );
                     }
                      
                      //_.Log("End Deselection Date: "+calobj.FormatDate(calobj.RangeStart));
                  }
              }
          }
          mbtn.onclick = calobj.CreateMonthCalender;
          mntcell.appendChild(mbtn);
          cnt++;
      }

      contbx.innerHTML = '';
      contbx.appendChild(wktable);
      calobj.WeekDisplay.style.display = 'none';
      calobj.MonthDisplay.style.display = 'none';
      calobj.MonthDisplay.className = "monthcalendar " + calobj.InTransition;
      calobj.YearDisplay.style.display = 'block';
      contbx.style.zIndex = "200";
      calobj.MainDisplay.style.minHeight = calobj.Caption != ""?(5.5 * 70) + "px":(5 * 70) + "px";
      //select all range month
      if (calobj.Range) {
          //get the target
          if (CurDateMax != null) {
              calobj.SelectRangeYear(CurDateMin, CurDateMax);
          } else {
              var clname = CurDateMin.getFullYear();
              var sobj = calobj.YearDisplay.getElementsByClassName(clname);
              if (sobj != null && typeof sobj[0] != "undefined"){
                  sobj[0].classList.add(calobj.SelectedClass);
              if(calobj.RangeStart != null){
                  sobj[0].classList.add('startblink');
              }
                  
              }
          }
      }

  }



}

