/*
Title: EnduroMonth
  <MooMonth.Base>

Script: EnduroMonth.js
  EnduroMonth - Full javascript calendar based on MooMonth which uses MooTools.

License:
  CC-GNU LGPL, <http://creativecommons.org/licenses/LGPL/2.1/>


EnduroMonth Copyright:
 copyright (c) 2008 David Driscoll, <http://endurotracker.com>
MooMonth Copyright:
  copyright (c) 2007 Roland Poulter, <http://rolandpoulter.com>

EnduroMonth Credits:
 Based on the great work of MooMonth
MooMonth Credits:
  - All this wouldn't be possible without MooTools <http://mootools.net>, (c) 2007 Valerio Proietti, MIT-style license
*/

var MooMonth = {
  version: "0.10"
};

/*
Constant: $DaysPerWeek
  <MooMonth.Constants.DaysPerWeek>
*/

/*
Namespace: MooMonth.Constants
*/

MooMonth.Constants = {
  
  /*
  Property: DaysPerWeek
    Weeks always have 7 days
  */
  
  DaysPerWeek: 7
};
$DaysPerWeek = MooMonth.Constants.DaysPerWeek;

/*
Namespace: MooMonth.Module
*/

MooMonth.Module = {
  
  /*
  Property: Coorinates
    <MooMonth.Module.Coordinates>
  */
  
  Coordinates: {},
  
  /*
  Property: Selectors
    <MooMonth.Module.Selectors>
  */
  
  Selectors: {},
  
  /*
  Property: Transitions
    <MooMonth.Module.Transitions>
  */
  
  Transitions: {}
};

/*
Namespace: MooMonth.Module.Coordinates
  Alias: $mmC
*/

MooMonth.Module.Coordinates = {
  
  /*
  Function: from
    Get the day, and week position from a <MooMonth.Element> day element, or UID.
  
  Arguments:
    el *OR* number - Either a <MooMonth.Element> day element, or a UID.
  
  Returns:
    array - An array with the day, and week position.
  */
  
  from: function(el) {
    var type = $type(el), d, w;
    if(type === "string") uid = el.split("-").getLast();
    else if(type === "element") uid = el.id.split("-").getLast();
    else uid = el;
    d = uid % $DaysPerWeek;
    w = (uid - d) / $DaysPerWeek;
    return [d, w];
  },
  
  /*
  Function: toId
    Find the UID of a day based on it's position.
  
  Arguments:
    number - Day position, number.
    number - Week position, number.
  
  Returns:
    number - UID of the <MooMonth.Element> day element.
  */
  
  toId: function(d, w) {
    return (w.toInt() * $DaysPerWeek) + d.toInt();
  }
};
$mmC = MooMonth.Module.Coordinates;

/*
Namespace: MooMonth.Module.Selectors
  Alias: $mmS
*/

MooMonth.Module.Selectors = {
  
  /*
  Function: from
    Find an element from a <MooMonth.Element>.
  
  Arguments:
    string - Selector prefix.
    number *OR* array - A UID. *OR* Day poisition. (/w week argument) *OR* Array with the day and week positions.
    number - Optional, Week poisition.
  
  Returns:
    el - A calendar element.
  */
  
  from: function(prefix, uid) {
    if(!$defined(uid)) return false;
    if($type(uid) === "array") {
      return $(prefix + "-" + $mmC.toId.pass(uid));
    } else if(arguments.length > 2) {
      return $(prefix + "-" + $mmC.toId(uid, arguments[2]));
    } else {
      return $(prefix + "-" + uid);
    }
  },
  
  /*
  Function: fromId
    Same as <from> but assumes UID is just a number.
  */
  
  fromId: function(prefix, uid) {
    return $(prefix + "-" + uid);
  },
  
  /*
  Function: toId
    Find the UID of a <MooMonth.Element> element.
  
  Arguments:
    el - <MooMonth.Element> element.
  
  Returns:
    number - UID of the element.
  
  Note:
    The UID from content in a MooMonth.Element is different then the UID from a wrapper element.
  */
  
  toId: function(el) {
    return $(el).id.split("-").getLast().toInt();
  }
};
$mmS = MooMonth.Module.Selectors;

/*
Namespace: MooMonth.Module.Transitions
  Alias: $mmT
*/

MooMonth.Module.Transitions = {
  
  /*
  Function: forEach
    
  
  Arguments:
    array - A list of (MooTools: Fx.Elements) effects.
    object - Styles to be passed into each effect as the transition.
  */
  
  forEach: function(effects, styles) {
    effects.each(function(effect, index) {
      var elements = {};
      if($chk(styles[index].height)) $extend(styles[index], {lineHeight: styles[index].height});
      for(var i = 0; i < effect.elements.length; i++) elements[i] = styles[index];
      effect.start(elements);
    });
  }
};
$mmT = MooMonth.Module.Transitions;



/*
Class: MooMonth.DateObject
  A "Utility" Class which adds a set property for seting dates.
*/

MooMonth.DateObject = new Class({
  
  /*
  Property: set
    Sets the date value, and calls this.update.
  
  Arguments:
    timestamp - New date.
  */
  
  set: function(date) {
    this.date = new Date(date);
    if(this.update) this.update();
  }
});

/*
Class: MooMonth.Day

Arguments:
  timestamp - This date.
  week - <MooMonth.Week> object.
*/

MooMonth.Day = new Class({
  initialize: function(date, week) {
    this.week = week;
    this.set(date);
    this.events = [];
  },
  update: function() {
    this.day = this.date.getDate();
    this.weekDay = this.date.getDay();
    this.name = this.date.getDayName();
  },
  addEvent: function(event) {
    this.events.push(event);
  }
});
MooMonth.Day.implement(new MooMonth.DateObject);

/*
Class: MooMonth.Week

Arguments:
  timestamp - This date.
  month - <MooMonth.Month> object.
*/

MooMonth.Week = new Class({
  initialize: function(date, month) {
    this.month = month;
    this.set(date);
  },
  
  update: function() {
    var date = this.date.getDate(),
        week = this.date.getWeek(),
        month = this.month.month,
        year = this.month.year.year;
    if(month === 11 && week === 0) week = 52;
    if(month === 0 && week === 0) {week = 0; year -= 1;}
    this.week = week;
    this.name = this.week + 1;
    this.monthWeek = this.week - this.month.date.getMonthWeek();
    this.days = [];
    for(var i = 0; i < $DaysPerWeek; i++) {
      this.days[i] = new MooMonth.Day(new Date(year, this.date.getMonth(), date + i), this);
    }
  }
});
MooMonth.Week.implement(new MooMonth.DateObject);

/*
Class: MooMonth.Month

Arguments:
  timestamp - This date.
  month - <MooMonth.Year> object.
*/

MooMonth.Month = MooMonth.DateObject.extend({
  initialize: function(date, year) {
    this.year = year;
    this.set(date);
  },
  update: function() {
    var firstDay = this.date.getMonthDay(),
        endDay = this.date.getMonthEnd(),
        firstWeek = this.date.getMonthWeek(),
        fullMonth = firstDay - 1 + endDay,
        weeksLength = Math.ceil(fullMonth / $DaysPerWeek);
    this.month = this.date.getMonth();
    this.name = this.date.getMonthName();
    this.offset = firstDay - 1;
    this.weeks = [];
    for(var i = 0; i < weeksLength; i++) {
      var temp = temp = this.date.copy();
      this.weeks[i] = new MooMonth.Week(temp.setWeek(firstWeek + i), this);
    }
  }
});
MooMonth.Month.implement(new MooMonth.DateObject);

/*
Class: MooMonth.Year

Arguments:
  timestamp - This date.
*/

MooMonth.Year = new Class({
  initialize: function(date) {
    this.set(date);
  },
  update: function() {
    this.year = this.date.getFullYear();
    this.offset = this.date.getYearStartDay();
    this.isLeap = this.date.isLeapYear();
  }
});
MooMonth.Year.implement(new MooMonth.DateObject);

/*
Class: MooMonth.Date

Arguments:
  timestamp - This date.
  moomonth - Optional, <MooMonth.Base> object.
*/

MooMonth.Date = new Class({
  //(*date, *root)
  initialize: function(date, root) {
    this.date = new Date(date || $today);
    if(root) this.root = root;
    this.update();
  },
  set: function(date) {
    this.date = new Date(date);
    this.update();
    if(this.root && this.root.fireEvent) 
	{ 
	 this.root.fireEvent("onDateSet");
	 this.root.fireEvent("populateData");
	
	 
	}
  },
  update: function() {
    this.year = new MooMonth.Year(this.date);
    this.month = new MooMonth.Month(this.date, this.year);
    this.week = new MooMonth.Week(this.date, this.month);
    this.day = new MooMonth.Day(this.date, this.week);
  }
});


/*
Class: MooMonth.Session
*/

MooMonth.Session = new Class({
  
});
MooMonth.Session.implement(new Options);


/*
Class: MooMonth.Events
*/

MooMonth.Events = new Class({
  initialize: function(options) {
    this.fetch();
  },
  fetch: function() {
    this.events = [];
  },
  create: function() {
    var event = new MooMonth.Event(arguments);
    event.save();
  }
});

/*
Class: MooMonth.Event
*/

MooMonth.Event = new Class({
  options: {
    
  },
  initialize: function(options) {
    this.setOptions(options);
  },
  save: function() {
    alert(this);
  },
  udpate: function() {
    alert(this);
  },
  destroy: function() {
    alert(this);
  }
});
MooMonth.Event.implement(new Options);


/*
Class: MooMonth.Size

Arguments:
  moomonth - <MooMonth.Base> object.
  array *OR* width *OR* el - _All Optional_, Array with the width, and height. *OR* Element width. (/w height argument) *OR* An element to copy.
  height - Optional, Element height.
*/

MooMonth.Size = new Class({
  //(*root, *([w, h] || w, h) || *wrapper)
  initialize: function(root) {
    var width, height, type = $type(root);
    if(type === "array" || arguments.length > 2) {
      this.type = "solid";
      width = arguments[1][0] || arguments[1];
      height = arguments[1][1] || arguments[2];
    }
    else if(type === "element" || type === "string") {
      this.type = "wrapper";
      this.wrapper = $(arguments[1]);;
      width = this.wrapper.offsetWidth;
      height = this.wrapper.offsetHeight;
    }
    else {
      this.type = "liquid";
      width = window.getWidth();
      height = window.getHeight();
    }
    this.root = root;
    this.setChecker();
    this.update(width, height);
  },
  removeChecker: function() {
    if(this.type === "wrapper") {
      $clear(this.checker);
    } else if(this.type === "liquid") {
      window.onresize = null;
    }
  },
  setChecker: function() {
    if($defined(this.checker)) this.removeChecker();
    if(this.type === "wrapper") {
      this.checker = function() {
        if(this.isPaused) return false;
        var newWidth = this.wrapper.offsetWidth.toInt(), newHeight = this.wrapper.offsetHeight.toInt();
        if(newWidth !== this.width || newHeight !== this.height) this.set(newWidth, newHeight);
      }.periodical(500, this);
    } else if(this.type === "liquid") {
      window.onresize = function() {
        if(this.isPaused) return false;
        this.set(window.getWidth(), window.getHeight());
      }.bind(this);
    }
  },
  set: function(w, h) {
    this.update(w, h);
    if(this.root && this.root.fireEvent) this.root.fireEvent("onSizeSet");
  },
  update: function(w, h) {
    this.width = w;
    this.height = h;
  },
  pause: function() {
    this.isPaused = true;
  },
  resume: function() {
    this.isPaused = false;
  }
});

/*
Class: MooMonth.Resize

Arguments:
  moomonth - <MooMonth.Base> object.
  options - Effect options.
*/

MooMonth.Resize = Fx.Base.extend({
  initialize: function(root, options) {
    this.root = root;
    this.parent(options);
  },
  setNow: function() {
    this.now = this.compute(this.from, this.to);
  },
  compute: function(from, to) {
    return [this.parent(from[0], to[0]), this.parent(from[1], to[1])];
  },
  start: function(from, to) {
    if (!this.options.wait) this.stop();
    else if (this.timer) return this;
    this.root.size.pause();
    this.from = from;
    this.to = to;
    this.change = [this.to[0] - this.from[0], this.to[0] - this.from[0]];
    this.time = $time();
    this.timer = this.step.periodical(Math.round(1000 / this.options.fps), this);
    this.fireEvent('onStart', this.element);
    return this;
  },
  stop: function(end){
    if (!this.timer) return this;
    this.timer = $clear(this.timer);
    this.root.size.resume();
    if (!end) this.fireEvent('onCancel', this.element);
    return this;
  },
  fromTo: function(w, h) {
    this.root.size.removeChecker();
    this.root.size.type = "solid";
    return this.start([this.root.size.width, this.root.size.height], [w, h]);
  },
  toFull: function() {
    var to;
    if($defined(this.root.wrapper)) {
      this.root.size.type = "wrapper";
      to = [this.root.size.wrapper.offsetWidth, this.root.size.wrapper.offsetHeight];
    } else {
      this.root.size.type = "liquid";
      to = [window.getWidth(), window.getHeight()];
    }
    this.root.size.setChecker();
    return this.start([this.root.size.width, this.root.size.height], to);
  },
  increase: function() {
    this.root.size.set(this.now[0], this.now[1]);
  }
});


/*
Class: MooMonth.Element

Arguments:
  moomonth - <MooMonth.Base> object.
  el - Optional, element to be used as the parenNode.
*/

MooMonth.Element = new Class({
  initialize: function(root, element) {
    this.root = root;
    this.uid = this.root.uid;
    this.element = element || this.root.element;
    this.options = this.root.options;
    this.date = this.root.date;
    this.size = this.root.size;
	
	this.username = this.root.username;
    
    this.element.addClass = this.root.type;
    this.wrapper = new Element("div", {
      "id": "calendar-wrapper-" + this.uid,
      "class": "calendar-wrapper"
    }).injectInside(this.element);
    
    this.header = new Element("div", {
      "id": "calendar-header-" + this.uid,
      "class": "calendar-header",
      "style": {"height": this.options.headerHeight + "px"}
    }).injectInside(this.wrapper);
    this.monthLabel = new Element("h1", {
      "id": "calendar-main-label-" + this.uid,
      "class": "calendar-month-label"
    }).injectInside(this.header);
    
    this.main = new Element("div", {
      "id": "calendar-main-" + this.uid,
      "class": "calendar-main"}
    ).injectAfter(this.header);
    
    this.weeks = new Element("div", {
      "id": "calendar-weeks-" + this.uid,
      "class": "calendar-weeks",
      "styles": {"width": this.options.labelSize}
    }).injectInside(this.main);
    this.weeksLabel = new Element("div", {
      "id": "calendar-weeks-labels-" + this.uid,
      "class": "calendar-weeks-label",
      "styles": {"width": this.options.labelSize, "height": this.options.labelSize}
    }).injectInside(this.weeks);
    this.weeksContainer = new Element("div", {
      "id": "calendar-weeks-contianer-" + this.uid,
      "class": "calendar-weeks-container",
      "styles": {"width": this.options.labelSize}
    }).injectAfter(this.weeksLabel);
    
    this.days = new Element("div", {
      "id": "calendar-days-" + this.uid,
      "class": "calendar-days"
    }).injectAfter(this.weeks);
    this.dayLabels = new Element("div", {
      "id": "calendar-day-labels-" + this.uid,
      "class": "calendar-day-labels",
      "styles": {"height": this.options.labelSize}
    }).injectInside(this.days);
    this.daysContainer = new Element("div", {
      "id": "calendar-days-container-" + this.uid,
      "class": "calendar-days-container"
    }).injectAfter(this.dayLabels);
    this.paintMonth(this.username);
	//this.paintMonthWithData(this.username);
  },
  paintMonth: function(username) {
    var opacity = this.main.effect("opacity", {duration: 500, transition: Fx.Transitions.Quad.easeInOut});
    var action = function() {
      var daysHtml = "", weeksHtml = "", labelsHtml = "",
          monthTypes = ["last-month", "this-month", "next-month"],
          year = this.date.year,
          month = this.date.month,
          weeks = this.date.month.weeks;
      if(!this.monthPainted) {
        for(var i = 0; i < $DaysPerWeek; i++) {
          labelsHtml += "<div id=\"day-label-" + i + "\" class=\"day d-" + i + "\">" + Date.dayNames[i] + "</div>";
        }
        this.weeksLabel.innerHTML = "wk";
        this.dayLabels.innerHTML = labelsHtml;
        this.monthPainted = true;
      }
      this.monthLabel.innerHTML = "" +
        "<span class=\"labels\">" +
          "<a href=\"#\" id=\"month-view-" + this.uid + "\" >" + month.name + "</a> " +
          "<a href=\"#\" id=\"year-view-" + this.uid + "\" >" + year.year + "</a>" +
        "</span>"+
        " " +
        "<span class=\"controls\">" +
          "<a href=\"#\" id=\"previous-" + this.uid + "\">&lt;</a> " +
          "<a href=\"#\" id=\"current-" + this.uid + "\">&bull;</a> " +
          "<a href=\"#\" id=\"next-" + this.uid + "\">&gt;</a>" +
        "</span>";
      if(this.root.type === "app") {
        $mmS.fromId("month-view", this.uid).onclick = this.resetMonthSize.bindAsEventListener(this);
        $mmS.fromId("year-view", this.uid).onclick = this.toYearView.bindAsEventListener(this);
      } 
      $mmS.fromId("previous", this.uid).onclick = this.root.previousMonth.bindAsEventListener(this.root);
      $mmS.fromId("current", this.uid).onclick = this.root.currentMonth.bindAsEventListener(this.root);
      $mmS.fromId("next", this.uid).onclick = this.root.nextMonth.bindAsEventListener(this.root);
	  
	 
      
     
	  //loop thru weeks
      for(var i = 0; i < weeks.length; i++) {
        var week = weeks[i], days = week.days;
        weeksHtml += "<div id=\"week-label-" + week.monthWeek + "\" class=\"week w-" + week.monthWeek + "\">" + week.name + "</div>";
        daysHtml += "<div id=\"week-" + week.monthWeek + "\" class=\"week w-" + week.monthWeek + "\">";
        
        
		//loop thru days in week
        for(var j = 0; j < days.length; j += 1) {
          var day = days[j], classes = "day d-" + day.weekDay + " " + monthTypes[1 + day.date.getMonth() - month.month];
          daysHtml += ""+
          "<div id=\"day-" + $mmC.toId( day.weekDay, week.monthWeek ) + "\" class=\"" + classes + "\">" +
            "<div class=\"inner-day\">"+
              "<div class=\"day-label\">" +
			  "<a id=\"day-max-" + $mmC.toId( day.weekDay, week.monthWeek ) + "\" class=\"maximize\"><img src=\"/content/images/calendar/icon_maximize.png\" class=\"maximizeicon\" /></a>" +  
			  "<a id=\"day-close-" + $mmC.toId( day.weekDay, week.monthWeek ) + "\" class=\"close\"><img src=\"/content/images/calendar/icon_minus.gif\" class=\"closeicon\" /></a>" + day.day + "</div>" +
              "<div class=\"day-content\">"+
              "</div>"+
            "</div>" +
          "</div>";
        }
        daysHtml += "</div>";
      }
      this.weeksContainer.innerHTML = weeksHtml;
      this.daysContainer.innerHTML = daysHtml;
      this.view = "month";
      this.resizeMonth();
    }.delay(500, this);
    opacity.start(1, 0).chain(function() {this.start(0, 1);});
  },
  resizeMonth: function() {
    var margin = this.options.margin, border = this.options.border.toInt(),
        wrapperWidth = this.size.width - margin[0], wrapperHeight = this.size.height - margin[1],
        mainWidth = wrapperWidth, mainHeight = wrapperHeight - this.options.headerHeight,
        tempWidth = mainWidth - border - this.options.labelSize, tempHeight = mainHeight - border - this.options.labelSize;
    this.containerWidth = tempWidth - (tempWidth % $DaysPerWeek);
    this.containerHeight = tempHeight - (tempHeight % this.date.month.weeks.length);
    this.dayWidth = Math.floor(this.containerWidth / $DaysPerWeek);
    this.weekHeight = Math.floor(this.containerHeight  / this.date.month.weeks.length);
    // Set elements dimensions
    this.wrapper.setStyles({"width": wrapperWidth, "height": wrapperHeight});
    this.header.setStyle("width", wrapperWidth);
    this.main.setStyles({"width": mainWidth, "height": mainHeight});
    this.weeksContainer.setStyle("height", this.containerHeight);
    this.days.setStyles({"width": this.containerWidth, "height": mainHeight});
    this.dayLabels.setStyle("width", this.containerWidth);
    this.daysContainer.setStyles({"width": this.containerWidth, "height": this.containerHeight});
    this.resizeDays();
    this.resizeWeeks();
  },
  resizeDays: function() {
    var labels = $$("#" + this.dayLabels.id + " .day"),
        days = $$("#" + this.daysContainer.id + " .day"),
        dayWidth = this.dayWidth,
        dayHeight = this.weekHeight,
        border = this.options.border.toInt();
    labels.each(function(label, index) {
      label.style.width = dayWidth - border + "px";
      label.style.height = this.options.labelSize - border + "px";
      label.style.left = index * dayWidth + "px";
    }.bind(this));
    days.each(function(day, index) {
      var position = $mmC.from(day);
	  
	  //old
      //day.onclick = function(e, day) {
      //  if(this.root && this.root.fireEvent) this.root.fireEvent("onDayClick", [day]);
      //  e.stopPropagation();
      //}.bindAsEventListener(this, [day]);
	  
	  //new
	  var dayMaximizeButton = $("day-max-" + $mmS.toId(day.id));
	  dayMaximizeButton.onclick = function(e, day) {
        if(this.root && this.root.fireEvent) this.root.fireEvent("onDayClick", [day]);
        e.stopPropagation();
      }.bindAsEventListener(this, [day]);
	  
      day.style.width = dayWidth - border + "px";
      day.style.left = (position[0] * dayWidth) + "px";
    }.bind(this));
  },
  resizeWeeks: function() {
    var weeks = $$("#" + this.weeksContainer.id + " .week"),
        days = $$("#" + this.daysContainer.id + " .week"),
        dayHeight = this.weekHeight,
        border = this.options.border;
    weeks.each(function(week, index) {
      week.onclick = function(e, week) {
        if(this.root && this.root.fireEvent) this.root.fireEvent("onWeekClick", [week]);
        e.stopPropagation();
      }.bindAsEventListener(this, [week]);
      week.style.width = this.options.labelSize - border + "px";
      week.style.height = dayHeight - border + "px";
      week.style.lineHeight = dayHeight + "px";
      week.style.top = index * dayHeight + "px";
    }.bind(this));
    days.each(function(day, index) {
      day.style.height = dayHeight - border + "px";
      day.style.top = index * dayHeight + "px";
    }.bind(this));
  },
  toYearView: function() {
    if(this.view === "year") {this.toMonthView(); return false;}
    else this.view = "year";
    var newWidth = Math.floor(this.size.width / 4),
        newHeight = Math.floor(this.size.height / 3);
    if($defined(this.root.resize)) {
      this.wrapper.addClass = "mini";
      this.root.resize.fromTo(newWidth, newHeight);
      var move = new Fx.Styles(this.wrapper, {duration: 500});
      move.start({"left": (window.getWidth() - newWidth) / 2, "top": (window.getHeight() - newHeight) / 2});
      //this.root.newMiniMooMonth(new Date(2008, 4, 20), newWidth, newHeight);
    } else {
      //this.size.set(newWidth, newHeight);
    }
    var afterResize = function() {
      this.wrapper.onclick = function(e) {
        e.stopPropagation();
        this.toMonthView();
      }.bindAsEventListener(this);
    };
    afterResize.delay(500, this);
  },
  toMonthView: function() {
    if(this.view !== "year") {return false;}
    else this.view = "month";
    if($defined(this.root.resize)) {
      this.wrapper.removeClass = "mini";
      this.root.resize.toFull();
      var move = new Fx.Styles(this.wrapper, {duration: 500});
      move.start({"left": 0, "top": 0});
    } else {
      //this.size.set(newWidth, newHeight);
    }
    this.wrapper.onclick = null;
  },
  // CHANGE el TO week, OR USE A this.selected
  toWeekView: function(el) {
    this.resetExpandedWeek();
    this.expandedWeek = el;
    this.zoomWeek(el);
  },
  // CHANGE el TO day, OR USE A this.selected
  toDayView: function(el) {
    this.resetExpandedDay();
    this.expandedDay = el;
    if(this.view === "day" || this.view === "week") this.fullDay(el);
    else this.zoomDay(el);
  },
  onDayClick: function(el) {
    var delay = 0;
    if(this.view === "year") {this.toMonthView(); delay = 600;}
    if(this.expandedDay !== el) {
      this.toDayView.delay(delay, this, [el]);
    } else {
      if(this.view !== "day") this.fullDay.delay(delay, this, [el]);
    }
  },
  onWeekClick: function(el) {
    var delay = 0;
    if(this.view === "year") {this.toMonthView(); var delay = 600;}
    if(this.expandedWeek !== el) {
      this.toWeekView.delay(delay, this, [el]);
    } else {
      this.resetMonthSize();
    }
  },
  resetExpandedDay: function() {
    if(!$defined(this.expandedDay)) return false;
    var el = this.expandedDay,
        dayDW = $mmC.from(el),
        day = this.date.month.weeks[ dayDW[1] ].days[ dayDW[0] ],
        close = $("day-close-" + $mmS.toId(el.id));
    el.removeClass("expanded");
    close.style.display = "none";
    this.expandedDay = null;
  },
  resetExpandedWeek: function() {
    if(!$defined(this.expandedWeek)) return false;
    this.expandedWeek = null;
  },
  resetMonthSize: function() {
    if(this.view === "year") {this.toMonthView(); return false;}
    else if(this.view === "month") return false;
    if(this.expandedDay) this.resetExpandedDay();
    else if(this.expandedWeek) this.resetExpandedWeek();
    this.view = "month";
    var rows = this.date.month.weeks.length, border = this.options.border.toInt(),
        effectsOptions = {duration: 500, transition: Fx.Transitions.Sine.easeOut},
        weeks = [], weeksEffects = [],
        days = [], daysEffects = [];
    for(var i = 0; i < this.date.month.weeks.length; i++) {
      weeksEffects[i] = new Fx.Elements($$("#" + this.wrapper.id + " .w-" + i), effectsOptions);
      weeks[i] = {"height": this.weekHeight - border, "top": this.weekHeight * i};
    }
    for(var i = 0; i < $DaysPerWeek; i++ ) {
      daysEffects[i] = new Fx.Elements($$("#" + this.wrapper.id + " .d-" + i), effectsOptions);
      days[i] = {"width": this.dayWidth - border, "left": this.dayWidth * i};
    }
    $mmT.forEach(weeksEffects, weeks);
    $mmT.forEach(daysEffects, days);
  },
  zoomDay: function(el) {
    if(this.expandedWeek) this.resetExpandedWeek();
    this.view = "zoom";
    var dayDW = $mmC.from(el),
        day = this.date.month.weeks[ dayDW[1] ].days[ dayDW[0] ],
        dayClasses = el.className,
        dayClose = $("day-close-" + $mmS.toId(el.id)),
        rows = this.date.month.weeks.length,
        cols = $DaysPerWeek,
        border = this.options.border.toInt(),
        widthNormal = this.dayWidth,
        widthSmall = Math.floor(widthNormal * (cols - 2) / (cols - 1)),
        widthLarge = Math.floor(widthNormal * 2),
        heightNormal = this.weekHeight,
        heightSmall = Math.floor(heightNormal * (rows - 2) / (rows - 1)),
        heightLarge = Math.floor(heightNormal * 2),
        weeks = [], weeksEffects = [],
        days = [], daysEffects = [],
        effectsOptions = {duration: 500, transition: Fx.Transitions.Sine.easeOut};
    el.addClass("expanded");
    dayClose.style.display = "block";
    dayClose.onclick = function(e) {
      this.resetMonthSize();
      e.stopPropagation();
    }.bindAsEventListener(this);
    for(var i = 0; i < rows; i++ ) {;
      weeksEffects[i] = new Fx.Elements($$("#" + this.wrapper.id + " .w-" + i), effectsOptions);
      if(i < day.week.monthWeek) weeks[i] = {"height": heightSmall - border, "top": heightSmall * i};
      else if (i > day.week.monthWeek) weeks[i] = {"height": heightSmall - border, "top": heightLarge + heightSmall * (i - 1)};
      else weeks[i] = {"height": heightLarge - border, "top": heightSmall * i};
    }
    for(var i = 0; i < cols; i++ ) {
      daysEffects[i] = new Fx.Elements($$("#" + this.wrapper.id + " .d-" + i), effectsOptions);
      if(i < day.weekDay) days[i] = {"width": widthSmall - border, "left": widthSmall * i};
      else if (i > day.weekDay) days[i] = {"width": widthSmall - border, "left": widthLarge + widthSmall * (i - 1)};
      else days[i] = {"width": widthLarge - border, "left": widthSmall * i};
    }
    $mmT.forEach(weeksEffects, weeks);
    $mmT.forEach(daysEffects, days);
  },
  zoomWeek: function(el) {
    if(this.expandedDay) this.resetExpandedDay();
    this.view = "week";
    var week = $mmS.toId(el),
        rows = this.date.month.weeks.length,
        cols = $DaysPerWeek,
        border = this.options.border.toInt(),
        widthNormal = this.dayWidth,
        heightNormal = this.weekHeight,
        heightSmall = 20,
        heightLarge = this.daysContainer.style.height.toInt() - (heightSmall * (rows - 1)),
        days = [],
        weeks = [],
        tempWeeks = [],
        effectsOptions = {duration: 500, transition: Fx.Transitions.Sine.easeOut},
        daysEffects = [];
        weeksEffects = [];
    for(var i = 0; i < rows; i++ ) {;
      weeksEffects[i] = new Fx.Elements($$("#" + this.wrapper.id + " .w-" + i), effectsOptions);
      if(i < week) weeks[i] = {"height": heightSmall - border, "top": heightSmall * i};
      else if (i > week) weeks[i] = {"height": heightSmall- border, "top": heightLarge + heightSmall * (i - 1)};
      else weeks[i] = {"height": heightLarge - border, "top": heightSmall * i};
    }
    for(var i = 0; i < cols; i++ ) {
      daysEffects[i] = new Fx.Elements($$("#" + this.wrapper.id + " .d-" + i), effectsOptions);
      days[i] = {"width": widthNormal - border, "left": widthNormal * i};
    }
    $mmT.forEach(weeksEffects, weeks);
    $mmT.forEach(daysEffects, days);
  },
  fullDay: function(el) {
    if(this.expandedWeek) this.resetExpandedWeek();
    this.view = "day";
    var dayDW = $mmC.from(el),
        day = this.date.month.weeks[ dayDW[1] ].days[ dayDW[0] ],
        dayClasses = el.className,
        dayClose = $("day-close-" + $mmS.toId(el.id)),
        rows = this.date.month.weeks.length,
        cols = $DaysPerWeek,
        border = this.options.border.toInt(),
        widthNormal = this.dayWidth,
        widthSmall = 20,
        widthLarge = this.daysContainer.style.width.toInt() - (widthSmall * (cols - 1)),
        heightNormal = this.weekHeight,
        heightSmall = 20,
        heightLarge = this.daysContainer.style.height.toInt() - (heightSmall * (rows - 1)),
        weeks = [], weeksEffects = [],
        days = [], daysEffects = [],
        effectsOptions = {duration: 500, transition: Fx.Transitions.Sine.easeOut};
    el.addClass("expanded");
    dayClose.style.display = "block";
    dayClose.onclick = function(e) {
      this.resetMonthSize();
      e.stopPropagation();
    }.bindAsEventListener(this);
    for(var i = 0; i < rows; i++ ) {;
      weeksEffects[i] = new Fx.Elements($$("#" + this.wrapper.id + " .w-" + i), effectsOptions);
      if(i < day.week.monthWeek) weeks[i] = {"height": heightSmall - border, "top": heightSmall * i};
      else if (i > day.week.monthWeek) weeks[i] = {"height": heightSmall - border, "top": heightLarge + heightSmall * (i - 1)};
      else weeks[i] = {"height": heightLarge - border, "top": heightSmall * i};
    }
    for(var i = 0; i < cols; i++ ) {
      daysEffects[i] = new Fx.Elements($$("#" + this.wrapper.id + " .d-" + i), effectsOptions);
      if(i < day.weekDay) days[i] = {"width": widthSmall - border, "left": widthSmall * i};
      else if (i > day.weekDay) days[i] = {"width": widthSmall - border, "left": widthLarge + widthSmall * (i - 1)};
      else days[i] = {"width": widthLarge - border, "left": widthSmall * i};
    }
    $mmT.forEach(weeksEffects, weeks);
    $mmT.forEach(daysEffects, days);
  }
});

/*
Section: MooMonths (Array)
  All initialized MooMonths get added to an array called MooMonths.
*/

var MooMonths = [];

/*
Section: MooMonth.DefaultOptions
  Object with the default MooMonth options.
*/

MooMonth.DefaultOptions = {
  margin: [24, 16],
  border: 1,
  headerHeight: 45,
  labelSize: 20
};

/*
Class: MooMonth.Base
*/

MooMonth.Base = new Class({
  options: MooMonth.DefaultOptions,
  //(el, date, *options)
  initialize: function(el, date, options) {
    this.type = $pick(this.type, "base");
    this.uid = MooMonths.length;
    MooMonths.push(this);
    if(options) this.setOptions(options);
    this.date = new MooMonth.Date($pick(date, ""), this);
    this.today = $today;
    this.element = $(el);


    this.element.className = "calendar " + this.type;
  },

  currentMonth: function() {
    this.date.set(this.today);
  },
  nextMonth: function() {
    this.date.set(this.date.date.getNextMonth());
  },
  previousMonth: function() {
    this.date.set(this.date.date.getLastMonth());
  }
});
MooMonth.Base.implement(new Options, new Events);

/*
Class: MooMonth.App
*/

MooMonth.App = MooMonth.Base.extend({
  options: {
    calendar: MooMonth.DefaultOptions,
    app: {}
  },
  initialize: function() {
    this.type = "app";
    this.parent.apply(this, arguments);
    this.session = new MooMonth.Session();
    this.size = new MooMonth.Size(this);
    this.resize = new MooMonth.Resize(this);
    this.calendar = new MooMonth.Element(this);
    this.miniMooMonths = [];
    this.addEvent("onDateSet", this.onDateSet.bind(this));
    this.addEvent("onSizeSet", this.calendar.resizeMonth.bind(this.calendar));
    this.addEvent("onDayClick", this.calendar.onDayClick.bind(this.calendar));
    this.addEvent("onWeekClick", this.calendar.onWeekClick.bind(this.calendar));
  },
  onDateSet: function() {
    this.calendar.paintMonth();
  },
  newMiniMooMonth: function(date, width, height) {
    var index = this.miniMooMonths.length;
        id = "calendar-" + this.uid + "-" + index;
    this.element.adopt(new Element("div", {id: id}));
    this.miniMooMonths.push(new MooMonth.Mini($(id), date, width, height, this.options.calendar));
    return this.miniMooMonths[index];
  }
});

/*
 Class: EnduroMonth
*/
EnduroMonth = MooMonth.Base.extend({
initialize: function(el, date, options, username, webservice, planningtypeid, calendartype, trainingtemplateid){
   this.type = $pick(this.type, "enduromonth");
   
   this.parent.apply(this,arguments);
   this.username = username;
   this.webservice = webservice;
   this.planningtypeid = planningtypeid;
   this.calendartype = calendartype;
   this.trainingtemplateid = trainingtemplateid;
   this.session = new MooMonth.Session();
   this.size = new MooMonth.Size(this);
   this.resize = new MooMonth.Resize(this);
   this.calendar = new MooMonth.Element(this);
   
   window.addEvent("domready",this.populateData.bind(this));
   this.miniMooMonths = [];
   this.addEvent("onDateSet", this.onDateSet.bind(this));
   this.addEvent("populateData", this.populateData.bind(this));
   this.addEvent("onSizeSet", this.calendar.resizeMonth.bind(this.calendar));
   this.addEvent("onDayClick", this.calendar.onDayClick.bind(this.calendar));
   this.addEvent("onWeekClick", this.calendar.onWeekClick.bind(this.calendar));
 },
 onDateSet: function() {
	this.calendar.paintMonth(this.username);
 },
 
 populateData: function() {
    
     
	 
	  var username = this.username,
	      year = this.date.year,
          month = this.date.month,
          weeks = this.date.month.weeks;
          
      var planningtypeid = this.planningtypeid;
	  var calendartype = this.calendartype;
	  var trainingtemplateid = this.trainingtemplateid;
      
      
	  
	  //var EnduroDayInfoByUserAndDateUrl = 'http://localhost:4816/TrainingSession/EnduroDayInfoByUserAndDate.rails'; 
	  var EnduroDayInfoByUserAndDateUrl = this.webservice;
	  var debugdate = this.datestring(weeks[0].date,'%N/%D/%Y');
	  
		
	  var startdate = this.datestring(weeks[0].date,'%N/%D/%Y');
	  var j = weeks.length-1;
	  //var enddate = this.addDays(weeks[j].date,6);
	  var enddate = this.datestring(this.addDays(weeks[j].date,6),'%N/%D/%Y');
	  
	 //MOOTOOLS ONLY USAGE
	 //Mootools format to check if DOM is Ready, then Get A Month of Training Data via Ajax call to WebService, and update DOM with Data
     
     
     
     
          
     //IE 7 does not like the mootools 1.1 function 'domready'
     //so for IE 7 compatibility need to use 'load'
     //consider detecting browser type and adding if stmt, use 'load' for IE
     //and 'domready' for non-IE
     
  //   window.addEvent('domready', function() {
	   
	 //mootools format for Ajax Call
	 
	
	var enduroDayInfo = new Ajax(EnduroDayInfoByUserAndDateUrl, 
						{method: 'post', headers: {'X-Request': 'JSON'},data: {'username': username,'startdate': startdate, 'enddate': enddate, 'planningtypeid': planningtypeid },onSuccess: processreturn}).request();
		

    
//	  });
	  
	  function processreturn(response) {		 
		 
		 var myJSON = eval(response);
		 //var planningtypeid = this.planningtypeid;
		 
		
		 
		//loop thru array of trainingsession objects
		 var trainingArray = myJSON;
		 var i=0;
		 for(var trnSession in trainingArray)
		 {
		   //Add New Link for New Training Session Here
		    		    
		    //create selector expression
		    if(typeof(trainingArray[i])=='object')
		    {
		     var selectorExpressionPart1 = 'div#week-' + trainingArray[i].WeekIndex;
				 
			 var weekElement = $E(selectorExpressionPart1);
				 
			 //mootools Selector Syntax
				 
			 var DayIndexFix = trainingArray[i].DayIndex;
			 var selectorExpressionPart2 = 'div#day-' + DayIndexFix + ' div[class=day-content]';
			
            var firstDayContentAppend = $(weekElement).getElement(selectorExpressionPart2);
			
	        //Commenting Out / Removing Add Training Session Link , from UI persp. this link probably is not needed here		
			//if(firstDayContentAppend)
			 //{
			//	
	        //     var mydataId = "'id=" + planningtypeid + "'";
	        //    
	        //     var clickScript="\"jQuery.ajax({url:'/RecordFitnessDataWizard/NewTrainingSessionStep-New.rails', success: function(data){jQuery(document).ready(function(){eval(data);});}, type:'POST', data:" + mydataId + "}); return false;\"";
	       //       
	       //      var htmlToAdd = "<p><span><a href='javascript:void(0);' onclick=" + clickScript + ">Add New Training Session</a></span></p>";		
	       //    appendHtml(htmlToAdd,firstDayContentAppend);   
	          //}	

            			
		   
		   
		  
		   
		 		
			 var j=0;
		     for(var wrkOut in trainingArray[i].WorkOutsCollection)
			 {
			   if(typeof(trainingArray[i].WorkOutsCollection[j])=='object')
			   {
			     
				 		 
				 if(firstDayContentAppend)
				 {
				 var workoutid=trainingArray[i].WorkOutsCollection[j].WorkOutId;
				 var trainingsessionid=trainingArray[i].TrainingSessionId;
				
				 var htmlToAppend='';
				 // Add To Template Link Logic
				 
                 if(calendartype=='Template') 
				 {
				    var mydataId = "'id=" + trainingsessionid + "'";
					
					var dataEntryId="data_entry" + DayIndexFix;
					var newClickScript = "function simple_function(e){ document.getElementById('" +  dataEntryId  + "').style.display='block'; if(!e) window.event.cancelBubble = true; else if(e.stopPropagation) e.stopPropagation(); } simple_function(event); return false;";
					var addtemplateId = 'addtemplatelink' + DayIndexFix;
				htmlToAppend = "<p><b><a id='" + addtemplateId + "' href='javascript:void(0);' onclick=\"" + newClickScript + "\"" + ">Click To Add To Template</a></b></p>";
					
					htmlToAppend += '<div id=' + '"data_entry' + DayIndexFix + '"' + 'class="data_entry" style="display:none;"><form id="trainsessionform">' + '<input type="hidden" name="trnsessionid" id="trnsessionid" value="' + trainingsessionid + '" />' + 
					'<input type="hidden" name="trainingtemplateid" id="trainingtemplateid" value="' + trainingtemplateid + '" />' +
					'<div class="whiteTheme"><span>Week Number</span><select id="trainingsession_WeekIndex" name="trainingsession.WeekIndex"> 	<option selected="selected" value="0">1</option><option value="1">2</option><option value="2">3</option><option value="3">4</option><option value="4">5</option><option value="5">6</option><option value="6">7</option><option value="7">8</option><option value="8">9</option><option value="9">10</option><option value="10">11</option><option value="11">12</option><option value="12">13</option><option value="13">14</option>	<option value="14">15</option><option value="15">16</option><option value="16">17</option><option value="17">18</option><option value="18">19</option><option value="19">20</option><option value="20">21</option><option value="21">22</option><option value="22">23</option><option value="23">24</option><option value="24">25</option><option value="25">26</option><option value="26">27</option>	<option value="27">28</option><option value="28">29</option><option value="29">30</option></select></div><div class="whiteTheme"><span>Day of Week</span><select id="trainingsession_DayIndex" name="trainingsession.DayIndex"><option selected="selected" value="0">Sunday</option><option value="1">Monday</option><option value="2">Tuesday</option><option value="3">Wednesday</option><option value="4">Thursday</option><option value="5">Friday</option><option value="6">Saturday</option></select></div></form>';
					
					var dataSelector = "#data_entry" + DayIndexFix + " form";
					var dataEntrySelector = "#data_entry" + DayIndexFix;
					var successElementId = 'data_entry_success' + DayIndexFix;
					var successSelector = "#data_entry_success" + DayIndexFix;
					
					
					
					var saveClickScriptPart1='jQuery(function(event){jQuery.ajax({url:"/TrainingSession/SaveTemplateData.rails", type:"POST", data:jQuery('  + '"' + dataSelector  + '"' + ').serialize(),success:function(data){jQuery(' + '"' + dataEntrySelector + '"' + ').css({"display":"none"});jQuery('  + '"' + successSelector + '"' + ').css({"display":"block"})}});  });';
					
					var saveClickScriptPart2 = 'function simplesave_function(e){ if(!e) window.event.cancelBubble = true; else if(e.stopPropagation) e.stopPropagation();' + saveClickScriptPart1 + ' } simplesave_function(event); return false;';
					
					
					
					var saveLinkId = 'savetemplatelink' + DayIndexFix;
					htmlToAppend += "<p><b><a id='" + saveLinkId + "' href='javascript:void(0);' onclick='" + saveClickScriptPart2 + "'>Save</a></b></p>";
					
					htmlToAppend +='</div>';
					htmlToAppend += '<div id=' + '"' + successElementId + '"' + 'class="data_entry_success" style="display:none;"><span>Save Complete</span></div>';
					appendHtml(htmlToAppend,firstDayContentAppend);
					
									   
				   
					  
					  
					}
				  
				 //}
				 
				 //New Html To Insert
				 htmlToAppend = '<p><b>Workout Info</b>' + '</p><p><span><b>WorkOut Type: </b></span><span>' + trainingArray[i].WorkOutsCollection[j].WorkOutType.Description + '</span></p><p><span><b>Description: </b></span><span>' + trainingArray[i].WorkOutsCollection[j].Description +'</span>';
	             //New Link
	             var newdataId = "'id=" + trainingsessionid + "'";
	             var onclickScript="\"jQuery.ajax({url:'/RecordFitnessDataWizard/NewWorkOutStep-New.rails', success: function(data){jQuery('#bodycontent').html(data);}, type:'POST', data:" + newdataId + "}); return false;\"";
	              
	             htmlToAppend += "<p><span><a href='javascript:void(0);' onclick=" + onclickScript + "> Add Workout</a></span></p>";			 
				 //Add Edit Link 
				 
				 
				 var dataId = "'id=" + workoutid + "'";
	            onclickScript="\"jQuery.ajax({url:'/WorkOut/Edit.rails', success: function(data){jQuery('#bodycontent').html(data);}, type:'POST', data:" + dataId + "}); return false;\"";			 
	                
	              htmlToAppend += "<p><span><a href='javascript:void(0);' onclick=" + onclickScript + ">Edit Workout</a></span></p>";	
	              htmlToAppend += "<p>&nbsp;</p>";			 
				 
				 appendHtml(htmlToAppend,firstDayContentAppend);
				 
				 }
				
				
			   }
			   j++;
			 }
		  
		   i++;
		   }
		 }
		 
		 		 //Add Data to DOM (Html)
		 function appendHtml(html,elementNode) {
		    var child = document.createElement('span');
			child.innerHTML = html;
			elementNode.appendChild(child);
		}
		 
		}
	
  },   
 datestring: function(date,string) {
	/* key for creating string
			%Y = 2008
			%y = 08
			%M = January
			%m = Jan
			%N = 01 (month)
			%n = 1 (month)
			%W = Monday
			%w = Mon
			%D = 05 (day of month)
			%d = 5 (day of month)
		*/
		var year=date.getFullYear();
		var month=date.getMonth();
		var realMonth=month+1;
        var fillMonth
		if (realMonth<10) {
			fillMonth = '0' + realMonth;
		} else {
			fillMonth = realMonth;
		}
		var months = ['January','February','March','April','May',
									'June','July','August','September',
									'October','November','December'];
		var monthName=months[month];
		var day=date.getDate();
        var fillDate
		if (day<10) {
			fillDate='0' + day;
		} else {
			fillDate=day;
		}
		var weekday=date.getDay();
		var weekdays = ['Sunday','Monday','Tuesday','Wednesday',
								'Thursday','Friday','Saturday'];
		var dayName=weekdays[weekday];
		
		
		//year
		string = string.replace(/%Y/g,year); // 2008
		string = string.replace(/%y/g,year.toString().slice(-2)); //08
		//month
		string = string.replace(/%M/g,monthName); //January
		string = string.replace(/%m/g,monthName.slice(0,3)); //Jan
		string = string.replace(/%N/g,fillMonth); // 01
		string = string.replace(/%n/g,realMonth); // 1
		//day of week
		string = string.replace(/%W/g,dayName); //Monday
		string = string.replace(/%w/g,dayName.slice(0,3)); //Mon
		//day of month
		string = string.replace(/%D/g,fillDate); //05
		string = string.replace(/%d/g,day); // 5
		return string;


},
 addDays: function(datepassedin,numofdays) {
 var msPerDay = 1000*60*60*24;
 var datePassedInMS = datepassedin.getTime();
 var addDaysTogether = (msPerDay * numofdays) + datePassedInMS;
 var addDaysDate = new Date(addDaysTogether);
 return addDaysDate;
},  		
 newMiniMooMonth: function(date, width, height) {
    var index = this.miniMooMonths.length;
        id = "calendar-" + this.uid + "-" + index;
    this.element.adopt(new Element("div", {id: id}));
    this.miniMooMonths.push(new MooMonth.Mini($(id), date, width, height, this.options.calendar));
    return this.miniMooMonths[index];
  }
    
});

EnduroEventMonth = MooMonth.Base.extend({
initialize: function(el, date, options, username, webservice){
this.type = $pick(this.type, "EnduroEventMonth");
this.parent.apply(this,arguments);
this.username = username;
this.webservice = webservice;
this.session = new MooMonth.Session();
this.size = new MooMonth.Size(this);
this.resize = new MooMonth.Resize(this);
this.calendar = new MooMonth.Element(this);
this.miniMooMonths = [];
window.addEvent("domready",this.populateData.bind(this));
this.addEvent("onDateSet", this.onDateSet.bind(this));
this.addEvent("populateData", this.populateData.bind(this));
this.addEvent("onSizeSet", this.calendar.resizeMonth.bind(this.calendar));
this.addEvent("onDayClick", this.calendar.onDayClick.bind(this.calendar));
this.addEvent("onWeekClick", this.calendar.onWeekClick.bind(this.calendar));
},
onDateSet: function() {
	this.calendar.paintMonth(this.username);
 },
 populateData: function() {
 
   
   
   var username = this.username,
	      year = this.date.year,
          month = this.date.month,
          weeks = this.date.month.weeks;
		  
   var EnduroEventByUserAndDateUrl = this.webservice;
	  var debugdate = datestring(weeks[0].date,'%N/%D/%Y');
	  
		
	  var startdate = datestring(weeks[0].date,'%N/%D/%Y');
	  var j = weeks.length-1;
	  //var enddate = this.addDays(weeks[j].date,6);
	  var enddate = datestring(addDays(weeks[j].date,6),'%N/%D/%Y');
	  
	  
	 
     
      var ieflag=false;
      //IE Flag - to tell WebService to pause so IE can render dom, if dom not fully rendered then Event Calendar can't be populated
      /*@cc_on @*/
      /*@if (@_win32) {
		   ieflag=true;
		 }
	     /*@end @*/
	  
	  
	  var enduroDayInfo = new Ajax(EnduroEventByUserAndDateUrl, {method: 'post', headers: {'X-Request': 'JSON'},data: {'username': username,'startdate': startdate, 'enddate': enddate, 'ieflag': ieflag }, onSuccess: processEvents}).request();
	  
	 
     
     function processEvents(response)
{
  
  var eventSubscriptionArray = eval(response);
    var i=0;
    for(var eventSubscription in eventSubscriptionArray)
	{
	  	if(typeof(eventSubscriptionArray[i]) == 'object')
		{
		  
		  if(eventSubscriptionArray[i].WeekIndex)
		   {var selectorExpressionPart1 = 'div#week-' + eventSubscriptionArray[i].WeekIndex;
		   
			var topDiv = $E('#EnduroCalendar');
			
			var wrapperDiv = $E('div#calendar-wrapper-0');
			
			var calendarMainDiv = $E('div#calendar-main-0');
			
			var mainDayDiv = $E('div#calendar-days-0',calendarMainDiv);
			
			var containerDayDiv = $E('div#calendar-days-container-0',mainDayDiv);
						
			var weekDiv = $E('div#day-labels-0');
			
			//initialize weekElement
			
			var weekElement = $E(selectorExpressionPart1);
			//new
			//#EnduroCalendar
			var weekElementId = 'week-' + eventSubscriptionArray[i].WeekIndex;
			var weekElementDebug = document.getElementById('week-' + eventSubscriptionArray[i].WeekIndex);
			
		   
		   //mootools Selector Syntax				 
			
			 //In IE weekElement is being evaluated as null
			 var DayIndexFix = eventSubscriptionArray[i].DayIndex;
			 var selectorExpressionPart2 = 'div#day-' + DayIndexFix + ' div[class=day-content]';
			 if(typeof(weekElement) != 'undefined')
			 { 
			   
			   //old
			   var firstDayContentAppend = $(weekElement).getElement(selectorExpressionPart2);
			   
			   
			   
			   
			   var clickScript="\"jQuery.ajax({url:'/Event/List.rails', success: function(data){jQuery('#bodycontent').html(data);}, type:'POST'}); return false;\"";
	              
	             var htmlToAdd = "<p><span><a href='javascript:void(0);' onclick=" + clickScript + ">Add New Event</a></span></p>";		
	             appendHtml(htmlToAdd,firstDayContentAppend);   
			}
		  }
	         	 
			  
			  
			 if(typeof(eventSubscriptionArray[i].Event) == 'object')
			 {
				   var eventname = eventSubscriptionArray[i].Event.EventName;
				   var city = eventSubscriptionArray[i].Event.City;
				   var state = eventSubscriptionArray[i].Event.State;
				   var country = eventSubscriptionArray[i].Event.Country;
				   if(firstDayContentAppend)
				   {
				     var htmlToAppend = '<p><b>Event Info</b>' + '</p><p><span><b>Event Name: </b><span>' + eventname + '</span></p>' + '<p><span><b>Location: </b><span>' + city + '</span>';
					 
					 //check for US Location, else outside US locatin show country
					 if(state != '')
					 {
					    htmlToAppend += '<span>, ' + state + '</span></p>';
					 }
					 else
					 {
					   htmlToAppend += '<span>, ' + country + '</span></p>';
					 }
					 
					 appendHtml(htmlToAppend,firstDayContentAppend);
					 
			       }
			 }
				
			 i++;			 
		}
	}
   
   function appendHtml(html,elementNode) {
		    var child = document.createElement('span');
			child.innerHTML = html;
			elementNode.appendChild(child);
		}
}	 
       	
  }
 });





/*
Class: MooMonth.Mini
*/

MooMonth.Mini = MooMonth.Base.extend({
  options: MooMonth.DefaultOptions,
  initialize: function(el, date, width, height, options) {
    this.type = "mini";
    this.parent.apply(this, [el, date, options]);
    this.session = new MooMonth.Session();
    this.size = new MooMonth.Size(this, width, height);
    this.resize = new MooMonth.Resize(this);
    this.calendar = new MooMonth.Element(this);
    this.addEvent("onDateSet", this.onDateSet.bind(this));
    this.addEvent("onSizeSet", this.calendar.resizeMonth.bind(this.calendar));
    this.addEvent("onDayClick", this.calendar.onDayClick.bind(this.calendar));
    this.addEvent("onWeekClick", this.calendar.onWeekClick.bind(this.calendar));
  },
  onDateSet: function() {
    this.calendar.paintMonth();
  }
});

/*
Class: MooMonth.DatePicker
*/

MooMonth.DatePicker = MooMonth.Base.extend({});

function datestring(date,string) {
	/* key for creating string
			%Y = 2008
			%y = 08
			%M = January
			%m = Jan
			%N = 01 (month)
			%n = 1 (month)
			%W = Monday
			%w = Mon
			%D = 05 (day of month)
			%d = 5 (day of month)
		*/
		var year=date.getFullYear();
		var month=date.getMonth();
		var realMonth=month+1;
        var fillMonth
		if (realMonth<10) {
			fillMonth = '0' + realMonth;
		} else {
			fillMonth = realMonth;
		}
		var months = ['January','February','March','April','May',
									'June','July','August','September',
									'October','November','December'];
		var monthName=months[month];
		var day=date.getDate();
        var fillDate
		if (day<10) {
			fillDate='0' + day;
		} else {
			fillDate=day;
		}
		var weekday=date.getDay();
		var weekdays = ['Sunday','Monday','Tuesday','Wednesday',
								'Thursday','Friday','Saturday'];
		var dayName=weekdays[weekday];
		
		
		//year
		string = string.replace(/%Y/g,year); // 2008
		string = string.replace(/%y/g,year.toString().slice(-2)); //08
		//month
		string = string.replace(/%M/g,monthName); //January
		string = string.replace(/%m/g,monthName.slice(0,3)); //Jan
		string = string.replace(/%N/g,fillMonth); // 01
		string = string.replace(/%n/g,realMonth); // 1
		//day of week
		string = string.replace(/%W/g,dayName); //Monday
		string = string.replace(/%w/g,dayName.slice(0,3)); //Mon
		//day of month
		string = string.replace(/%D/g,fillDate); //05
		string = string.replace(/%d/g,day); // 5
		return string;


}
 function addDays(datepassedin,numofdays) {
 var msPerDay = 1000*60*60*24;
 var datePassedInMS = datepassedin.getTime();
 var addDaysTogether = (msPerDay * numofdays) + datePassedInMS;
 var addDaysDate = new Date(addDaysTogether);
 return addDaysDate;
}