/*!
 * jQuery UI Character Count @VERSION
 *
 * Copyright (c) 2009 AUTHORS.txt (http://shellscape.org/juice/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 * Depends:
 * 	juice.js
 *	juice.prototype.js
 *  ui.core.js
 */
 

$(document).ready(function(){
  var date = new Date(),
    monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    dayLabels = ['S','M','T','W','T','F','S'],
    dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],   
	shortDayNames =  ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],   
    month = date.getMonth(),
    element = $('#cal').hide(),
    target = $('<ul/>').insertAfter(element).addClass('ui-widget juice-spectalendar'),

	animEnter = {backgroundColor: '#000', color:  '#000'},
	animLeave = {backgroundColor: '#FFF', color:  '#FFF'},
	animLiEnter = {backgroundColor:  '#FFF', color: '#FFF'},
	animLiLeave = {backgroundColor:  '#000', color:  '#000'};

 
  
  var header = $('<li class="juice-spectalendar-header"/>')
    .append('<a class="juice-spectalendar-nextyear" title="Next Year" data-dir="2"/>')
    .append('<a class="juice-spectalendar-nextmonth" title="Next Month" data-dir="1"/>')
    .append('<a class="juice-spectalendar-prevyear" title="Previous Year" data-dir="-2"/>')
    .append('<a class="juice-spectalendar-prevmonth" title="Previous Month" data-dir="-1"/>')
    .append('<h2 class="ui-state-default juice-spectalendar-monthname">' + monthNames[date.getMonth()] + ', ' + date.getFullYear() + '</h2>')
    .appendTo(target);
  
  
	
	newMonth = date.getMonth() + 1;
	newYear = date.getFullYear();
	newYearEnd = newYear;
	newMonthEnd = date.getMonth() + 2;
		if(newMonthEnd == 13) newMonthEnd = 1, newYearEnd = newYearEnd + 1;
		if(newMonth < 10) newMonth = "0" +  newMonth;
		if(newMonthEnd < 10) newMonthEnd = "0" +  newMonthEnd;
	requestFrom =  newYear + '-' + newMonth + '-' + '01';
	requestTo =  newYearEnd + '-' + newMonthEnd + '-' + '01';
  
  
	$("#calendar-loader").show();
	$("#cal").load("/calendar/events-visual-calendar-ajax/", {startdate: requestFrom, enddate: requestTo}, function(){			
		header.find('h2').html(monthNames[date.getMonth()] + ', ' + date.getFullYear());
	    target.find('li.juice-spectalendar-week').remove();
		renderDays(target, date);
		$("#calendar-loader").hide();
		$(".juice-spectalendar").css({opacity: 1});
	});
  
  
 
  header.find('a').click(function(){
    var dir = parseInt($(this).attr('data-dir')),
      newdate = date;
      
    if(dir == 2){
      date.setFullYear(date.getFullYear() + 1);
    }
    else if(dir == 1){
      date.setMonth(date.getMonth() + 1);
    }
    else if(dir == -1){
      date.setMonth(date.getMonth() - 1);
    }
    else if(dir == -2){
      date.setFullYear(date.getFullYear() - 1);
    }
	
	//2010-05-01
	
	newMonth = date.getMonth() + 1;
	newYear = date.getFullYear();
	newYearEnd = newYear;
	newMonthEnd = date.getMonth() + 2;
		if(newMonthEnd == 13) newMonthEnd = 1, newYearEnd = newYearEnd + 1;
		if(newMonth < 10) newMonth = "0" +  newMonth;
		if(newMonthEnd < 10) newMonthEnd = "0" +  newMonthEnd;
	requestFrom =  newYear + '-' + newMonth + '-' + '01';
	requestTo =  newYearEnd + '-' + newMonthEnd + '-' + '01';



	$("#calendar-loader").show();
	$(".juice-spectalendar").css({opacity: 0.5});

		$("#cal").load("/calendar/events-visual-calendar-ajax/", {startdate: requestFrom, enddate: requestTo}, function(){			
			header.find('h2').html(monthNames[date.getMonth()] + ', ' + date.getFullYear());
		    target.find('li.juice-spectalendar-week').remove();
			renderDays(target, date);
			$("#calendar-loader").hide();
			$(".juice-spectalendar").css({opacity: 1});
		});
  });
  

 
  $('.juice-spectalendar-event').live('click', function(){ //click on a day with an event
    if($('.juice-spectalendar-dialog').length){
      return;
    }
 
    var e = $(this),
      bounds = e.bounds(),
      spanBounds = e.find('span').bounds(),
      widgetBounds = e.closest('.juice-spectalendar').bounds(),
      day = parseInt(e.find('p').html()),
      dayDate = new Date(date),
      endWidth = widgetBounds.width - 100,
      endHeight = widgetBounds.height - 100,      
      startCss = {
        width: spanBounds.inner.width,
        height: spanBounds.inner.height,
        left: bounds.left - widgetBounds.left,
        top: bounds.top - widgetBounds.top
      },
      endCss = {
        width: endWidth,
        height: endHeight,
        left: ((widgetBounds.width - endWidth) / 2),
        top: ((widgetBounds.height - endHeight) / 2)
      },
      dataItems = [];

    dayDate.setDate(day);
	
	clickedDayRel = $(this).attr('rel'); //rel="" of the day you clicked on
	
	//find the clicked on date in result html
    element.find('li').each(function(){
	
	if(clickedDayRel == $(this).attr('rel').substr(0,15)){ //match the clicked with existing
      var e = $(this),
        item = { date: e.attr('rel'), title: e.attr('title'), body: e.html(), special: e.attr('class')};
      if(!item.date || !item.title || !item.body || !item.date.length || !item.title.length || !item.body.length){
        return;
      }
	  
	
      dataItems.push(item);
	 }
    });
    
    var header = $('<div class="juice-spectalendar-header"/>')
      .append('<p>' + day + '</p>')
      .append('<p>' + dayDate.format('dddd MMMM d, yyyy') + '</p>'),
    
    close = $('<a class="ui-state-default juice-spectalendar-close" title="Close Events"><span class="ui-icon ui-icon-circle-close"></span></a>')
      .css({opacity: 0})
      .hover(function(){ $(this).toggleClass('ui-state-hover'); })
      .click(function(){
        close.fadeOut()
        events.fadeOut();
        dialog.find('q:eq(0)').slideDown().animate({opacity: 1});
        header.find('p:first').animate({marginTop: 0}, function(){
          dialog.animate(startCss, function(){
            e.animate({opacity: 1});
            dialog.fadeOut(function(){
              dialog.remove();
            });
          });
        });
      }),

    events = $('<div class="juice-spectalendar-events"/>').css({opacity: 0}),
    page = $('<div class="juice-spectalendar-page"/>').appendTo(events).css({width: endCss.width}),
    list = $('<ul/>');
    
    $.each(dataItems, function(i, item){
	
		if(item.special == "star") {
		    list.append('<li class="ui-widget-header starevent">' + (i + 1) + '. 	<img src="/images/icons/star.png" alt="star" /> ' + item.title + '</li>');
		
		} else {
		    list.append('<li class="ui-widget-header">' + (i + 1) + '. ' + item.title + '</li>');
		
		}
	
		
		
  
      events.append(page.clone().hide().append('<a class="juice-spectalendar-back">&laquo; back</a><h2>' + item.title + '</h2><span>' + item.body + '</span>'));
    });
    
    page.append(list);
    
    list.find('li')
      //.mouseenter(function(){ $(this).stop().animate(animLiEnter); })
      //.mouseleave(function(){ $(this).stop().animate(animLiLeave); })
      .click(function(){
				var e = $(this),
					thisPage = e.closest('.juice-spectalendar-page'),
					index = e.parent().children().index(this),
					nextPage = $('.juice-spectalendar-events .juice-spectalendar-page:eq(' + (index + 1) + ')');
					if(e.hasClass('starevent')) {
						currentPVal = $(nextPage).find('p:first').text().substring(0,300);
						$(nextPage).find('p').text(currentPVal + "...");
					}
					
		
			
				nextPage.show();
				thisPage.animate({marginLeft: -1 * thisPage.bounds().width});
      });
      
    events.find('.juice-spectalendar-back')
			.click(function(){
				var e = $(this),
					thisPage = e.closest('.juice-spectalendar-page');

				$('.juice-spectalendar-page:eq(0)').animate({marginLeft: 0}, function(){
					thisPage.hide();
				});
      });      
    
    var dialog = $('<div class="ui-widget ui-widget-content juice-spectalendar-dialog"/>')
      .append(close)
      .append(header)
      .append('<q>' + e.find('q').html() + '</q>')
      .append(events)
      .appendTo(target)
      .css(startCss)
      .animate(endCss, function(){
        var p = header.find('p:first');
        p.animate({marginTop: -1 * p.bounds().height});
        close.animate({opacity: 1});
        events.animate({opacity: 1});
        $(this).find('q:eq(0)').animate({opacity: 0}).slideUp();
      });
    
    e.animate({opacity: 0});
	

    
    dialog.find('.juice-spectalendar-close')
    
  })
  //.live('mouseenter', function(){ $(this).animate(animEnter, {queue: false}); })
	//.live('mouseleave', function(){ $(this).animate(animLeave, {queue: false}); });

  

  renderDays(target, date);  

  function renderDays(e, baseDate){       
 
  	var dateEvents = new Array ( );
  	//builder
	$.each( $("ul#cal > li"), function(index, l){		
		eventRel= $(this).attr('rel');
		eventClass = $(this).attr('class');
		dateEvents[index] = new Array ();
		
		dateEvents[index][1] = eventRel;
		dateEvents[index][2] = eventClass;
		
		
	});
  
  
      
    e = e.jquery ? e : $(e);
      
    var date = new Date(baseDate.getFullYear(), baseDate.getMonth(), 1),
      firstDay = date.getDay(),
      days = daysInMonth(date),
      month = baseDate.getMonth(),
      daysPrev = 0,
      today = baseDate.getDate(),
      dayIndex = 0,
      newRow = function(){
        return $('<li/>').appendTo(e).addClass('juice-spectalendar-week');
      },
      lastRow = newRow();

    date.setMonth(month - 1);
    daysPrev = daysInMonth(date);

    for(var i = 0; i < 7; i++){
      lastRow.append('<div class="juice-spectalendar-dayname">' + dayNames[i] + '</div>');
    }

    lastRow = newRow();

    //render days from the month before
    for(var i = 0; i < firstDay; i++){
      lastRow.append('<div class="ui-state-default juice-spectalendar-day juice-spectalendar-empty"><span><p>' + (daysPrev - (firstDay - i - 1)) + '</p></span></div>');
      dayIndex++;
	
    }

	//Thu-Apr-09-2009-17:46:21

    for(var day = 1; day <= days; day++){

		var hasEventBool = false;
		var hasStarEvent = false;
		if(day < 10) {
			currentDayNumber = "0" + day;
		} else {
			currentDayNumber = day;
		}

		var dayClassName =   shortDayNames[dayIndex]  + "-"+shortMonthNames[baseDate.getMonth()]+"-"+ currentDayNumber  + "-" + baseDate.getFullYear();
	
		var kz = 0;
		for (var i=0; i<dateEvents.length; i++) {			
			if (dayClassName == dateEvents[i][1].substr(0,15)) {	kz++;	hasEventBool = true; 
				if(dateEvents[i][2] == "star") { hasStarEvent = true;	}
		
			
			}		
		}
		 
	
				var hasEvent = (hasEventBool == true), klass = (hasEvent ? 'ui-state-highlight ' : '') + 'ui-state-default juice-spectalendar-day '+  (hasEvent ? ' juice-spectalendar-event' : ''), relValue = (dayClassName),
				div = $('<div class="' + klass +'" rel="' + relValue +'"><span class="' + (hasEvent ? 'ui-state-highlight' : '') + '"><p>' + day + '</p></span></div>');

				//hasEvent && div.hover(function(){ $(this).toggleClass('ui-state-hover'); });
				
			
				if(hasEventBool == true){
					
					if(hasStarEvent == true) {
						div.find('span').append('<img src="/images/icons/star.png" alt="star" style="position: absolute" />');
						
					}
					div.append();
					div.find('span').append('<q>' + kz +' events</q>');
				}


				lastRow.append(div);
				dayIndex++;

				if(dayIndex > 6){	dayIndex = 0;	lastRow = newRow();
				}
      
    };
    
    //render days from the month after
    if(dayIndex < 7){
      for(var i = 1; dayIndex < 7; i++){
        lastRow.append('<div class="ui-state-default juice-spectalendar-day juice-spectalendar-empty"><span><p>' + i + '</p></span></div>');
        dayIndex++;
      }      	
    }  
  };

  function daysInMonth(date){
    var year = date.getFullYear(),
      month = date.getMonth(),
      first = new Date(year, month, 1),
      nmonth = (month + 1) % 12,
      nyear = (nmonth == 0) ? year + 1 : year,
      end = new Date(nyear,nmonth, 1);
      
    return Math.round((end - first) / 86400000);
  };  
  
});
