var xmlHttp;
var requestCalURL;
var text="";
var icount =0;
var callength=0;

function startCalendar(){
	cl = new calendarLayout();
}

function calendarLayout() {
	var today = new Date();
	var m = today.getMonth() +1;
	var d = today.getDate();
	var y = today.getFullYear();
	this.currentStartDate =  m + "/" + d + "/" + y;
	this.nextStartDate = null;
	this.prevStartDate = null;
	this.init();	
}

calendarLayout.prototype.init = function () {
	var t = this;
	t.requestCalInfo(t);
};


calendarLayout.prototype.requestCalInfo = function(cal) {
	var t = cal;
	requestCalURL = location + "&sdate=" + t.currentStartDate;
	
		  
	xmlHttp = GetXmlHttpObject();
					
	if (xmlHttp.readyState != 0) {
		xmlHttp.abort();
	}
	
	xmlHttp.open('GET', requestCalURL, true);
	
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete"){
			var str = xmlHttp.responseText;
			if (str.length > 0) {
				var days = new Array();
				days = str.split(",");				
				t.createDayViews(days);
			}
		} 
	};
	xmlHttp.send(null);
};

calendarLayout.prototype.createDayViews = function(days) {
	var li = null;
	var a = null;
	var sleeping = true;
	function change(){
		sleeping = false;
	}
	
	for (var i = 0; i < 7; i++){
		var d = new Array(2);
		d = days[i].split("_");
		$j('#dayDate' + i).text(d[0]);
		var requestCalURL = location + "&dateview=" + d+"&i="+i;
		$j.ajax({
  		type: "GET",
  		url: requestCalURL,
  		dataType: "json",
		complete: function(xhr){
			callback(xhr.responseText);
		}	
	})
	
	function callback(status){
		//need to do this for Firefox weird character
		//status = status.slice(0, status.length - 1);
		var index = status.split("_")[0];
		var ul = document.getElementById("dayTask" + (index));
		ul.innerHTML = ""
		var exercises = new Array();
		var list = status.split("_")[1].split(",");
		for(var i=0; i<list.length; i++){
			var exercise = new Object();
			exercise.name = list[i].split(";")[1];
			exercise.link = list[i].split(";")[0]
			exercises.push(exercise);
		}
		
		for(var i=0; i<exercises.length; i++){
			var a = document.createElement("a");			
			a.setAttribute('href',exercises[i].link);
			a.appendChild(document.createTextNode(exercises[i].name));
			li = document.createElement("li");
			li.appendChild(a);
			ul.appendChild(li);
		}
	}
		
		if (i == 0) {
			var c = new Date(d[0]);
			var n = new Date(d[0]);
			var p = new Date(d[0]);
			
			n = n.addDays(7);
			p = p.addDays(-7);
			
			var m = c.getMonth() + 1;
			var d = c.addDays(-1).getDate();
			var y = c.getFullYear();
			var nm = n.getMonth() + 1;
			var nd = n.getDate();
			var ny = n.getFullYear();
			var pm = p.getMonth() + 1;
			var pd = p.getDate();
			var py = p.getFullYear();
			document.getElementById("currWeek").innerHTML = "Your Calendar Week - " + (c.SHORTMONTHNAMES[c.getMonth()]) + " " + d + " - " + (n.SHORTMONTHNAMES[n.getMonth()]) + " " + nd;	
			this.nextStartDate = nm + "/" + nd + "/" + ny;	
			this.prevStartDate = pm + "/" + pd + "/" + py;			
		}
	}	
};


calendarLayout.prototype.requestNext = function () {
	var t = this;
	t.currentStartDate = t.nextStartDate;
	t.requestCalInfo(t);
};

calendarLayout.prototype.requestPrevious = function () {
	var t = this;
	t.currentStartDate = t.prevStartDate;
	t.requestCalInfo(t);
};

function assignvalues(i)
{
//alert(i);	
}
//Override the Date Function


/* date.js - Custom Date methods
 * addDays
 * addYears
 * addMonths
 * addMonthsTrunc
 * copy
 * daysBetween
 * getCDay
 * getDayName
 * getDayOfYear
 * getCMonth
 * getMonthName
 * getWeekDays
 * addBizDays
 * lastDay
 * monthsBetween
 * yearsBetween
 * getAge
 */

Date.prototype.DAYNAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
Date.prototype.MONTHNAMES = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
Date.prototype.SHORTMONTHNAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
Date.prototype.msPERMIN = 1000 * 60;
Date.prototype.msPERDAY = 1000 * 60 * 60 * 24;

Date.prototype.addBizDays = function(d) {
    /* Adds the necessary number of days
     * to the date to include the required
     * weekdays.
     */
    var day = this.getDay();    //day of week number 0 through 6
    var wkEnd = 0;              //number of weekends needed
    var m = d % 5;              //number of weekdays for partial week

    if (d < 0) {
        wkEnd = Math.ceil(d/5); //Yields a negative number of weekends

        switch (day) {
        case 6:
            //If staring day is Sat. one less weekend needed
            if (m == 0 && wkEnd < 0) wkEnd++;
            break;
        case 0:
            if (m == 0) d++; //decrease - part of weekend
            else d--;        //increase - part of weekend
            break;
        default:
            if (m <= -day) wkEnd--; //add weekend if not enough days to cover
        }
    }
    else if (d > 0) {
        wkEnd = Math.floor(d/5);

        switch (day) {
        case 6:
            /* If staring day is Sat and
             * no partial week one less day needed
             * if partial week one more day needed
             */
            if (m == 0) d--;
            else d++;
            break;
        case 0:
            if (m == 0 && wkEnd > 0) wkEnd--;
            break;
        default:
            if (5 - day < m) wkEnd++;
        }
    }

    d += wkEnd * 2; //Add weekends to weekdays needed

    this.addDays(d);
};
Date.prototype.addDays = function(d) {
        /* Adds the number of days to the date */
        this.setDate( this.getDate() + d );
        return this;
    };
Date.prototype.addMonths = function(m) {
        /* Adds the number of months to date
         * If starting with a day that is
         * greater than the number of days
         * in the new month the new date is
         * in the next month
         */
        this.setMonth(this.getMonth() + m);
    };
Date.prototype.addMonthsTrunc = function(m) {
        /* Adds the number of months to date,
         * but unlike addMonths this method
         * truncates extra days at end of month
         */
         var d = this.getDate();
         this.setDate(1);
         this.setMonth(this.getMonth() + m);

         var l = this.lastday();
         this.setDate( (d < l?d:l) );
    };
Date.prototype.addYears = function(y) {
        /* Adds the number of years to date
         * If adding to 2/29 and result is not
         * a leap year the day is set to 28
         */
        var m = this.getMonth();
        this.setFullYear(this.getFullYear() + y);

        //Adjust for leap years
        var m2 = this.getMonth();
        if (m < m2) {
            this.addDays(this.getDate() * -1);
        }
    };
Date.prototype.copy = function () {
        /* Creates a copy of date by value
         * Normal assignment only creates
         * a reference to the date, whereas
         * this creates a new date object
         */
        return Date(this.getTime());
    };
Date.prototype.daysBetween = function(d) {
        /*Returns number of days between two dates
        * including the last day, but not the first.
        *
        * This is value can be added
        * to one date get the other date.
        */
        var rtrn = null;

        if (! d instanceof Date) {
            try {
                d = new Date(d);
            }
            catch (e) {
                d = null;
            }
        }

        if (d) {
            /* Save time values */
            var th = this.getHours();
            var tm = this.getMinutes();
            var ts = this.getSeconds();
            var tms = this.getMilliseconds();

            /*Set time to midnight */
            this.setHours(0, 0, 0, 0);

            /*get date value */
            var c = this.getTime();
            /* restore time */
            this.setHours(th, tm, ts, tms);

            /* Save time values */
            th = d.getHours();
            tm = d.getMinutes();
            ts = d.getSeconds();
            tms = d.getMilliseconds();

            /*Set time to midnight */
            d.setHours(0, 0, 0, 0);

            /*get date value */
            var n = d.getTime();

            /* restore time */
            d.setHours(th, tm, ts, tms);

            c = Math.floor(c/this.msPERDAY);
            n = Math.floor(n/this.msPERDAY);
            rtrn = n - c;
        }
        return rtrn;
    };
Date.prototype.getCDay = function() {
        //Returns first 3 letters in day name
        return this.DAYNAMES[this.getDay()].slice(0,3);
    };
Date.prototype.getDayName = function() {
        //Returns full name of day
        return this.DAYNAMES[this.getDay()];
    };
Date.prototype.getDayOfYear = function() {
        //Returns day of year 1 through 365 or 366
        var start = new Date(this.getFullYear(), 0, 0);
        return this.daysBetween(start) * -1;
    };
Date.prototype.getCMonth = function() {
        //Returns first 3 letters in month name
        return this.MONTHNAMES[this.getMonth()].slice(0, 3);
    }
Date.prototype.getMonthName = function() {
        //Returns full name of month
        return this.MONTHNAMES[this.getMonth()];
    };
Date.prototype.getWeekDays = function(d) {
        /*Returns number of weekdays between two dates
        * including the last day, but not the first,
        * if either is a weekday.
        *
        * This is the value that can be added
        * to one date to get the other date
        * (although because you can use dates
        * that are weekends, adding back,
        * which only returns weekdays, may
        * return a different date than original.
        */
        var wkEnds = 0, days = 0;
        var s = 0, e = 0;

        days = Math.abs(this.daysBetween(d));

        if (days) {
            wkEnds = Math.floor(days/7);

            s = (d < this) ? d.getDay() : this.getDay() ;
            e = (d < this) ? this.getDay() : d.getDay();

            if (s != 6 && s > e) wkEnds++;
            if (s != e && (s == 6 || e == 6) ) days--;

            days -= (wkEnds * 2);
        }
        return days;
    };
Date.prototype.lastday = function() {
        //returns number of days in month
        var d = new Date(this.getFullYear(), this.getMonth() + 1, 0);
        return d.getDate();
    };
Date.prototype.monthsBetween = function(d) {
        //returns months between dates
        var d1 = this.getFullYear() * 12 + this.getMonth() + 1;
        var d2 = d.getFullYear() * 12 + d.getMonth() + 1;
        return d2 - d1;
    };
Date.prototype.yearsBetween = function(d) {
        //returns years and fraction between dates
        var months = this.monthsBetween(d);
        var years = months/12;
        if (Number.prototype.toFixed)
            return (years%1) ? years.toFixed(2) : years.toFixed(0);
        else
            return (years%1) ? Math.round(years * 100)/100 : Math.round(years);
    };
Date.prototype.getAge = function() {
		var d = new Date();
		return (this.yearsBetween(d));
	};
/* Add later builtinmethod to earlier browsers*/
if (!Date.prototype.toDateString) {
    Date.prototype.toDateString = function() {
            return this.toString().replace(/\d\d:\d\d:\d\d\s\w{2,3}\s/, '');
        };
}
if (!Date.prototype.toLocaleDateString) {
    Date.prototype.toLocaleDateString = function() {
            return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
        };
}


function highlightCalendar(){
	var tables = document.getElementsByTagName("table");
	var cal;
	for(var i=0; i<tables.length; i++){
		if(tables[i].className == "cal"){
			cal = tables[i];
		}
	}
	return cal;
}

function pickDay(){
	var cal = highlightCalendar();
	
	var calday = new Date();
	var today = calday.getDay();
	if((today >= 0) && (today <= 6)){
		
		for(var i=0; i<cal.rows.length; i++){
			var cells = cal.rows[i].cells;
			for(var j=0; j<cells.length; j++){
				if((today) == j)
				cells[j].className = "current";
				expandCell(this,cells);
			}
		}
	}
	clickCalendar(cal);
}

function clickCalendar(cal){
	for(var i=0; i<cal.rows.length; i++){
		var cells = cal.rows[i].cells;
		for(var j=0; j<cells.length; j++){
			cells[j].onclick = function(){
				clearCurrent(cells);
				this.className = "current";
				expandCell(this,cells);
				var cel=this;
			}
		}
	}
}

function clearCurrent(cells){
	for(var i=0; i<cells.length; i++){
		cells[i].className = "";
	}
}

function backToNormal(){
	var cal = highlightCalendar();
	for(var i=0; i<cal.rows.length; i++){
		var cells = cal.rows[i].cells;
		setCellsNormal(cells);
	}
}

function setCellsNormal(cells){
	for(var i=0; i<cells.length; i++){
		cells[i].style.width = "90px";
		cells[i].style.backgroundColor = "#fff9ea";
		var url = "/webresources/images/cal_" + i + ".gif";
		cells[i].getElementsByTagName("h1")[0].getElementsByTagName("img")[0].src = url;
		cells[i].getElementsByTagName("h5")[0].style.display = "block";
		cells[i].getElementsByTagName("ul")[0].style.display = "block";
	}
}

function expandCell(cell,cells){
	setCellsNormal(cells);
	
	for(var j=0; j<cells.length; j++){
		if(cells[j].className =="current"){
			cells[j].style.width = "510px";
				
		}
		else{
			cells[j].style.width = "20px";
			cells[j].style.backgroundColor = "#fff";
			var url = "/webresources/images/calver_" + j + ".gif";
			cells[j].getElementsByTagName("h1")[0].getElementsByTagName("img")[0].src = url;
			cells[j].getElementsByTagName("h5")[0].style.display = "none";
			cells[j].getElementsByTagName("ul")[0].style.display = "none";
		}
	}
}

function highlightCell(){
	
	var tables = document.getElementsByTagName("table");
	var cal;
	for(var i=0; i<tables.length; i++){
		if(tables[i].className == "cal"){
			cal = tables[i];
		}
	}
	
	var rows = cal.getElementsByTagName("tr");
	for(var j=0; j<rows.length; j++){
		var cells = rows[j].getElementsByTagName("td");
		for(var x=0; x<cells.length; x++){
		
			cells[x].onmouseover = function(){
				hoverCell(this);
			}
			cells[x].onmouseout = function(){
				outHover(this);
			}
		}
	}
	
	}
	
	function hoverCell(cell){
		var currDate = cell.getElementsByTagName("h5")[0];
		currDate.className = "hover";
		cell.className = "hover";
	}
	
	function outHover(cell){
		var currDate = cell.getElementsByTagName("h5")[0];
		currDate.className = "";
		cell.className = "";
	}
