var obj;
var undoText = null;
var undoEl = null;

function get(url, next) {
  if (window.XMLHttpRequest) { 
    obj = new XMLHttpRequest();     // Firefox, Safari, ...
    obj.onreadystatechange = function(){
      if (obj.readyState == 4) {
        if (obj.status == 200) {
          undoText = null;
          undoEl = null;
          if ( next ) { eval(next + '()'); }
          else {
            hideOverlay();
            return;
          }
        } else {
          if ( undoEl != null ) {
            alert("There was an error editting the calendar.");
            undoEl.innerHTML = undoText;
            hideOverlay();
          }
          alert("There was a problem in the returned data:\n");
        }
      }
    };
    obj.open("GET", url, true);
    obj.send(null);
  } else if (window.ActiveXObject) {
    obj = new ActiveXObject("Microsoft.XMLHTTP");  // Internet Explorer
    obj.onreadystatechange = function(){
      if (obj.readyState == 4) {
        if (obj.status == 200) {
          eval(next + '()');
        } else {
          alert("There was a problem in the returned data:\n");
        }
      }
    };
    obj.open("GET", url, true);
    obj.send();
  } else {
    alert("Your browser does not support AJAX");
  }
}

function prevMonth(url) {
  displayOverlay();
  var current = document.getElementById("currentMonth").value;
  var calendar = document.getElementById("fpCal").value;
  var newMonth = prevMonthString(current);
  url = url + "?start=" + newMonth + "&cal=" + calendar;
  get(url, "changeMonth");
}

function nextMonth(url) {
  displayOverlay();
  var current = document.getElementById("currentMonth").value;
  var calendar = document.getElementById("fpCal").value;
  var newMonth = nextMonthString(current);
  url = url + "?start=" + newMonth + "&cal=" + calendar;
  get(url, "changeMonth");
}

function prevMonthString(oldMonth) {
  var newMonth;
  var dateParts = oldMonth.split("-");
  if ( parseInt(dateParts[1]) == 1 ) {
    newMonth = (parseInt(dateParts[0]) - 1) + "-12-01";
  } else {
    newMonth = parseInt(dateParts[1].replace(/0/, '')) - 1;
    newMonth = dateParts[0] + "-" + newMonth + "-01";
  }
  return newMonth;
}

function nextMonthString(oldMonth) {
  var newMonth;
  var dateParts = oldMonth.split("-");
  if ( parseInt(dateParts[1]) == 12 ) {
    newMonth = (parseInt(dateParts[0]) + 1) + "-1-01";
  } else {
    newMonth = dateParts[0] + "-" + (parseInt(dateParts[1]) + 1) + "-01";
  }
  return newMonth;
}

function changeMonth() {
  var result = obj.responseText;
  var days = result.split("||");

  //Set up the new month
  days[0] = days[0].replace(/^\s+|\s+$/g,"");
  document.getElementById("currentMonth").value = days[0];
  var dateParts = days[0].split("-");
  var d = new Date();
  d.setFullYear(parseInt(dateParts[0]), parseInt(dateParts[1]) - 1, parseInt(dateParts[2]));
  month = "<small>" + formatDate(d, 'NNN').toUpperCase() + "</small>";

  //Change the month that is display in the 
  var dateCells = getElementsByClass('myCalMonth', document.getElementById('myCal'));
  for ( var i = 0; i < dateCells.length; i++ ) {
    dateCells[i].innerHTML = month;
  }

  //Update the text in the date cells and toggle off any unneeded dates
  for ( var i = 1; i <= 31; i++ ) {
    if ( days[i] == 'OFF' ) {
      document.getElementById("fpCal_" + i).className = 'tableOff';
    } else {
      document.getElementById("fpCal_" + i).className = 'tableOn';
    }
    document.getElementById("fpCal_" + i + "_text").innerHTML = days[i];
  }

  //Change the buton text
  var prev = prevMonthString(days[0]);
  dateParts = prev.split("-");
  d.setFullYear(parseInt(dateParts[0]), parseInt(dateParts[1]) - 1, parseInt(dateParts[2]));
  document.getElementById("prevMonth").innerHTML = "&laquo; " + formatDate(d, 'MMM');

  var next = nextMonthString(days[0]);
  dateParts = next.split("-");
  d.setFullYear(parseInt(dateParts[0]), parseInt(dateParts[1]) - 1, parseInt(dateParts[2]));
  document.getElementById("nextMonth").innerHTML = formatDate(d, 'MMM') + " &raquo;";

  hideOverlay();

}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function editDay(url, el) {
  displayOverlay();
  undoEl = document.getElementById(el.id + "_text");
  undoText = undoEl.innerHTML;

  if ( undoText == '&nbsp;' ) { undoText = ''; }
  var text = prompt("Favorite Part?", undoText);
  if ( text == null || text == '' ) { return false; }
  document.getElementById(el.id + "_text").innerHTML = text;

  var editDate = el.id;
  var cur = document.getElementById('currentMonth').value;
  editDate = editDate.replace('fpCal_', '');
  editDate = cur.replace(/\d+$/, editDate);
  
  get(url + "?mode=edit&cal=" + document.getElementById("fpCal").value + "&date=" + editDate + "&text=" + escape(text));
}

function fixValue(value) {
  document.getElementById('currentMonth').value = value;
}

function displayOverlay() {
  Element.clonePosition('gOverlay', 'myCal');
  $('gOverlay').style.height = Element.getHeight('gOverlay') - 10 + 'px';
  Effect.Appear('gOverlay', {duration: 0.5, from: 0, to: 0.6});
}

function hideOverlay() {
  Effect.Fade('gOverlay', {duration: 0.5});
}
