(function($){
		
	$.widget('ui.calendar', {
		/*
		 * Option values that the user can set
		 */
		options: {
			year: new Date().getFullYear(),
			month: new Date().getMonth()
		},
		/*
		 * Initializes the widget
		 */
		_create: function() {
					
			var self = this,
			options = self.options,
			element = self.element;
					
			//Gets the calendar set up
			var cc = self.initCalendar(options.year, options.month);	
			self.generateCalendarHTML(self, cc.ccStartingDay, cc.ccCurrentDate, cc.ccMonthLabels, cc.ccDayLabels, cc.ccMonthLength, options.year, options.month);
			self.setupInteraction(self, cc.ccStartingDay, cc.ccCurrentDate, cc.ccMonthLabels, cc.ccDayLabels, cc.ccMonthLength, options.year, options.month);				
			
		},
		
		/**
		 * @function
		 * @name initCalendar
		 * @description Initializes the calendar
		 * @param {int} year
		 * @param {int} month
		 */
		initCalendar: function(year, month) {
			//Create labels
			ccDayLabels = ['Mån', 'Tis', 'Ons', 'Tor', 'Fre', 'Lör', 'Sön'];
			ccMonthLabels = ['Januari', 'Februari', 'Mars', 'April', 'Maj', 'Juni', 'Juli', 'Augusti', 'September', 'Oktober', 'November', 'December'];
			ccDaysInMonth = ['31', '28', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31'];
			
			//Gets the length of the current month
			ccMonthLength = ccDaysInMonth[month];
			
			//Gets the current date
			ccCurrentDate = new Date();
			
			//Gets the starting day of the month
			ccStartingDay = new Date(year, month, 0).getDay();

			//Compensate for leap year
			if (month == 1) {
				if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0){
			    	ccMonthLength = 29;
			  	}
			}
												
			//Creates an object with values to return
			return { ccStartingDay: ccStartingDay, ccCurrentDate: ccCurrentDate, ccMonthLabels: ccMonthLabels[month], ccDayLabels: ccDayLabels, ccMonthLength: ccMonthLength };		
		},
		
		/**
		 * @function
		 * @name generateCalendarHTML
		 * @description Generates all the HTML for the calendar
		 */
		generateCalendarHTML: function(self, ccStartingDay, ccCurrentDate, monthName, ccDayLabels, ccMonthLength, year, month) {
			//Creates basic structure
			var container = $('<div></div>').addClass('ui-widget cc-calendar');
			var ccHeader = $('<div></div>').addClass('ui-widget-header').appendTo(container);
			
			var ccLeftNav = $('<div></div>').appendTo(ccHeader);
			$('<a></a>').attr('href', '#').addClass('cc-nav-prev').text('Föregående').appendTo(ccLeftNav);
			
			var ccHeaderMonth = $('<div></div>').addClass('cc-Head-Month').text(ccMonthLabels[month] + ' ' + year).appendTo(ccHeader);
			
			var ccRightNav = $('<div></div>').addClass('nav-right').appendTo(ccHeader);
			$('<a></a>').attr('href', '#').addClass('cc-nav-next').text('Nästa').appendTo(ccRightNav);
			
			var ccContent = $('<div></div>').addClass('cc-content').appendTo(container);
			var ccWeekdays = $('<div></div>').addClass('cc-weekdays').appendTo(ccContent);
			var ccDays = $('<div></div>').addClass('cc-days').appendTo(ccContent);
			
			//Iterates through the weekdays and prints the correct label
			for(var i = 0; i < 7; i++){
				var cssClass = 'cc-weekday';
				if(i == 6) {
					cssClass += ' last';
				}
				$('<div></div>').addClass(cssClass).text(ccDayLabels[i]).appendTo(ccWeekdays);
			}
			$('<div></div>').addClass('clear').appendTo(ccWeekdays);
			
			//Iterates through the days						
			var day = 1;
			
			//Just an check to see if we need an extra row in the calendar
			if(ccStartingDay == 5 || ccStartingDay == 6 && ccMonthLength == 31){
				counter = 41;
			} else {
				counter = 34;
			}

		  	for (i = 0; i <= counter; i++) { 
		  		cssClass = 'cc-day';
		  		//Adds extra class if its the last element in the row
				if(i % 7 == 6){
					cssClass += ' last';
				}

				//Creates a wrapper for the day						
		    	var ccDay = $('<div></div>').addClass(cssClass);
				
				//Check to see if the day is in this month
		    	if (day <= ccMonthLength && (i >= ccStartingDay)) {
					$(ccDay).attr('id', 'day-' + year + '-' + month + '-' + day);
					//Check if the day is today
					if(day == ccCurrentDate.getDate() && ccCurrentDate.getMonth() == month && ccCurrentDate.getFullYear() == year){
						cssClass += ' cc-today';
					}	
					$(ccDay).addClass(cssClass);				
					//Generates the day
					self.generateDayHTML(self, ccDay, year, month, day);	
		      		day++;
		    	}
				//Else it is an empty day with no number
				else {
					$(ccDay).addClass('cc-empty-day');
				}
				
				//And at last we append the day to the wrapper
				$(ccDay).appendTo(ccDays);
		  	}
			
			//Adds an clear div tag after all the days
			$('<div></div>').addClass('clear').appendTo(ccDays);

			//Appends all the structure to the root element
			$(container).appendTo(self.element);
			
			var cc_footer = $('<div></div>').addClass('calendar-footer').appendTo(container);
			var my_current_day = $('<div></div>').addClass('my-current-day').text('Aktuell dag');
			$(cc_footer).append(my_current_day);
			
			var info_home_game = $('<div></div>').addClass('info-home-game').text('Hemma');
			$(cc_footer).append(info_home_game);
			
			var info_away_game = $('<div></div>').addClass('info-away-game').text('Borta');
			$(cc_footer).append(info_away_game);
			
		},
					
		/**
		 * @function
		 * @name generateDayHTML
		 * @description Generates a day in the calendar
		 */
		generateDayHTML: function(self, ccDay, year, month, day) {
			
			//Check to see if the day has any events
			var identifier = year + '-' + month + '-' + day;
			var ccEventWrapper = '';
			
			for(var i=0; i < calendarData.length; i++) {
				
				var fixed_date = calendarData[i].date;
				var date_array = fixed_date.split('-');
				var a_year = date_array[0];
				var a_month = date_array[1] - 1;
				var a_day = date_array[2];
				
				var new_date = a_year + '-' + a_month + '-' + a_day;
				
				//Checks to see if day has game
				if(identifier == new_date){
										
					//If GIF Sundsvall is home-team
					if(calendarData[i].home == 'gif-sundsvall') {
						
						$(ccDay).addClass('cc-day-game').addClass(calendarData[i].away).addClass('home-team').attr('title', calendarData[i].full_home + ' - ' + calendarData[i].full_away + ', ' + calendarData[i].nice_date + ' ' + calendarData[i].the_time);
						
						if(ccDay.hasClass('cc-today')) {
							ccDay.css('border', '1px solid #FABA3E');
						}
					}
					//If GIF Sundsvall is away team
					else {
						$(ccDay).addClass('cc-day-game').addClass(calendarData[i].home).addClass('away-team').attr('title', calendarData[i].full_home + ' - ' + calendarData[i].full_away + ', ' + calendarData[i].nice_date + ' ' + calendarData[i].the_time);
						
						if(ccDay.hasClass('cc-today')) {
							ccDay.css('border', '1px solid #FABA3E');
						}
					}
					//Add pop-up to day
					var tempDiv = $('<div></div>').addClass('pop-up-info').attr('title', '');
					//Add close-button to pop-up
					var aTag = $('<a></a>').attr('href', '#').addClass('close-popup').text('Stäng');
					$(tempDiv).append(aTag);
						//Checks to see if the game is not broadcasted
						if(calendarData[i].broadcast == '') {
							var hTag = $('<p></p>').text('');
							$(tempDiv).append(hTag);
						}
						//Print if the game is broadcasted
						else {
							var hTag = $('<p></p>').text('Matchen sänds på ' + calendarData[i].broadcast);
							$(tempDiv).append(hTag);
						}
						//Mid-container div
						var popMidDiv = $('<div></div>').addClass('pop-mid-div').appendTo(tempDiv);
						
						var homeTeam = $('<div></div>').addClass('home-team-info');
						$(popMidDiv).append(homeTeam);
						//If GIF Sundsvall is home team, do this
						if(calendarData[i].home == 'gif-sundsvall') {
							var imgTeamHome = $('<img />').attr('src', '/wp-content/uploads/team-images/gif-sundsvall.png').attr('alt', 'GIF Sundsvalls logo').addClass('left');
							$(homeTeam).append(imgTeamHome);
							var textHomeTeam = $('<p></p>').text('GIF Sundsvall');
							$(homeTeam).append(textHomeTeam);	
							
							//Checks to see if game has been played
							var todays_date = new Date();
							var my_date = new Date(a_year, a_month, a_day);
							if(my_date < todays_date) {
								var vsText = $('<span></span>').text(calendarData[i].result).css('margin', '27px 0 0 10px');
								$(popMidDiv).append(vsText);
							}
							else {
								var vsText = $('<span></span>').text('VS');
								$(popMidDiv).append(vsText);
							}
													
							var awayTeam = $('<div></div>').addClass('away-team-info');
							$(popMidDiv).append(awayTeam);				
							
							var imgTeamAway = $('<img />').attr('src', '/wp-content/uploads/team-images/'+ calendarData[i].away +'.png').attr('alt', calendarData[i].away).addClass('right');
							$(awayTeam).append(imgTeamAway);	
							var textAwayTeam = $('<p></p>').text(calendarData[i].full_away);
							$(awayTeam).append(textAwayTeam);			
						}
						else {
							var imgTeamHome = $('<img />').attr('src', '/wp-content/uploads/team-images/' + calendarData[i].home + '.png').attr('alt', calendarData[i].home+' logo').addClass('left');
							$(homeTeam).append(imgTeamHome);
							var textHomeTeam = $('<p></p>').text(calendarData[i].full_home);
							$(homeTeam).append(textHomeTeam);
							
							var todays_date = new Date();
							var my_date = new Date(a_year, a_month, a_day);
							if(my_date < todays_date) {
								var vsText = $('<span></span>').text(calendarData[i].result).css('margin', '27px 0 0 10px');
								$(popMidDiv).append(vsText);
							}
							else {
								var vsText = $('<span></span>').text('VS');
								$(popMidDiv).append(vsText);
							}
						
							var awayTeam = $('<div></div>').addClass('away-team-info');
							$(popMidDiv).append(awayTeam);				
							
							var imgTeamAway = $('<img />').attr('src', '/wp-content/uploads/team-images/gif-sundsvall.png').attr('alt', 'GIF Sundsvalls logo').addClass('right');
							$(awayTeam).append(imgTeamAway);	
							var textAwayTeam = $('<p></p>').text('GIF Sundsvall');
							$(awayTeam).append(textAwayTeam);
						}			
						
					var lowerDiv = $('<div></div>').addClass('lower-div').appendTo(tempDiv);
					
					var locationText = $('<p></p>').text(calendarData[i].location);
					$(lowerDiv).append(locationText);
					
					var timeAndDate = $('<p></p>').text(calendarData[i].the_time + ' ' + calendarData[i].nice_date);
					$(lowerDiv).append(timeAndDate);
					
					var todays_date = new Date();
					var my_date = new Date(a_year, a_month, a_day);
					if(my_date < todays_date) {
						var bottomDiv = $('<div></div>').addClass('bottom-div').appendTo(tempDiv);
						var gamereportBtn = $('<a></a>').attr('href', calendarData[i].game_report).text('Läs matchrapport').addClass('left').css('margin-left', '55px');
						$(bottomDiv).append(gamereportBtn);
					}
					
					else {
						if(calendarData[i].buy_tickets != '' && calendarData[i].restaurant_vip == '') {
							var bottomDiv = $('<div></div>').addClass('bottom-div').appendTo(tempDiv);
							var buyBtn = $('<a></a>').attr('href', calendarData[i].buy_tickets).text('Köp biljetter').addClass('left');
							$(bottomDiv).append(buyBtn);
						}
						else if(calendarData[i].restaurant_vip != '' && calendarData[i].buy_tickets == '') {
							var bottomDiv = $('<div></div>').addClass('bottom-div').appendTo(tempDiv);
							var restaurantBtn = $('<a></a>').attr('href', calendarData[i].restaurant_vip).text('Restaurang / VIP').addClass('left');
							$(bottomDiv).append(restaurantBtn);
						}
						else if(calendarData[i].restaurant_vip != '' && calendarData[i].buy_tickets != '') {
							var bottomDiv = $('<div></div>').addClass('bottom-div').appendTo(tempDiv);
							var buyBtn = $('<a></a>').attr('href', calendarData[i].buy_tickets).text('Köp biljetter').addClass('left');
							$(bottomDiv).append(buyBtn);
						
							var restaurantBtn = $('<a></a>').attr('href', calendarData[i].restaurant_vip).text('Restaurang / VIP').addClass('right');
							$(bottomDiv).append(restaurantBtn);
						}
						else if(calendarData[i].restaurant_vip == '' && calendarData[i].buy_tickets == '') {
							lowerDiv.css('border-bottom', 'none');
						}
					}
					
														
					$(tempDiv).addClass('pop-up-info').appendTo(ccDay);			
							
				}
			}
			
			//Adds the day number
			var spanTag = $('<span>' + day + '</span>');
      		$(ccDay).append(spanTag);
			
			$(ccEventWrapper).appendTo(ccDay);
			$(ccDay).addClass('cc-ordinary-day');			
			
		},
		
		/**
		 * @function
		 * @name setupInteraction
		 * @description Handles all the interaction with the user
		 * @param {object} self
		 */
		setupInteraction: function(self, ccStartingDay, ccCurrentDate, ccMonthLabels, ccDayLabels, ccMonthLength, year, month) {
			
			var cYear = self.options.year;
			var cMonth = self.options.month;	
								
			$('.cc-nav-next').live('click', function(e){
				e.preventDefault();
				$('.cc-calendar').remove();
				
				if(cMonth > 10) {
					cYear++;
					cMonth = 0;
				}
				else {
					cMonth++;
				}
				
				var cc = self.initCalendar(cYear, cMonth);	
				self.generateCalendarHTML(self, cc.ccStartingDay, cc.ccCurrentDate, cc.ccMonthLabels, cc.ccDayLabels, cc.ccMonthLength, cYear, cMonth);
			});
			
			$('body').click(function(){
 				 $('.pop-up-info').fadeOut(100);
			});

			// Prevent events from getting pass .pop-up-info
			$(".pop-up-info").click(function(e){
				if(!$(e.target).hasClass('close-popup')) {
					e.stopPropagation();
				}
 				
			});
			
			
			$('.close-popup').live('click', function(e){
				$(this).parents('body').find('.cc-day-game').find('.pop-up-info').fadeOut(100);
			});
			
			
			$('.cc-nav-prev').live('click', function(e){
				e.preventDefault();
				$('.cc-calendar').remove();
				
				if(cMonth < 1) {
					cYear--;
					cMonth = 11;
				}
				else {
					cMonth--;
				}
				
				var cc = self.initCalendar(cYear, cMonth);	
				self.generateCalendarHTML(self, cc.ccStartingDay, cc.ccCurrentDate, cc.ccMonthLabels, cc.ccDayLabels, cc.ccMonthLength, cYear, cMonth);
			});
			
			$('.cc-day-game').live('click', function(e){
				e.preventDefault();
				$(this).parents('body').find('.cc-day-game').find('.pop-up-info').hide();				
				$(this).find('div').show();
			});

			
			
			$('.bottom-div a').live('click', function(e){
				window.open($(this).attr('href'));
			});
											
			//Shows the add event tooltip
			$('.cc-day-has-events').hover(function(){
				$(this).next().stop(true, true).fadeIn(100);
			}, function(){
				$(this).next().stop(true, true).fadeOut(100);
			});

			//Shows the event list for the day
			$('.cc-day-has-events').hover(function(){
				$(this).children('.cc-event-wrapper').stop(true, true).fadeIn(200);
			}, function(){
				//Updates the event when the wrapper is not displayed
				$(this).find('.cc-event').each(function(){
					var id = $(this).parent().parent().attr('id');
					var title = $(this).find('h4').text();
					var place = $(this).find('.place-inner').text();
					var description = $(this).find('.description').text();
					var time = $(this).find('.time-inner').text();
					self.updateEvent(id, title, place, description, time);
				});					
				$(this).children('.cc-event-wrapper').stop(true, true).fadeOut(200);
			});

			//Saves the event on submit
			$('.cc-add-event-wrapper .submit').click(function(){
				var id = $(this).parents('.cc-day').attr('id');
				var title = $(this).parent().find('#title').val();
				var place = $(this).parent().find('#place').val();
				var time = $(this).parent().find('#time').val();
				var description = $(this).parent().find('#description').val();
				self.createEvent(id, title, place, description, time);
			});
			
			//Deletes the event
			$('.cc-event .delete').click(function(){
				var id = $(this).parents('.cc-day').attr('id');			
				self.deleteEvent(id);
				//Removes the class for the day
				$(this).parents('.cc-day').removeClass('cc-day-has-events');		
				//Removes the event wrapper
				$(this).parent().parent().remove();
				return false;
			});
			
			$('#change').click(function(){
				$(this).parents('body').find('.cc-calendar').remove();
				//self.initCalendar(2011, 3);
				self.generateCalendarHTML(self, 4, ccCurrentDate, 'April', ccDayLabels, ccMonthLength, 2011, 5);
				self.setupInteraction(self);
				
			});																			
		},
		/**
		 * @function
		 * @name createEvent
		 * @description Creates an event
		 * @param {string} id
		 * @param {string} title
		 * @param {string} place
		 * @param {string} description
		 * @param {string} time
		 */
		createEvent: function(id, title, place, description, time) {
			var event = { id: id, title: title, place: place, description: description, time: time };
			localStorage.setItem(id, JSON.stringify(event));
		},	
		/**
		 * @function
		 * @name getEvent
		 * @description Get a specific event
		 * @param {string} id
		 * returns {object}
		 */
		getEvent: function(id) {
			return JSON.parse(localStorage.getItem(id));
		},
		/**
		 * @function
		 * @name updateEvent
		 * @description Updates an event
		 * @param {string} id
		 * @param {string} title
		 * @param {string} place
		 * @param {string} description
		 * @param {string} time
		 */
		updateEvent: function(id, title, place, description, time) {
			var event = { id: id, title: title, place: place, description: description, time: time };					
			localStorage.setItem(id, JSON.stringify(event));
		},		
		/**
		 * @function
		 * @name deleteEvent
		 * @description Deletes a specific event
		 * @param {string} id
		 */
		deleteEvent: function(id) {
			localStorage.removeItem(id);
		},			
		
		/**
		 * @function
		 * @name destroy
		 * @description Destroys the widget
		 */	
		destroy: function() {
			//Destroy Widget
		}				
	});
})(jQuery);

