String.prototype.repeat = function(num) {
	return new Array(num + 1).join(this);
}

cal = new Calendar(1);

function page_onload() {
	//updateStylesheet();
	cal.render(2009, 9);
	
	//doCalendar();
	
	if(typeof user_onload == 'function') { 
		user_onload(); 
	}
}

function updateStylesheet() {
	if (screen.width > 1024) {
		setStylesheet("high");
	} else {
		setStylesheet("low");
	}
}

function setStylesheet(cssname) {
	var i, link_tag;
	for (i = 0, link_tag = document.getElementsByTagName("link"); i < link_tag.length; i++) {
		if ((link_tag[i].rel.indexOf("stylesheet") != -1) && link_tag[i].title) {
			link_tag[i].disabled = true;
			if (link_tag[i].title == cssname) {
				link_tag[i].disabled = false;
			}
		}
	}
}

function Calendar(calendarId) {  
  //window.status = 'Initialising Calendar';
  // setting local variables
  curDate = new Date();
  this.id = calendarId;
  this.theYear = curDate.getFullYear();
  this.theMonth = curDate.getMonth();
  this.today = curDate.getDay(); 
    theFirst = new Date(this.theYear, this.theMonth, 1);
    var firstDayOfMonth = theFirst.getDay();
       
    this.dayOffset = firstDayOfMonth;
    if(this.dayOffset == 0) {
      this.dayOffset = 7;
    }

	this.months = new Array();
	this.months[0] = 'Gen';
	this.months[1] = 'Feb';
	this.months[2] = 'Mar';
	this.months[3] = 'Apr';
	this.months[4] = 'Mag';
	this.months[5] = 'Giu';
	this.months[6] = 'Lug';
	this.months[7] = 'Ago';
	this.months[8] = 'Set';
	this.months[9] = 'Ott';
	this.months[10] = 'Nov';
	this.months[11] = 'Dic';

	this.monthDays = new Array();
	this.monthDays[0] = 31;
	this.monthDays[1] = 28;
	this.monthDays[2] = 31;
	this.monthDays[3] = 30;
	this.monthDays[4] = 31;
	this.monthDays[5] = 30;
	this.monthDays[6] = 31;
	this.monthDays[7] = 31;
	this.monthDays[8] = 30;
	this.monthDays[9] = 31;
	this.monthDays[10] = 30;
	this.monthDays[11] = 31;

	this.weekDays = new Array();
	this.weekDays[0] = 'Dom';
	this.weekDays[1] = 'Lun';
	this.weekDays[2] = 'Mar';
	this.weekDays[3] = 'Mer';
	this.weekDays[4] = 'Gio';
	this.weekDays[5] = 'Ven';
	this.weekDays[6] = 'Sab';

	this.weekDaysOrder = new Array();
	this.weekDaysOrder[0] = 1;
	this.weekDaysOrder[1] = 2;
	this.weekDaysOrder[2] = 3;
	this.weekDaysOrder[3] = 4;
	this.weekDaysOrder[4] = 5;
	this.weekDaysOrder[5] = 6;
	this.weekDaysOrder[6] = 0;  
	
	//window.status = 'Local variables defined...';
	// methods definition
	
  this.writeCalendarDays = function() {
  
    theFirst = new Date(this.theYear, this.theMonth, 1);
    var firstDayOfMonth = theFirst.getDay();
       
    var theDayOffset = firstDayOfMonth;
    if(theDayOffset == 0) {
      theDayOffset = 7;
    }
    
    for(var x=0; x < this.monthDays[this.theMonth]; x++) {
      var dayCell = document.getElementById('cal_' + theDayOffset);
      var dayCellText = document.createTextNode(x+1);
      dayCell.appendChild(dayCellText);
      
      theDayOffset++;      
    }
  }
  
  this.setMonth = function (theMonth) {
    this.theMonth = theMonth;
  }
  
  this.setYear = function (theYear) {
    this.theYear = theYear;
  }
  
  this.getAppointments = function(theYear, theMonth, offset) {
    this.blockMonthScrolling(true);
  	var xmlhttp = false;
  	/* @cc_on @ */
  	/*
  	 * @if (@_jscript_version >= 5) // JScript gives us Conditional compilation,
  	 * we can cope with old IE versions. // and security blocked creation of the
  	 * objects. try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
  	 * try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) {
  	 * xmlhttp = false; } } @end @
  	 */
  
  	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
  		try {
  			xmlhttp = new XMLHttpRequest();
  		} catch (e) {
  			xmlhttp = false;
  		}
  	}
  	if (!xmlhttp && window.createRequest) {
  		try {
  			xmlhttp = window.createRequest();
  		} catch (e) {
  			xmlhttp = false;
  		}
  	}
  
  	var url = "http://www.fabrianorugby.local/appointment/get";
  
  	try {
  		xmlhttp.open("POST", url, true);
  	} catch (e) {
  		//alert(e.message);
  	}
  	xmlhttp.onreadystatechange = function() {
  		if (xmlhttp.readyState == 4) {
  			var appointments = eval('(' + xmlhttp.responseText + ')');
//  alert(xmlhttp.responseText);
  			var a = new Array();
  			for ( var x = 0; x < appointments.appointments.length; x++) {
  				appointmentDate = parseInt(appointments.appointments[x].start_date.substr(8, 2));
//alert(appointmentDate);
  				if(a[appointmentDate] == undefined) {
  					a[appointmentDate] = new Array();
  				}
  				a[appointmentDate].push(new Array(appointments.appointments[x].id_appointment, appointments.appointments[x].appointment_title));
  				//a[appointmentDate].push(appointments.appointments[x].id_appointment);
  				//alert(a[appointmentDate].length);
  			}

  			if(a.length > 0) {
      	  for (var x = 1; x <= 31; x++) {
    	      if(a[x]) {
               td_element = document.getElementById("cal_" + (x - 1 + offset));      
               if(td_element.innerHTML == '') {
            	   td_element = document.getElementById("cal_" + (x + 6 + offset));
               }
               var paddedx = x
               if(paddedx < 10) {
            	   paddedx = "0" + x; 
               }
               titleString = ":";
               for(var t=0; t<a[x].length; t++) {
                   titleString += a[x][t][1] + ":";
               }
               
               td_element.innerHTML = '<b><a title="' + titleString + '" href="/calendar/view/' + theYear + theMonth + paddedx + '">' + td_element.innerHTML + '</a></b>';
               //td_element.innerHTML = '<b><a title="' + a[x][1] + '" href="/calendar/view/' + theYear + theMonth + paddedx + '">' + td_element.innerHTML + '</a></b>';
            }
          }
        }  
        this.blockMonthScrolling(false);			
  		}
  	}
  	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  	xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  	xmlhttp.send('year=' + theYear + '&month=' + theMonth);
  }  
  
  this.blockMonthScrolling = function (block) {
      scroller1 = document.getElementById('prevMonthLink');
      scroller2 = document.getElementById('nextMonthLink');
      if(block) {        

      } else {

      }
  }
  
  this.render = function () {
    var cal_div = document.getElementById('calendar_div');
    if(cal_div.hasChildNodes) {
      for(var i = 0; i < cal_div.childNodes.length; i++) {
         cal_div.removeChild(cal_div.childNodes[i]);
      }
    }
    //alert("OK");
    theYear = this.theYear;
    theMonth = this.theMonth;
    offset = this.dayOffset;
    //window.status = 'Beginning Render...';
    // create calendar root element TABLE
    var calendarRoot = document.createElement('table');
    calendarRoot.setAttribute('id', this.id);
    calendarRoot.setAttribute('class', 'calendar');
    //window.status = 'Calendar Root defined...';
    
    // create calendar header row
    var headerRow = document.createElement('tr');
    var headerCell = document.createElement('th');
    var calendarTitle = document.createTextNode('Calendario ' + theYear);
    headerCell.appendChild(calendarTitle);
    headerCell.setAttribute('colspan', '7');
    headerRow.appendChild(headerCell);
    calendarRoot.appendChild(headerRow);
    //window.status = 'Header Row defined...';
    
    // create calendar Month Selection row
    var monthSelectionRow = document.createElement('tr');
    var previousMonthSelectorCell = document.createElement('th');
    var previousMonthSelectorCellLink = document.createElement('a');
    previousMonthSelectorCellLink.setAttribute('id', 'prevMonthLink');
    previousMonthSelectorCellLink.setAttribute('href', 'javascript:previousMonth("' + theYear + '", "' + theMonth + '")');
    var previousMonthSelectorText = document.createTextNode('<');
    previousMonthSelectorCellLink.appendChild(previousMonthSelectorText);
    previousMonthSelectorCell.appendChild(previousMonthSelectorCellLink);
    monthSelectionRow.appendChild(previousMonthSelectorCell);
    
    var monthTextCell = document.createElement('th');
    monthTextCell.setAttribute('colspan', '5');
    var monthText = document.createTextNode(this.months[theMonth]);
    monthTextCell.appendChild(monthText);
    monthSelectionRow.appendChild(monthTextCell);
    
    var nextMonthSelectorCell = document.createElement('th');
    var nextMonthSelectorCellLink = document.createElement('a');
    nextMonthSelectorCellLink.setAttribute('id', 'nextMonthLink');
    nextMonthSelectorCellLink.setAttribute('href', 'javascript:nextMonth("' + theYear + '", "' + theMonth + '")');
    var nextMonthSelectorText = document.createTextNode('>');
    nextMonthSelectorCellLink.appendChild(nextMonthSelectorText);
    nextMonthSelectorCell.appendChild(nextMonthSelectorCellLink);
    monthSelectionRow.appendChild(nextMonthSelectorCell); 
    calendarRoot.appendChild(monthSelectionRow);
    //window.status = 'Month Selector Row defined...';  
    
    // column headers
    var columnHeadersRow = document.createElement('tr');
    for(var x = 0; x<7; x++) {
      var dayCell = document.createElement('th');
      var dayCellText = document.createTextNode(this.weekDays[this.weekDaysOrder[x]]);
      dayCell.appendChild(dayCellText);
      columnHeadersRow.appendChild(dayCell);      
    }
    calendarRoot.appendChild(columnHeadersRow);
    //window.status = 'Column Headers defined...';
    
    // start rendering of calendar body 
    for(y = 0; y < 6; y++) {
      var calendarBodyRow = document.createElement('tr');
      for(x = 0; x < 7; x++) {
        var calendarBodyCell = document.createElement('td');
        calendarBodyCell.setAttribute('id', 'cal_' + parseInt((7 * y) + x + 1));
        calendarBodyRow.appendChild(calendarBodyCell);
      }
      calendarRoot.appendChild(calendarBodyRow);
    }
    //window.status = 'Calendar Body defined...';
    
    // append Calendar to the calendar_div
    document.getElementById('calendar_div').appendChild(calendarRoot);
    //window.status = 'Calendar added to root...';
    
    // write the days to the calendar
    //window.status = 'Preparing to write days...';
    
    this.writeCalendarDays();
    this.getAppointments(theYear, theMonth, offset);
  }  
  //window.status = 'Calendar definition loaded';
}

function previousMonth(theYear, theMonth) {
   theMonth = parseInt(theMonth, 10);
   if (theMonth == 0) {
	    cal.setMonth(11);
	    cal.setYear(theYear - 1);
   } else {
	    cal.setMonth(theMonth - 1);
   }
   cal.render();
}

function nextMonth(theYear, theMonth) {
   theMonth = parseInt(theMonth, 10);
   if (theMonth == 11) {
	    cal.setMonth(0);
	    cal.setYear(parseInt(theYear, 10) + 1);
   } else {
	    cal.setMonth(parseInt(theMonth, 10) + 1);
   }
   cal.render();
}

function formatInject(formatType, fieldName) {
	if(formatType == 'b' || formatType == 'i' || formatType == 'u') {
		newText = doPopup(formatType);
	} else if(formatType == 'http') {
		newText = doHTTPPopup();
	} else if(formatType == 'img') {
		newText = doImgPopup();
	}
	
	document.getElementById(fieldName).value += newText;
}

function doPopup(formatType) {
	var popupText = 'Inserire il testo';
	var formatText = prompt('Inserire il testo', popupText);
	
	var outText = '[' + formatType + ']' + formatText + '[/' + formatType + ']';
	if(formatText != undefined) {
		return outText;
	} else {
		return '';
	}
}

function doHTTPPopup() {
	var popupText = 'Inserire indirizzo';
	var address = prompt(popupText, popupText);
	
	popupText = 'Inserire nome link';
	var linkname = prompt(popupText, popupText);
	
	var outText = '[url=' + address + ']' + linkname + '[/url]';
	if(linkname != undefined && address != undefined) {
		return outText;
	} else {
		return '';
	}
}

function doImgPopup() {
	popupText = 'Inserire indirizzo immagine';
	address = prompt(popupText, popupText);
	
	formatText = '[img]' + address + '[/img]';
	if(address != undefined) {
		return formatText;
	} else {
		return '';
	}
}

function formatShowMore() {
	window.open('http://www.fabrianorugby.it/info/bbcode', 'bbcpopup', "height=350,width=350");
	bbcpopup.moveTo((screen.width - 350) / 2, (screen.height - 350) / 2);
}
