$(document).ready(function() {
	var $ = jQuery;
	
	$("#startTime").datepicker();
	$("#endTime").datepicker();
	
	
	//*******************************************************
	//  Function to change the VCS calendar to the next month
	//*******************************************************
	var getNextMonth = function() {
		var nextMonth = $(this).attr("id");
		var storeNum = $(".calendarInfo").attr("id");
		
		var calInfo = $(".calendarInfo").val();
		//Need tp parse the calendar info to get the year & catId
		var year = calInfo.slice(0,calInfo.indexOf("-"));
		var catId = calInfo.slice(calInfo.indexOf("-")+1);
		
		if(nextMonth == "January")//Need to go to the new year
		{
			year = eval("" + year + "+" +  1);
		}
				
		var frag = $("#cooking-school-calendar");//This is the div that holds the calendar
		$.get("/consumer/cookingschool/fragments/calendar_fragment.jsp", {"id":catId, "storeNum":storeNum, "calMonth":nextMonth, "calYear":year}, function(data) {
			frag.html($(data).html());
			//Add the listeners back
			$(".nextMonth").click(getNextMonth);
			$(".prevMonth").click(getPrevMonth);
			$(".seriesSelect").change(highlightSeries);
			FancySelects($('select#filter-series'));
		});
		
		return false;
	}
	
	$(".nextMonth").click(getNextMonth);
	
	
	//*******************************************************
	//  Function to change the VCS calendar to the previous month
	//*******************************************************
	var  getPrevMonth = function() {
		var prevMonth = $(this).attr("id");
		var storeNum = $(".calendarInfo").attr("id");
		
		var calInfo = $(".calendarInfo").val();
		//Need tp parse the calendar info to get the year & catId
		var year = calInfo.slice(0,calInfo.indexOf("-"));
		var catId = calInfo.slice(calInfo.indexOf("-")+1);
		
		if(prevMonth == "December")//Need to go back to the previous year
		{
			year = eval("" + year + "-" +  1);
		}
		
		var frag = $("#cooking-school-calendar");//This is the div that holds the calendar
		$.get("/consumer/cookingschool/fragments/calendar_fragment.jsp", {"id":catId, "storeNum":storeNum, "calMonth":prevMonth, "calYear":year}, function(data) {
			frag.html($(data).html());
			//Add the listeners back
			$(".nextMonth").click(getNextMonth);
			$(".prevMonth").click(getPrevMonth);
			$(".seriesSelect").change(highlightSeries);
			FancySelects($('select#filter-series'));
		});
		
		return false;
	}
	
	$(".prevMonth").click(getPrevMonth);
	
	
	//*******************************************************
	//  Hide ul.error
	//*******************************************************
	var hideErrorList = function() {
		$("ul.error").removeClass("error-on").addClass("error-off");
	}
	
	
	//*******************************************************
	//  Show ul.error
	//*******************************************************
	var showErrorList = function() {
		$("ul.error").removeClass("error-off").addClass("error-on");
	}
	
	hideErrorList();//Initialize ul.error by hiding it.
    
    
	//*******************************************************
	//  Function needed to display errors for series filtering
	//*******************************************************
	var updateErrors = function(errors,area){
		area.empty();
		showErrorList();
		$.each(errors, function(i) {
			var li = $(['<li>', errors[i], '</li>'].join(''));
			area.append(li);
		});
	}
	
	
	//********************************************************
	//  Function to highlight VCS Calendar events of a certain series
	//  &  display appropriate error messages if no classes are found
	//*******************************************************
	var  highlightSeries = function() {
		
		hideErrorList();//Reset ul.error by hiding it.
		
		var series = $(this).val();//Get the select value from the dropdown
		var errors = [];//Array to hold the possible errors on the page
		var errorArea =$("#error-area");//The UL that will display the errors
		
		//Need to remove the previous class used for shading
		var previousEvents = $(this).parents("#cooking-school-calendar").find(".calendar-event");
		previousEvents.removeClass("filtered");
		previousEvents.css('color', '');//Temporary until CSS is done
		
		var events = $(this).parents("#cooking-school-calendar").find(".calendar-event."+ series);//Get all events that match the series
	
		if(events.length == 0 && series != "All")//No Calendar Events were selected to be highlighted/filtered
		{
			//***Needed info for the DWR call and the calendar link***
			var storeNum = $(".calendarInfo").attr("id");
			var nextMonth = $(".nextMonth").attr("id");
			//Need tp parse the calendar info to get the year & catId
			var calInfo = $(".calendarInfo").val();
			var year = calInfo.slice(0,calInfo.indexOf("-"));
			var catId = calInfo.slice(calInfo.indexOf("-")+1);
			
			if(nextMonth == "January")//Need to go to the new year
			{
				year = eval("" + year + "+" +  1);
			}
			
			//Call DWR method
			VCSCalendarManager.getNextAvailableClassDate(storeNum, series, nextMonth, year, function(classDate) {
				if(classDate == null)//No class of that series exists for that location
				{
					var phoneNum = $("#id-phone-num").text();//Get phone number from live_help_bin
					phoneNum = phoneNum.slice(phoneNum.indexOf(":")+2);//Get rid of the "Phone: " portion to get just the #
					var emailHref = $("#id-email-link").attr("href");//Get the actual href for the email link
					var emailLink = "<a href=\"" + emailHref + "\"> Email Us</a>";
					errors.push("No classes are available in this series for this location. Call us at " + phoneNum + " or " + emailLink + "  to request a class.");
					
					// Now filter out all events for current view.
					var filteredEvents = $(".calendar-event:not(." + series+")");//Get all events that DO NOT match the series
					filteredEvents.addClass("filtered");
				}
				else
				{
					//Get all the months names for the calendar link and the display
					var monthNames = new Array("January", "February", "March", 
						"April", "May", "June", "July", "August", "September", 
						"October", "November", "December");
					var month = classDate.getMonth() + 1;//Add 1 to adjust for 0-based index
					var monthName = monthNames[classDate.getMonth()];//Get the actual month's name
					var day = classDate.getDate();
					var year = classDate.getFullYear();
					
					//Pass in all the necessary parameters for providing a link to the calendar page
					var href = "/consumer/cookingschool/classes/calendar.jsp?id=" + catId + "&storeNum=" + storeNum + "&calMonth=" + monthName + "&calYear=" + year;
					var text = "View the calendar for " + monthName;
					var link = "<a href=\"" + href + "\">" +  text + "</a>";
					
					errors.push("The next available class in this series is " + month + "/" + day + "/" + year + ". " + link);
				}
				updateErrors(errors,errorArea);
			});
		}
		else if(series != "All")//There are Calendar Events that need to be filtreed
		{
			var filteredEvents = $(this).parents("#cooking-school-calendar").find(".calendar-event:not(." + series+")");//Get all events that DO NOT match the series
			filteredEvents.addClass("filtered");
		}
		
		//Need to remove possible old errors
		if(errors.length == 0)
		{
			 errorArea.empty();
			 
		}
	
		return false;
	}
	
	$(".seriesSelect").change(highlightSeries);
	
	
	//*************************************************************
	//  Function to load the specific location from a select box from a generic page
	//*************************************************************
	var  loadLocation = function() {
		var location = $(this).val();
		var pageParam = $(this).attr("id");
		var newPage = "";
		
		
		if(location != "Select One")//Do nothing if "Select One" is chosen
		{
			if( location.match("external"))
			{
				window.location = location;
			}
			else
			{
				if( pageParam.substring(0,4) == "prod")
				{
					newPage = "/consumer/cookingschool/classes/class_detail.jsp?prodId"
				}
				else
				{
					newPage = "/consumer/cookingschool/classes/class_category.jsp?series"
				}
				
				window.location = newPage + "=" + pageParam+ "&id=" + location;//Load the correct page with the correct parameter
			}
		
			
		}
	
		return false
	}
	
	$(".generic-location-select").change(loadLocation);
	
	
	//********************************************************************
	//  Function to load the specific location from a select box from a the VCS landing page
	//********************************************************************
	var  loadLandingLocation = function() {
		var location = $(this).val();
		var newPage = "";
		
		if(location != "Select One...")//Do nothing if "Select One..." is chosen
		{
			newPage = "/consumer/cookingschool/location_overview.jsp?id="
			if (location.indexOf('external') > -1) {
				newPage = "/consumer";
			}
			window.location = newPage + location;//Load the correct page with the correct parameters
		}
	
		return false
	}
	
	$(".landing-location-select").change(loadLandingLocation);
	
	
	//********************************************************************
	//  Function to display the "available number of seats" messase on the class detail page
	//********************************************************************
	var displayClassErrors = function() {
		var almostEmptyClasses = $("#classSkuTable").find(".seats-almost-empty");//See if any sku is ASO
		var errors = [];//Array to hold the possible errors on the page
		var errorArea =$("#error-area");//The UL that will display the errors
		
		if(almostEmptyClasses != null && almostEmptyClasses.length != 0)//An ASO sku exists in the table
		{
			var phoneNum = $("#id-phone-num").text();//Get phone number from contact_info_bin
			phoneNum = phoneNum.slice(phoneNum.indexOf(":")+2);//Get rid of the "Phone: " portion to get just the #
			var emailHref = $("#id-email-link").attr("href");//Get the actual href for the email link
			var emailLink = "<a href=\"" + emailHref + "\"> Email Us</a>";
			errors.push("Need more than the available number of seats? Call us at " + phoneNum + " or " + emailLink + "  for options.");

			updateErrors(errors,errorArea);//Call the function to show the errors
		}
	}
	
	displayClassErrors();
	
	
	//**************************************************************************
	//  Function to clear out the Search input box if when the button is clicked if there is no input
	//**************************************************************************
	var  clearSearchBox = function() {
		var searchBox = $(this).parents(".vcs-search-form").find(".vcs-search-box");
		
		if(searchBox.val() == "Class name or keyword")//The input box needs to be cleared
		{
			searchBox.val("");
		}
		return true
	}
	
	$(".vcs-find-class").click(clearSearchBox);
	$(".vcs-find-class").enable();//wait till the above function is loaded & ready before enabling the search button.

	
	//**************************************************************************
	//  Function to display an error message on the class detail page if 0 quantity is added to cart
	//**************************************************************************
    var displayCartAddError = function() {
	    var form = $(this).closest('form');
	    var p = form.find('p.error');
	    var ok = false;
	    
	    form.find('select').each(function()
	    {
	        if (parseInt($(this).val(), 10) > 0)
	        {
	            ok = true;
	        }
	    });
	    p.toggle(!ok);
	    return ok;
    };
    
    $('form#class-add-form').find(':submit').click(displayCartAddError);
    
    
    //*************************************************************************************
	//  Function to reset the quantity select box on the class detail page, once a class has been added to a cart
	//*************************************************************************************
    var restClassQuantity = function() {
    	var form = $(this).closest('form');
	    var quantity = form.find('select.quantity');
	    
	    quantity.val(0);
	    
	    return false;
    }
    
    $('form#class-add-form').submit(restClassQuantity);
    
    
  //*****************************************************************************************
	//  Function to handle the displaying of a message layer that appears as a fly-out above the element passed in
	//****************************************************************************************
    var MessageLayer = function(o) {
        var node = o;
        var layerId = 'calendar-registration-message';
        $(['#', layerId].pack()).remove();
        var tip = $('<div id="calendar-registration-message"><div id="calendar-registration-message-content"></div><div id="calendar-registration-message-bottom">&nbsp;</div></div>').hide();
        $('body').append(tip);
        return {
            show: function(text) {
                tip.find('div:first').text(text);
                var offset, top, left, w, h;
                offset = node.offset();
                top = offset.top;
                left = offset.left;
                setTimeout(function() {
                    tip.show();
                    tip.css({
                        top: top - tip.height() + 6,
                        left: (left + node.width() / 2) - (tip.outerWidth() / 2)
                    });
                    if ($.browser.msie && $.browser.version < 7) {
                       tip.find('div:last').remove();
                       tip.css({
                           top: node.offset().top - tip.height()
                       });
                    }
                }, 250);

            }
        };
    };
    
    
    //*****************************************************************************************************
	//  Function to show/remove the "Closed Registration" message when a user clicks on a class on the calendar in the 48hr window
	//*****************************************************************************************************
    var handleRegistrationMessage = function(action) {
    	var messageDiv = $("div#calendar-registration-message");
    	
    	if(action.type == "mouseenter" || action.type == "click")
    	{
    		if(messageDiv != null)
        	{
        		messageDiv.remove();
        	}
        	
        	var phoneNum = $("#id-phone-num").text();//Get phone number from contact_info_bin
    		phoneNum = phoneNum.slice(phoneNum.indexOf(":")+2);//Get rid of the "Phone: " portion to get just the #
    		var locationName = $("#id-location-name").text();//Get the location name from contact_info_bin

        	var layer = null;
        	var text = "Online class registration closes 48 hours prior to class meeting. Please contact "  + locationName + " at " + phoneNum + " for more information.";
            layer = new MessageLayer($(this).closest("li"));
            layer.show(text);
    	}
    	else if (action.type == "mouseleave")
    	{
    		messageDiv.remove();
    	}
    	
	    
	    return false;
    }
    
    $('a.salesRestricted').mouseenter(handleRegistrationMessage);//shows the registration message
    $('a.salesRestricted').mouseleave(handleRegistrationMessage);//removes the registration message
    $('a.salesRestricted').click(handleRegistrationMessage);//shows the registration message
	
});
