/**
* jQuery calendarLite plugin
*/
; (function($) {
    var eventData;
	var postback = true;
	
    $.fn.calendarLite = function(options) {
        var opts = $.extend({}, $.fn.calendarLite.defaults, options);
        return this.each(function() {
            $this = $(this);
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
            $.fn.calendarLite.draw(o);
            $(this).addClass(o.calendarClass);
        });
    };

    $.fn.calendarLite.getHead = function(opts) {
        var _days = new Array;
        $('DayNames', eventData).find('*').each(function() {
            _days.push($(this).text());
        });
        var html = [];
        for (var i = 0; i < _days.length; i++) {
            html.push('<th>' + _days[i] + '</th>');
        }
        return html.join('');
    };

    $.fn.calendarLite.draw = function(opts) {
        var o = $.extend({}, this.defaults, opts);
        
        month = parseInt(o.month, 10);
        year = parseInt(o.year, 10);
		
		if(!o.asyn&&postback){
    	    month = parseInt(o.currentMonth-1, 10);
	        year = parseInt(o.currentYear, 10);
	        postback=false;
		}
		
        var today = new Date();
        var srcDate = new Date();
        if (!isNaN(year)) {
            srcDate.setDate(1);
            srcDate.setFullYear(year);
        }
        if (!isNaN(month)) {
            srcDate.setDate(1);
            srcDate.setMonth(month);
        }
        var curDate = srcDate.getDate();
        var curMonth = srcDate.getMonth();
        var curYear = srcDate.getFullYear();
        var dates = [];
        var dayCount = new Date(curYear, curMonth + 1, 0).getDate();

        for (var i = 1; i <= dayCount; i++) {
            var tmpDate = new Date(curYear, curMonth, i);
            if (tmpDate.getMonth() == curMonth && tmpDate.getFullYear() == curYear) {
                dates.push(tmpDate);
            }
        }
        
        eventData = _loadEventData(opts,curMonth,curYear);
        var _months = new Array;
        var _monthsLink = new Array;
        $('MounthNames', eventData).find('*').each(function() {
            _months.push($(this).text());
            _monthsLink.push($(this).attr("Url"));
        });

        var table = $('<table cellspacing="0" cellpadding="0" class="'+o.calendarTableClass+'"></table>');
        var str = '<tbody><tr class="' + o.dayHeaderStyle + '">' + this.getHead(o) + '</tr>', cl = '';
        var line = [];
        for (var j = 0; j < dates.length; j++) {
            var day = dates[j].getDay();
            var month = dates[j].getMonth();
            var year = dates[j].getFullYear();

            var date = dates[j].getDate();
            var rel = _formatLink(o.dateFormat, dates[j]);
            cl = ' class="'+o.dayStyle+'"';
            if (date == today.getDate() && curMonth == today.getMonth() && curYear == today.getFullYear()) {
                cl = ' class="'+o.selectedDayStyle+'"';
            } else if (day == 6 || day == 0) {
                cl = ' class="'+o.otherMonthDayStyle+'"';
            }
            var href = '#';
            if (o.linkFormat != null && o.linkFormat != undefined) {
                href = _formatLink(o.linkFormat, dates[j]);
            }
            line.push('<td' + cl + '><a href="' + href + '" rel="' + rel + '">' + date + '</a></td>');
            if (dates[j].getDay() == 0) {
                if (line.length < 7) {
                    var ln = line.length;
                    var pad = [];
                    for (var k = 0; k < (7 - ln); k++) {
                        pad.push('<td class="' + o.dayStyle + '">&nbsp;</td>');
                    }
                    line = pad.concat(line);
                }
                str += '<tr>' + line.join('') + '</tr>';
                line = [];
            } else if (j == (dates.length - 1)) {
                str += '<tr>' + line.join('') + '</tr>';
            }
        }
        str += '</tbody>';
        table.html(str);
        if (typeof o.onSelect == 'function') {
            table.find('a').click(function() {
                return o.onSelect($(this).attr('rel'));
            });
        }
        var toolTipContentStyle = function(title, link, d) {
            if (title.length == link.length) {
                var itemTemplate = '<li><a href="{0}">{1}</a></li>';
                var contentItems = "";
                for (var i = 0; i < title.length; i++) {
                    contentItems += itemTemplate.replace("{0}", link[i]).replace("{1}", title[i]);
                }
            }
            var contentTemplate = '<div class="tipContent"><span>{0}</span><ul>' + contentItems + '</ul></div>'
            contentTemplate = contentTemplate.replace("{0}",(d + "/" + curMonth + "/" + curYear))
            return contentTemplate;
        };
	        var elemTooltip = table.find('a');
	        $(elemTooltip).each(function() {
	            var _elem = this;
	            var _day = $(_elem).text();
	            var _title = new Array;
	            var _link = new Array;
	            var _dayLink = null;
	            $('Dates', eventData).find("Date").each(function() {
	                if (_day == $(this).attr("Day")) {
	                	_dayLink = $(this).attr("Url");
	                	$(this).find("Event").each(function(){
		                    _title.push($(this).find("title").text());
		                    _link.push($(this).find("link").text());	
	                	});
					}
	            });
	            if(_dayLink != null)
	            {
					$(_elem).attr("href", _dayLink);
					$(_elem).parent("td").addClass(o.eventDayStyle);

			        if(o.asyn)
			        {
						$(_elem).parent("td").qtip({
							content: toolTipContentStyle(_title, _link, _day),
							hide: { when: 'mouseout', fixed: true, delay: 500 },
							position: {
							   corner: {
							      target: 'topMiddle',
							      tooltip: 'bottomMiddle'
							   }
							},
							style: {
			                  border: {
			                     width: 1,
			                     radius: 5
			                  },
			                  padding: 2, 
			                  textAlign: 'left',
			                  tip: true, // Give it a speech bubble tip with automatic corner detection
			                  name: 'light' // Style it according to the preset 'cream' style
			               }
						});
					}
					/*
					$(_elem).parent("td").simpletip({
						content: toolTipContentStyle(_title, _link),
						fixed: true,
						position: 'top'
					});
					*/
	            }
	            else
	            {
					$(_elem).removeAttr("href");
	            }
	        });
        var y = '';
        if (o.showYear == true) {
            y = ' ' + curYear + ' ';
        }
        $this[0].innerHTML = '<span class="state" style="display:none;">'+curMonth +'.'+curYear+'</span><div class="'+o.navigatorStyle + '"><a href="#" class="'+o.nextStyle+'" style="float:right;">'+o.nextArrow+'</a><a href="#" class="'+o.prevStyle+'" style="float:left;">'+o.prevArrow+'</a><a href="'+_monthsLink[curMonth]+'" class="'+o.monthNameStyle+'">'+_months[curMonth]+y+'</a></div>';
        $this.append(table);
             //.find('.'+o.navigatorStyle).width($this.find('.'+o.cssClass).width());
        this.next($this.find('a.'+o.nextStyle), o);
        this.prev($this.find('a.'+o.prevStyle), o);
    };

    function _loadEventData(o,m,y) {
        var returnData;
        var pageURL = document.location.href;
		var variable = pageURL.split("/");
        var eventXMLSource = "http://" + variable[2] + "/" + variable[3] + o.eventXML;
        
        $.ajax({
            async: false,
            url: eventXMLSource,
            data: "mounth=" + (m + 1) + "&year=" + y,
            type: "GET",
            success: function(data) {
                returnData = $(data);
            },
            error: function(error){
            	alert(error.responseText + "- " + eventXMLSource);
            }
        });
        return returnData;
    }

    function _formatLink(format, objDate) {
        var date = objDate.getDate();
        var month = objDate.getMonth() + 1;
        var year = objDate.getFullYear();
        if (format.indexOf('{%dd}') != -1) {
            date = _formatNum(date);
        }
        if (format.indexOf('{%mm}') != -1) {
            month = _formatNum(month);
        }
        if (format.indexOf('{%yy}') != -1) {
            year = year.toString().slice(2);
        }
        var link = format.replace(/{%d(d)?}/, date).replace(/{%m(m)?}/, month).replace(/{%yy(yy)?}/, year);
        return link;
    };

    function _formatDate(format, objDate) {
        var date = objDate.getDate();
        var month = objDate.getMonth();
        var year = objDate.getFullYear();
        if (format.indexOf('{%dd}') != -1) {
            date = _formatNum(date);
        }
        if (format.indexOf('{%mm}') != -1) {
            month = _formatNum(month);
        }
        if (format.indexOf('{%yy}') != -1) {
            year = year.toString().slice(2);
        }
        month++;
        var link = format.replace(/{%d(d)?}/, date).replace(/{%m(m)?}/, month).replace(/{%yy(yy)?}/, year);
        return link;
    };

    $.fn.calendarLite.next = function(button, o) {
        this.change(button, 1, o);
    };

    $.fn.calendarLite.prev = function(button, o) {
       this.change(button, -1, o);
    };

    $.fn.calendarLite.change = function(button, monthDelta, o) {
        var opts = $.extend({}, $.fn.calendarLite.defaults, o);
        var _self = this;
        var parent = button.parent('.'+opts.navigatorStyle).parent();
        button.click(function() {
        	
            var state = _self.getState(parent);
            var d = new Date(state[1], state[0] + monthDelta, 1);
            opts.month = d.getMonth();
            opts.year = d.getFullYear();
            /*
        	if(!opts.asyn)
        	{
        		var months = $('MounthNames', eventData).children();
				var url = $(months[opts.month]).attr('Url');
				window.location.href = url;
        		return false;
        	}*/
            parent.calendarLite(opts);
            return false;
        });
    };

    /**
    * Get current calendar's state (month and year)
    */
    $.fn.calendarLite.getState = function(div) {
        var st = div.find('.state')[0].innerHTML.split('.');
        return [parseInt(st[0], 10), parseInt(st[1], 10)];
    };

    function _formatNum(num) {
        num = parseInt(num, 10);
        if (num < 10) {
            return '0' + num;
        }
        return num;
    };

    $.fn.calendarLite.defaults = {
        eventXML: null,
        asyn: true,
        currentMonth: null,
        currentYear: null,
        days: ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'],
        months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
                 'September', 'October', 'November', 'December'],
        /**
        * Link to be assigned for each link in cell:
        *   e.g.: http://simternet.com/events/{%dd}-{%mm}-{%yyyy}
        * 
        * Possible values:
        *   {%dd} - date with leading zero
        *   {%d}  - date without leading zero
        *   {%mm} - month with leading zero
        *   {%m}  - month without leading zero
        *   {%yy} - yar (two digits)
        *   {%yyyy}  - full year (for digits)
        */
        linkFormat: null,
        /**
        * Format for date in 'rel' attribute (onSelect callback function retrieves this value)
        * Formatting options are the same as for 'linkFormat' option
        * Default: mm.dd.yyyy ('{%dd}.{%mm}.{%yyyy}')
        */
        dateFormat: '{%dd}.{%mm}.{%yyyy}',
        /**
        * Callback function, fires when user click on the cell
        * Function retrives one parameter - date
        * (in format that has been assigned by 'dateFormat' option):
        */
        onSelect: null,
        /**
        * When set to true, full year is displaying in the calendar caption
        */
        showYear: false,
        /**
        * Prev/Next arrows (you can also use &larr; and &rarr;)
        */
        prevArrow: '&laquo;',
        prevStyle: 'prevStyle',
        nextArrow: '&raquo;',
        nextStyle: 'nextStyle',
        calendarClass: 'calendarClass',
        calendarTableClass: 'calendarTableClass',
        navigatorStyle: 'navigatorStyle',
        monthNameStyle: 'monthNameStyle',
        dayHeaderStyle: 'dayHeaderStyle',
        dayStyle: 'dayStyle',
        selectedDayStyle: 'selectedDayStyle',
        otherMonthDayStyle: 'otherMonthDayStyle',
        eventDayStyle: 'eventDayStyle'
    };
})(jQuery);