var firstPageLoad = 0;
var noofdaysLessons = 6;
var noofdaysRental = 6;
var minNoOfDays = 0;

$(function () {
    // Attach savetoCart event on continue button clcick
    $("[id$='btnContinue']").click(SaveToCart);

	firstPageLoad = 1;
    // Setup the tab
    tabSetup();

   // sets and attach click event to open modal window on save to trip
    displaylessonsModal();

	$(".ddlAdultLocation").bind("change", function () {
        var val = $(this).val();

		if (val.toLowerCase() != "select one" && $(this).find("option").eq(0).val().toLowerCase() == "select one") {
            $(this).find("option").eq(0).remove();
        }

        $('.hdnSelectedRPOSSaleLocationID').val($(this).find("option").eq(0).val());
    });

	$(".ddlChildLocation").bind("change", function () {
        var val = $(this).val();

		if (val.toLowerCase() != "select one" && $(this).find("option").eq(0).val().toLowerCase() == "select one") {
            $(this).find("option").eq(0).remove();
        }

        $('.hdnSelectedRPOSSaleLocationID').val($(this).find("option").eq(0).val());
    });

   //Set the iframe window properties to be opened on clicking save to trip link in the result
   $('.saveToTripDataDialog').dialog({
	       bgiframe: true,
		    autoOpen: false,
		    width: 960,
		height: 855,
		    modal: true,
		    resizable: false,
		    position: 'center',
		    closeOnEscape: true
	    });

	$(".linkSave").unbind('click').bind('click', function (e) {
             e.preventDefault();
             OpenSavetoTripModal($(this));
   });

	$(".btnSearch").unbind('click').bind('click', function (e) {
             e.preventDefault();
             $('[id$=hdnDiscipline]').val($('[id$=rdblDiscipline] tr td input[type=radio]:checked').val());
             $('[id$=hdnSaleLocation]').val($('.privateLessonMeetingLocationDropDown select').val());
   });

   attachFilterEvents();
   dragDropEvent();
   DeactiveRemoveLink();

	// To display hover bubble around links 
	$("a.rollover").hover(
		function (e) {
    if ($(this).next("div").hasClass("hoverDiv")) {
        var hoverDiv = $(this).next("div.hoverDiv").appendTo("body").data("el", this);
        hoverDiv.bgiframe();
    }
    var rollover = this;
			$(".hoverDiv").each(function () {
        if ($(this).data("el") == rollover) {
            $(this).css({
                top: e.pageY + 15 + "px",
                left: e.pageX + "px",
                position: "absolute"
            }).removeClass("hideDiv");
            $(".gradientBoxMiddleRight", $(this)).css({ marginLeft: "17px", paddingRight: "17px" });
            $(".gradientBoxMiddleLeft", $(this)).css({ marginTop: "0px", marginBottom: "0px" });
            return false;
        }
    });
		},
		function (e) {
    var hoverDiv = null;
    var rollover = this;
			$(".hoverDiv").each(function () {
        if ($(this).data("el") == rollover) {
            hoverDiv = $(this);
            hoverDiv.addClass("hideDiv");
            return false;
        }
    });
		}
	);
});

//Function Name : attachFilterEvents
//Purpose : This function is used to bind all the required events to the controls
//Parameters : NA
function attachFilterEvents() {
	//No. of days slider=5 for heavenly foronly,  rest =6    
    if ($('#heavenly').length > 0) {
        $('.exploreLessonsDaysSlider li').each(function () {
			if ($(this).html() == "0" || $(this).html() == "6") {
                $(this).remove();
			}
        });

		$('.exploreLessonsDaysSlider li').css('padding-left', '25px');
		$('.exploreLessonsDaysSlider li:first-child').css('padding-left', '11px');
		minNoOfDays = 1;
		maxNoOfDays = 5;
	} else {
		minNoOfDays = 0;
		maxNoOfDays = 6;
	}
	
    //Getting hidden field value that is added from server side to get modal window height.
    var w = '';
    if ($('[id$=hidMapDimension]').length > 0) {
        w = Number($('[id$=hidMapDimension]').val().split(',')[0]);
    }

    if (w >= 800 || w == '') {
        w = 800;
    }

    //setting up the modal window attributes
    if ($('.exploreLessonLocationMapModal').length > 0 && $('body > .ui-dialog .exploreLessonLocationMapModal').length == 0) {
        $('.exploreLessonLocationMapModal').eq(0).dialog({
			bgiframe: true,
			autoOpen: false,
			width: w,
			modal: true,
			resizable: false,
			position: 'center',
			closeOnEscape: true
        });
    }

	var dlgMap = $('body > .ui-dialog .exploreLessonLocationMapModal');

	$('.exploreLessonsLocationMap').unbind("click").bind("click", function (e) {
	    e.preventDefault();
	    // grabs url from href and loads it into the modal window
	    var url = $(this).attr('href');
		dlgMap.find("img")
	    	.attr("src", url)
	    	.attr("display", "block")
	    	.attr("width", w - 20);

	    dlgMap
			.css('text-align', 'center')
			.dialog('open');

	    if ($.browser.msie && $.browser.version < 9.0) {
	        var scrollToPos = dlgMap.parent('.ui-dialog').position().top;
	        if (scrollToPos > 20) scrollToPos -= 20;
	        window.scrollTo(0, scrollToPos);
	    }

	    return false;
	});

    $("#numberOfDaysLessonsSlider").slider({
        animate: true,
        range: false,
        min: minNoOfDays,
        max: maxNoOfDays,
        step: 1,
        value: noofdaysLessons,
		stop: function (event, ui) {
            filterNumberOfDays();
        }
    });

        $("#numberOfDaysRentalSlider").slider({
            animate: true,
            range: false,
            min: minNoOfDays,
            max: maxNoOfDays,
            step: 1,
            value: noofdaysRental,
		stop: function (event, ui) {
                filterNumberOfDays();
            }
        });

    filterNumberOfDays();

    //Init datepicker calendar
    var cal = $(".withCalendar").datepicker({
        showOn: 'button',
        buttonImage: '/VailResorts/sites/PlanningAndBooking/assets/img/icon_calender.gif',
        buttonImageOnly: true,
        maxDate: '+1y',
        minDate: '0',
		onSelect: function (dateText, inst) { }
    });
};

function dragDropEvent() {
	$(".draggable").draggable({ helper: 'clone', stop: function (event, ui) { ui.helper.hide(); } });  //Make lessons box draggable
 $("#droppable").droppable({
 	drop: function (event, ui) {
 		addLessonToTray(ui.draggable);
 	},
 	tolerance: "touch"
 });
}

function tabSetup() {
    /*--------- Get TAB ID to be selected by default based on previous URL ----------*/
    var searchStr = 'search=';
    var sortByStr = '~';
    var fullURL = parent.document.URL;
    var queryString = '';

    /* Disable the remove all link on load */
    DeactiveRemoveLink();

	var qstrlessontype = 'lessontype=';
     fullURL = fullURL.toLowerCase();
	var tabIdx = fullURL.substring(fullURL.indexOf(qstrlessontype) + qstrlessontype.length, fullURL.indexOf(qstrlessontype) + qstrlessontype.length + 1);

	if (fullURL.indexOf(searchStr) != -1) {
		var extractURL = fullURL.substring(fullURL.indexOf(searchStr) + searchStr.length, fullURL.length);
        queryString = fullURL.substring(fullURL.indexOf(searchStr), fullURL.length);
        search = extractURL;

        var queryStringParameters = queryString.split(',');

		if (queryStringParameters.length == 7) {
            $('.hdnSelectedRPOSSaleLocationID').val(queryStringParameters[2]);
            $('.hdnSelectedRPOSCategoryID').val(queryStringParameters[3]);
			noofdaysLessons = queryStringParameters[4];
			noofdaysRental = (queryStringParameters[5].split('~'))[0];

            AttachResultsFilterEvents();
        }

        var tabIdx;
		if (fullURL.indexOf(sortByStr) > 0) {
            //~ is the seprator for tab index. This will get the tab index (0 or 1 or 2)
			tabIdx = fullURL.substring(fullURL.indexOf(sortByStr) + sortByStr.length, fullURL.indexOf(sortByStr) + 2);
		} else {
			fullURL = fullURL.toLowerCase();
            tabIdx = fullURL.substring(fullURL.indexOf(qstrlessontype) + 11, fullURL.length);
			
            if (tabIdx.indexOf('&') >= 0) {
                tabIdx = tabIdx.substring(0, tabIdx.indexOf('&'));
            }
        }

		if (queryString.indexOf('~') != -1 && $(".txtSearchClass").val() != "") {
			addTicketToTrayFromSearchParameter();
        }
    }

	if ($('[id$=hdnPrivateLessonTab]').length > 0) {
		if ($('[id$=hdnPrivateLessonTab]').val() != '2') {
			if ($('.hdnTabSelectedValue').val() != '') {
            tabIdx = $('.hdnTabSelectedValue').val();
				if (tabIdx == 0) {
			$("[id$=divInstructionalTextAdult]").show();
			$("[id$=divInstructionalTextChildren]").hide();
			$("[id$=AdultLesson]").show();
			$(".AdultLessonSearchFilters").show();
			$(".adultLocationSearchResult").show();
			$(".ChildLessonSearchFilters").hide();
			$(".childLocationSearchResult").hide();
			$(".divEmailPrintLinks").hide();
			$("[id$=divLessonResult]").hide();
			$(".divLessonFilter").hide();
					$("[id$=hrefViewMap]").attr("href", $("[id$=hdnViewAdultMapSrc]").val()).text($("[id$=hdnViewAdultMapText]").val());

				} else if (tabIdx == 1) {
			$("[id$=divInstructionalTextAdult]").hide();
			$("[id$=divInstructionalTextChildren]").show();
			$("[id$=AdultLesson]").show();
			$(".ChildLessonSearchFilters").show();
            $(".childLocationSearchResult").show();
			$(".AdultLessonSearchFilters").hide();
			$(".adultLocationSearchResult").hide();
			$(".divEmailPrintLinks").hide();
			$("[id$=divLessonResult]").hide();
			$(".divLessonFilter").hide();
					$("[id$=hrefChildViewMap]").attr("href", $("[id$=hdnViewChildrenMapSrc]").val()).text($("[id$=hdnViewChildrenMapText]").val());
		    }

				if ($('[id$=hdnPrivateLessonTab]').length > 0) {
					if ($('[id$=hdnPrivateLessonTab]').val().length > 0) {
                $('[id$=hdnPrivateLessonTab]').val('');
            }
        }
        }
        }
        }

	if ($('.hdnSelectedRPOSSaleLocationID').val() != '') {
		if (tabIdx == 0) {
            var val =  $(".ddlAdultLocation").val();
			if ($(".ddlAdultLocation").find("option").eq(0).val().toLowerCase() == "select one") {
                $(".ddlAdultLocation").find("option").eq(0).remove();
            }
        }

		if (tabIdx == 1) {
            var val =  $(".ddlChildLocation").val();
			if ($(".ddlChildLocation").find("option").eq(0).val().toLowerCase() == "select one") {
                $(".ddlChildLocation").find("option").eq(0).remove();
            }
        }
    };

        //Save currently selected tab
        $("#hdnclas34").html(tabIdx);

        var liTabs = $(".mainTabsPnB li");
	liTabs.bind("click", function (event) {
            event.preventDefault();
            $("#hdnclas34").html(liTabs.index(this));

		if (firstPageLoad == 1) {
			handleTabSelect('false', queryString);
            } else {
			handleTabSelect('true', queryString);
            }
        });

	if ($('[id$=hdnPrivateLessonTab]').length > 0) {
		if ($('[id$=hdnPrivateLessonTab]').val().length > 0) {
                $('[id$=hdnPrivateLessonTab]').val('');
                $('.mainTabsPnB li a:eq(2)').click()
		} else {
			$('.mainTabsPnB li a:eq(' + tabIdx + ')').click()
            }
            }
}

// This method is used to check for IsSaleable and attach Ajax call to controls
function handleTabSelect(isTabClicked, queryString) {
    tabIdx = $("#hdnclas34").html();

		//show the instructional text and reset the drop down value to default in case the TAB is clicked
	if (isTabClicked == 'true') {
		if (tabIdx == 0) {
			$("[id$=divInstructionalTextAdult]").show();
			$("[id$=divInstructionalTextChildren]").hide();
			$("[id$=AdultLesson]").show();
			$(".AdultLessonSearchFilters").show();
			$(".adultLocationSearchResult").hide();
			$(".ChildLessonSearchFilters").hide();
			$(".childLocationSearchResult").hide();
			$(".divEmailPrintLinks").hide();
			$("[id$=divLessonResult]").hide();
			$(".divLessonFilter").hide();
		} else if (tabIdx == 1) {
			$("[id$=divInstructionalTextAdult]").hide();
			$("[id$=divInstructionalTextChildren]").show();
			$("[id$=AdultLesson]").show();
			$(".ChildLessonSearchFilters").show();
            $(".childLocationSearchResult").hide();
			$(".AdultLessonSearchFilters").hide();
			$(".adultLocationSearchResult").hide();
			$(".divEmailPrintLinks").hide();
			$("[id$=divLessonResult]").hide();
			$(".divLessonFilter").hide();
		    }
		}

		//Reset dropdown to show first item selected by default
	$('.sortingParam ul li select').attr('selectedIndex', 0);

    var isSaleable = null;
    switch (tabIdx) {
        case "0":
            isSaleable = $(":hidden").filter(".AdultLessaonIsSaleable").val();
			if (isSaleable.toLowerCase() == "true") {
                $("#tab1.tabsContentContainer").addClass("tabs-show");
                $("#tab1 .sortingParam, #ajaxContentContainer, .lessonsExplorerFilterContainer, .divInstructionalTextAdult, .AdultLessonSearchFilters").show();
                $("[id$=divSaleLocationsAdult],[id$=divCategoriesAdult],[id$=hrefMapAdult]").show();
                $("[id$=divSaleLocationsChildren],[id$=divCategoriesChildren],[id$=hrefMapChildren],[id$=divInstructionalTextChildren]").hide();
				ajaxTabInit(isTabClicked, queryString);
            } else {
                $(" #ajaxContentContainer, .lessonsExplorerFilterContainer, .AdultLessonSearchFilters, .adultLocationSearchResult").hide();
                $("[id$=divInstructionalTextAdult]").show();
                $("[id$=divInstructionalTextChildren]").hide();
            }
            break;
        case "1":
            isSaleable = $(":hidden").filter(".ChildLessonIsSaleable").val();
			if (isSaleable.toLowerCase() == "true") {
            $("#tab1.tabsContentContainer").addClass("tabs-show");
                $("#tab1 .sortingParam, #ajaxContentContainer, .lessonsExplorerFilterContainer, .divInstructionalTextChildren, .ChildLessonSearchFilters").show();
                $("[id$=divSaleLocationsAdult],[id$=divCategoriesAdult],[id$=hrefMapAdult],[id$=divInstructionalTextAdult]").hide();
                $("[id$=divSaleLocationsChildren],[id$=divCategoriesChildren],[id$=hrefMapChildren]").show();
				ajaxTabInit(isTabClicked, queryString);
            } else {
                $(" #ajaxContentContainer, .lessonsExplorerFilterContainer, .ChildLessonSearchFilters, .childLocationSearchResult").hide();
                $("[id$=divInstructionalTextChildren]").show();
                $("[id$=divInstructionalTextAdult]").hide();
            }

            break;
        case "2":
            isSaleable = $(":hidden").filter(".PrivateLessaonIsSaleable").val();
			if (isSaleable.toLowerCase() == "true") {
                $(".lessonsExplorerFilterContainer").hide();
                $(".privateLessonsExplore").show();
            } else {
                $(".privateLessonsExplore, .lessonsExplorerFilterContainer").hide();
            }

            staticTabInit();
            break;
        default:
    }
}

// Bind Ajax calls to filter controls
function ajaxTabInit(isTabClicked, queryString) {
    var selSortBy = $("select.ddlSort");
    var selSortById = selSortBy.attr("id");
    var tabIdx = $("#hdnclas34").html();

	if (isTabClicked == 'true') {
        $('.hdnTabSelectedValue').val($("#hdnclas34").html());

		ApplyDataFilter(isTabClicked, queryString, true);
    }
	else if (queryString != '' && queryString.indexOf('~') != -1 && $('.hdnTabSelectedValue').val() == '') {

        $(".AdultLessonSearchFilters").hide();
        $(".ChildLessonSearchFilters").hide();
    }

     //Set firstPageLoad to 1 in case of ajax call.
	if (firstPageLoad == 1) {
		firstPageLoad = 0;
     }

    //Ajax Call to the Group Lesson Service on click on Search button
	$("[id$=updateClassList]").unbind("click").bind("click", function () {

            //Reset slider control on ajax call
		if ($("#numberOfDaysLessonsSlider").length > 0) {
			$("#numberOfDaysLessonsSlider").slider("values", 0, 1);

			if ($('#heavenly').length > 0) {
				minNoOfDays = 1;
				maxNoOfDays = 5;
                } else {
				minNoOfDays = 0;
				maxNoOfDays = 6;
                }

			$("#numberOfDaysLessonsSlider").slider("values", minNoOfDays, maxNoOfDays);
            }

		if ($("#numberOfDaysRentalSlider").length > 0) {
			$("#numberOfDaysRentalSlider").slider("values", 0, 1);

			if ($('#heavenly').length > 0) {
				minNoOfDays = 1;
				maxNoOfDays = 5;
                } else {
				minNoOfDays = 0;
				maxNoOfDays = 6;
                }

			$("#numberOfDaysRentalSlider").slider("values", minNoOfDays, maxNoOfDays);
            }
    
		ApplyDataFilter('false', queryString, true);
	});

    //Ajax Call to the Group Lesson Service on click of sales location radio button
	$(".saleLocation fieldset div:visible input:radio").unbind("click").bind("click", function () {
		ApplyDataFilter('false', queryString, true);
    });

    //AJAX Call to add purchased items to CART
	$("[id$=btnAdultContinue]").unbind("click").bind("click", function () {
    //first validate the selected category and then load the results
		if (validate('false')) {
			if (IsDateSelected()) {
				ShowResultsView('false', queryString, true);
			} else {
				$("<li>" + "Select a start date" + "</li>").appendTo(" .summary ul");
            $(" .summary").show();
				window.scrollTo(0, $(" .summary").offset().top); // to setfocus on error messgae
            return false;
        }
    }
    });

    //AJAX Call to add purchased items to CART
	$("[id$=btnChildContinue]").unbind("click").bind("click", function () {
    //first validate the selected category and then load the results
		if (validate('false')) {
			if (IsDateSelected()) {
				ShowResultsView('false', queryString, true);
			} else {
				$("<li>" + "Select a start date" + "</li>").appendTo(" .summary ul");
            $(" .summary").show();
				window.scrollTo(0, $(" .summary").offset().top); // to setfocus on error messgae
            return false;
        }
    }
    });

    //AJAX Call to add purchased items to CART
	$("$[id=btnAddToCartContinue]").unbind("click").bind("click", function () {
		if ($("#droppable ul li").length > 1) {
		var thisButton = $(arguments.callee.caller.arguments[0].target);
		$("<img src='/VailResorts/sites/global/assets/img/blank.gif' alt='' class='buttonLayer' />").prependTo(thisButton.parent());
		$(".buttonLayer").css("width", ($(thisButton).width() + 30));
		$(".buttonLayer").css("left", $(thisButton).position().left);
		$(".buttonLayer").css("height", ($(thisButton).height() + 5));
	}

     var fullURL = parent.document.URL;
     var queryString = '';
     var searchStr = 'search=';

		if (fullURL.toLowerCase().indexOf(searchStr) != -1) {
        queryString = fullURL.substring(fullURL.indexOf(searchStr), fullURL.length);
    }

        AddPurchaseItemsToCart(queryString);
    });

    //Ajax Call to the Group Lesson Service on change of Sort Drop down
	selSortBy.unbind("change").bind("change", function () {
		ApplyDataFilter('false', queryString, false);
    });

    //AJAX Call to add purchased items to CART
	$("#divbtnStartOver").unbind("click").bind("click", function () {
        RedirectOnStartOver();
    });
}

function IsDateSelected() {
	if ($("table.PreviousMonthCalendarClass td.state-selected").length > 0) {
        return true;
	} else if ($("table.NextCalendarClass td.state-selected").length > 0) {
        return true;
	} else {
        return false;
	}
}

function RedirectOnStartOver() {
    var URL = '';
    if ($('.hdnlessonExplorerPageURL').length > 0) {
        URL = $('.hdnlessonExplorerPageURL').val();
        }

        tabIdx = $("#hdnclas34").html();

        URL = URL + tabIdx;
	document.location.href = URL;
}

//Set private lesson control parameters
function staticTabInit() {

    //artf1007946 fixed --Vipin
    //Width retrieved from sitecore and set at modal window.

    //Start
    var w = '';
    if ($('[id$=hidMapDimension]').length > 0) {
        w = Number($('[id$=hidMapDimension]').val().split(',')[0]);
    }

    if (w >= 800 || w == '') {
        w = 800;
    }

    $('.openMapDiv').dialog({
        bgiframe: true,
        autoOpen: false,
        width: w,
        modal: true,
        resizable: false,
        position: 'center',
        closeOnEscape: true
    });

	$('.viewMapModal').unbind("click").bind("click", function (e) {
        e.preventDefault();
        var url = $(this).attr('href');
        $(".openMapDiv img").
    	attr("src", url).
    	attr("width", w - 20);
		$('.openMapDiv').css('text-align', 'center');
    	$('.openMapDiv').dialog('open');
        return false;
    });
    //End

    // show & hide persons age input by select
	$('[id$=personsIncluded]').unbind("change").bind("change", function () {
        var numberOfPersons = $('[id$=personsIncluded] option:selected').val();
        if (numberOfPersons == 0) {
            $('#personsAge').hide();
        }
        else {
            $('#personsAge').show();
        }
        $("#personsAge .agesOfPeople li").removeClass('personDisplay').hide();
        $("#personsAge .agesOfPeople li:lt(" + numberOfPersons + ")").addClass('personDisplay').show();
    })

    if ($(".lessonTypeModal").length == 0) {
        $(".lessonTypesRadioContainer").append('<div class="lessonTypeModal hideDiv"></div>');

        //Setting up the Lesson Type More Info modal window 
        $('.lessonTypeModal').dialog({
            bgiframe: true,
            autoOpen: false,
            width: 500,
            modal: true,
            resizable: false,
            position: 'center',
            closeOnEscape: true
        });
    }

    // Handle "Lesson Type More Info" modal window
	$('.lessonTypesDays a').unbind("click").bind("click", function () {
        // grabs url from href and loads it into the modal window
        var urlContent = $(this).attr('href');
		$('.lessonTypeModal').dialog('close').load(urlContent, function () {
            $('.lessonTypeModal').dialog('open');

        });
        return false;
    });
}

function AttachResultsFilterEvents() {
      //Ajax Call to the Group Lesson Service on click of display category radio button
    var rdoListSeasons = $(".displayCategory fieldset div:visible input:radio");
    rdoListSeasons.unbind("click").bind("click", function () {
    	rdoListSeasons.prop("checked", "");
    	$(this).prop("checked", "checked");
    	ApplyDataFilter('false', '', true);
    });

	$(".divEditButton div:visible input:button").unbind("click").bind("click", function () {
        EditSearchParameter();
    });
}

// Method to get parameters value for Ajax service
function ShowResultsView(isTabClicked, queryString, isValidation) {

	$(".AdultLessonSearchFilters").hide();
	$(".adultLocationSearchResult").hide();

	$(".ChildLessonSearchFilters").hide();
	$(".childLocationSearchResult").hide();

	$(".divLessonFilter").show();
	$(".divEmailPrintLinks").show();
	$("#divLessonResult").show();

	var tabIdx = $("#hdnclas34").html();
	var startDate = $(".hdnStartDateClass").val();

	var salesLocationId = $('.hdnSelectedRPOSSaleLocationID').val();
	var displayCategoryId = $(".hdnSelectedRPOSCategoryID").val();
	if (tabIdx == 1) {
		noofdaysLessons = $("[id$=ddlLessonDays]").val();
		noofdaysRental = $("[id$=ddlRentalDays]").val();
	}

	GetClassDetails('false', tabIdx, null, null, startDate, queryString, salesLocationId, displayCategoryId);

	$.ajax({
		type: "POST",
		url: "/vailresorts/sites/PlanningAndBooking/WebServices/GroupLessons.svc/GetGroupLessonFilters",
		data: '{"startDate" : "' + startDate + '","classType" : "' + tabIdx
            + '","salesLocationId" : "' + salesLocationId
            + '","displayCategoryId" : "' + displayCategoryId + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		async: false,
		success: function (msg) {
				$("#groupLessonDynamicFilter").html(msg.d);
				AttachResultsFilterEvents();
				attachFilterEvents();
		}
	});
}

function BindLocationDropdown(isTabClicked) {
	var tabIdx = $("#hdnclas34").html();

	$.ajax({
		type: "POST",
		url: "/vailresorts/sites/PlanningAndBooking/WebServices/GroupLessons.svc/BindLocationDropdown",
		data: '{"classType" : "' + tabIdx + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		async: false,
		success: function (msg) {
			setTimeout(function () {
				$("#divSalesLocation").html(msg.d);
			}, 1000);
		}
	});

}

// Method to get parameters value for Ajax service
function ApplyDataFilter(isTabClicked, queryString, isValidation) {
	if ($.trim($("ul.filterTripDetail input").val()).length > 0) {
		$(".hdnStartDateClass").val($.trim($("ul.filterTripDetail input").val()));
	}

	var tabIdx = $("#hdnclas34").html();
	var startDate = $(".hdnStartDateClass").val();

	var salesLocationId = $('.hdnSelectedRPOSSaleLocationID').val();
	var displayCategoryId = $('.displayCategory fieldset div:visible input:radio:checked').val();
	$('.hdnSelectedRPOSCategoryID').val($('.displayCategory fieldset div:visible input:radio:checked').val());

	GetClassDetails(isTabClicked, tabIdx, null, null, startDate, queryString, salesLocationId, displayCategoryId);
}

//Function Name : GetClassDetails
//Purpose : This function is used to load a group lesson results into an ajax container.
//Parameters :
//          tabclicked  - Boolean, if tab is service call done on click of tab or change of dropdown
//          tabIndex - Tab ID currently selected for search criteria
//          sortFilterControl - sort dropdown
//          hdnTabTextControl - hidden control client ID to set instructional text based on selected tab
//          dropdowndefaultitem - Default value to be set for sort dropdown
//          startDate - StartDate of the lesson
//          queryString - querystring for email URL
//          numberOfDays - numberofDays filter value
//          salesLocationId - selected sales location radio button value
//          displayCategoryId - selected display category radio button value
function GetClassDetails(tabclicked, tabIndex, hdnTabTextControl, dropdowndefaultitem, startDate, queryString, salesLocationId, displayCategoryId) {

	// Set the Email Href value for Adult classes or children classes
	var url = $(".emailVacationLink").attr('href');
	var index = url.indexOf('lessontype=');

	if (index > 0) {
		var findString = url.substr(index + 11);
		var replaceString = tabIndex + "_separator_Search=" + startDate;
		var newurl = url.replace(findString, replaceString);
		$(".emailVacationLink").attr('href', newurl);
	}

	if (tabclicked == "true") {
		//Set the map URL in filter depending upon tab clicked
		if ($(".hdnViewAdultMapSrc").attr("value") != null && $(".hdnViewChildrenMapSrc").attr("value") != null) {
			if (tabIndex == 0) {
				$(".exploreLessonsLocationMap").attr("href", $(".hdnViewAdultMapSrc").val());
			} else if (tabIndex == 1) {
				$(".exploreLessonsLocationMap").attr("href", $(".hdnViewChildrenMapSrc").val());
		}
	}
	}

	//Clear the error message
	var divError = $(".noProduct");
	divError.html('');

	//Show loading icon on ajax call 
	$("#ajaxContentContainer").showLoading({ loadingStr: "Please wait a moment while we search for your results", autoFocus: false });
	
	$.ajax({
		type: "POST",
		url: "/vailresorts/sites/PlanningAndBooking/WebServices/GroupLessons.svc/GetGroupLessonResult",
		data: '{"startDate" : "' + startDate + '","classType" : "' + tabIndex
            + '","queryString" : "' + queryString + '","salesLocationId" : "' + salesLocationId
            + '","displayCategoryId" : "' + displayCategoryId
            + '","noofdaysLessons" : "' + noofdaysLessons + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		async: false,
		success: function (msg) {
				$("#ajaxContentContainer").html(msg.d);

				$(".selectThis").unbind('click').bind('click', function () {
					animateToTray($(this));
				});

				$(".linkSave").unbind('click').bind('click', function (e) {
					e.preventDefault();
					OpenSavetoTripModal($(this));
				});

				//Attach modal windows to data
				displaylessonsModal();
				//Attach drag drop events to data
				dragDropEvent();
				attachFilterEvents();
		},
		error: function (xhr, status, msg) {
			var errormsg = getErrorMessage(xhr, status, msg);

			if (errormsg == ' ') {
				errormsg = 'No results match your search criteria. Please revise your criteria to view results';
			}

			$("#ajaxContentContainer").html("<span class='errorMessage'>" + errormsg + "</span>");
		}
	});
}

function EditSearchParameter() {
            var tabIdx = $("#hdnclas34").html();
            var startDate = $(".hdnStartDateClass").val();
            var salesLocationId = $('.hdnSelectedRPOSSaleLocationID').val();
            var displayCategoryId = $('.hdnSelectedRPOSCategoryID').val();

        switch (tabIdx) {
        case "0":
           $(".AdultLessonSearchFilters").show();
           $(".adultLocationSearchResult").show();
           $(".divLessonFilter").hide();
           $(".divEmailPrintLinks").hide();
           $("#divLessonResult").hide();
        break;
        case "1":
           $(".ChildLessonSearchFilters").show();
           $(".childLocationSearchResult").show();
           $(".divLessonFilter").hide();
           $(".divEmailPrintLinks").hide();
           $("#divLessonResult").hide();
        break;
        default:
        }
}

//Function Name : filterNumberOfDays
//Purpose : This function is used to hide all the rows of data on screen that do not come in the given range of the No. of days slider
//Parameters : NA
function filterNumberOfDays() {
    var tabIdx = $("#hdnclas34").html();

    //if Adult Lesson is seleted then don't filter the data
	if (tabIdx > 0) {
    //set the slider for Lessons
        var lessonSliderVal = $("#numberOfDaysLessonsSlider").slider("value");
        var lessons = $("input[type='hidden'][title='lessondays'][value]");

        lessons.closest("li.draggable").hide();
        lessons.filter("[value='" + lessonSliderVal + "']").closest("li.draggable").show();

    //set the slider for Equipment Rentals
        var rentalSliderVal = $("#numberOfDaysRentalSlider").slider("value");
        var rentals = $("input[type='hidden'][title='rentaldays'][value]");

        rentals.closest("li.draggable").hide();
        rentals.filter("[value='" + rentalSliderVal + "']").closest("li.draggable").show();
    }
}

function addTicketToTrayFromSearchParameter() {
	var searchStr = 'search=';
    var sortByStr = '~';
    var fullURL = parent.document.URL.toLowerCase();
    var search;

	if (fullURL.indexOf(searchStr) != -1) {
		var extractURL = fullURL.substring(fullURL.indexOf(searchStr) + searchStr.length, fullURL.length);
		var hdnval = $(".txtSearchClass").val();

		if (hdnval != "") {
			searchCriteria = hdnval.toString().split(',');
        }

		var ticket = $("#hiddenDroppableLessonTemplate").clone().appendTo(".dropItem").attr("id", "");
	    var arrURL = extractURL.toString().split(',');

		if (arrURL.length > 1) {
	        var startDate = arrURL[0];
			var arrSKUTab = arrURL[1].toString().split(sortByStr);
	        var lessonID = arrSKUTab[0];
			var currentTabValue = extractURL.substr(extractURL.indexOf(sortByStr) + 1, 1);
	        var saleLocationId = $('.hdnSelectedRPOSSaleLocationID').val();
	        var lessonDays = arrURL[4];
            var rentalDays = (arrURL[5].split('~'))[0];
	        ticket.find("input[name='purchasedLessonID']").attr("value", lessonID + "|" + startDate + "|" + currentTabValue + "|" + saleLocationId + "|" + lessonDays + "|" + rentalDays);
	    }

	    ticket.find("input[name='SelectedDate']").val(searchCriteria[0]);
		ticket.find("input[name='SelectedSKU']").val(searchCriteria[1]);
	    ticket.find(".amount").html(searchCriteria[2]);
		ticket.find("h6").html(searchCriteria[3]);
		ticket.find(".iconDelete").click(function () {
		    $(this).parents("li").remove();
		});
	}
}

//Function Name : AddPurchaseItemsToCart
//Purpose : This function is used to Add the Purchased items to CART
//Parameters : NA
function AddPurchaseItemsToCart(querystring) {
	if ($("#droppable ul li").length <= 1) {
        var divError = $(".noProduct")
        var errorMsg = "<span id='lblErrorMessage' class='errorMessage'>Please complete the required fields:";
		errorMsg = errorMsg + "<ul><li>Purchase Tray</li></ul></span>";
        divError.html(errorMsg);

		return false;
	}

    var purchasedItems = [];
    //Add all the items from the Tray to an Array
	$(".boxData input[type='hidden'][name='purchasedLessonID']").each(function () {
        if (this.value != '') {
            purchasedItems.push(this.value);
        }
    });

    //Put the Comma Seperated Items in a String to pass to Webservice
    purchasedItems = purchasedItems.toString();

    $.ajax({
        type: "POST",
        url: "/vailresorts/sites/PlanningAndBooking/WebServices/GroupLessons.svc/AddPurchaseItemsToCart",
         async: false,
		data: "{\"purchaseItems\" : \"" + purchasedItems + '","queryString" : "' + querystring + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
		success: function (msg) {
			var response = msg.d;
			if (response.indexOf('http') >= 0) {
                   parent.window.location = msg.d;
			}
        },
		error: function (xhr, status, error) {
			handlePnB_Lessons_Error(xhr, status, error);
	    }
    });
}

//Function Name : addLessonToTray
//Purpose : This function is used to add the dragged lesson item to the tray
//Parameters : draggedObj - The object that has been dragged
function addLessonToTray(draggedObj) {
	var lesson = $("#hiddenDroppableLessonTemplate").clone().appendTo(".dropItem").attr("id", "");
	var lessonTitle = draggedObj.find("input[title='shortTitle']").attr("value");
	var lessonID = draggedObj.find("input[title='lessonID']").attr("value");
	var lessonPrice = $.trim(draggedObj.find(".amount").text());
	var saleLocationId = $('.hdnSelectedRPOSSaleLocationID').val();
	var startDate = $(".hdnStartDateClass").val();

	lesson.find("h6").html(lessonTitle);
	lesson.find(".amount").html(lessonPrice);

	var lessonDays = 1;
	if ($("#numberOfDaysLessonsSlider:visible").length > 0) {
		lessonDays = $("#numberOfDaysLessonsSlider").slider("value");
	}

	var rentalDays = 1;
	if ($("#numberOfDaysRentalSlider:visible").length > 0) {
		rentalDays = $("#numberOfDaysRentalSlider").slider("value");
	}

	//Get the value of the current selected tab
	var currentTabValue = $(".exploreLessonsByProduct .mainTabsPnB li").index($(".exploreLessonsByProduct .mainTabsPnB .tabs-selected")[0]);

	lesson.find("input[name='purchasedLessonID']").attr("value", [lessonID, startDate, currentTabValue, saleLocationId, lessonDays, rentalDays].join('|'));
	
	lesson.find(".iconDelete").click(function () {
		$(this).parents("li").remove();
		DeactiveRemoveLink();
	});

	if ($("#droppable ul li").length > 0) {
		var divError = $(".noProduct");
		divError.html('');
		ActiveRemoveLink();
	}
}

//Function Name : clearPurchaseTray
//Purpose : This function is used to clear all the items from the purchase tray
//Parameters : NA
function clearPurchaseTray() {
    $(".dropItem li").not("#hiddenDroppableLessonTemplate").remove();
    DeactiveRemoveLink();
}

function SaveToCart() {
	if ($("#droppable ul li").length <= 1) {
        var divError = $(".noProduct");
		var errorMsg = "<span id='lblErrorMessage' class='errorMessage'>Please select a product before proceeding.</span>";
        divError.html(errorMsg);
	}

	var hd = $("[id$='hdLessons']");
    hd.val("");

	$('.dropItem li:not(#hiddenDroppableLessonTemplate)').each(function (i) {
		if (hd.val() == '') {
           hd.val($(this).find('.boxData #purchasedLessonID').val());
		} else {
			hd.val(hd.val() + ',' + $(this).find('.boxData #purchasedLessonID').val());
        }
	});
	
	if (hd.val() == '') {
        return false;
	}

    return true;
}

function OpenSavetoTripModal(obj) {
	       var urlContent = obj.attr("href");

	        $('body > .ui-dialog .saveToTripDataDialog iframe')
		.attr('src', urlContent)
		.attr('width', '100%')
		.attr('height', '100%')
		.attr('scrolling', 'no');
	         $('body > .ui-dialog .saveToTripDataDialog').dialog('open');
}


//Function Name : displayContinueModal
//Purpose : This function is used to open modal window
//Parameters : NA
function displaylessonsModal() {
	if ($('body > .ui-dialog .saveToTripAdultChildDialog').length == 0) {
	    $('.saveToTripAdultChildDialog').dialog({
	       bgiframe: true,
		    autoOpen: false,
		    width: 960,
			height: 650,
		    modal: true,
		    resizable: false,
		    position: 'center',
		    closeOnEscape: true
	    });
	}

	$('.lessonsExplorerFilterContainer .linkRightAligned').unbind("click").bind("click", function (e) {
	    e.preventDefault();

        // Add the id's in the hidden variable by retrieving from bucket
        SaveToCart();

	    // Check if any item in purchase bucket, before attempting to save
		if ($("#droppable ul li").length <= 1) {
            var divError = $(".noProduct");
			var errorMsg = "<span id='lblErrorMessage' class='errorMessage'>Please select a product before proceeding.</span>";
            divError.html(errorMsg);

			return false;
		} else {
	        // grabs url from href and loads it into the modal window
			var hd = $("[id$='hdLessons']");
	        var hdnField = hd.val();
			var urlContent = $(this).attr('href') + "&ProductId=" + hdnField;

	       $('body > .ui-dialog .saveToTripAdultChildDialog iframe')
	            .attr('src', urlContent)
	            .attr('width', '100%')
	            .attr('height', '100%')
	            .attr('scrolling', 'no');
	        $('body > .ui-dialog .saveToTripAdultChildDialog').dialog('open');

            return false;
         }
	});
}

function handlePnB_Lessons_Error(xhr, status, error) {
	var errMsg = getErrorMessage(xhr, status, error);

    if ($(".loadingPlaceholder").length > 0) {
        $(".loadingPlaceholder").hide();
        $(".loadingPlaceholder").parent().html('<div class="largeGboxContainer"><span class="errorMessage">' + errMsg + '</span></div>');
	} else {
        $("#ajaxContentContainer").html('<div class="largeGboxContainer"><span class="errorMessage">' + errMsg + '</span></div>');
    }
}

function ActiveRemoveLink() {
	if ($("#droppable ul li").length > 0) {
		$(".linkClear").attr("href", "javascript:clearPurchaseTray();");
		$(".linkClear").attr("style", " ");
	    }
}

function DeactiveRemoveLink() {
	if ($("#droppable ul li").length == 1) {
		$(".linkClear").css("color", "#666");
		$(".linkClear").attr("href", "javascript: void(0);");
		$(".linkClear").css("cursor", "text");
		$(".linkClear").css("textDecoration", "none");
 }
}

function ChildCategoryChangeEvent() {
        var val = $(".ddlChildCategory").val();

	if (val.toLowerCase() != "select one" && $(".ddlChildCategory").find("option").eq(0).val().toLowerCase() == "select one") {
            $(".ddlChildCategory").find("option").eq(0).remove();
        }

       $('.hdnSelectedRPOSCategoryID').val($(".ddlChildCategory").val());
}

function AdultCategoryChangeEvent() {
        var val = $(".ddlAdultCategory").val();

	if (val.toLowerCase() != "select one" && $(".ddlAdultCategory").find("option").eq(0).val().toLowerCase() == "select one") {
            $(".ddlAdultCategory").find("option").eq(0).remove();
        }

         $('.hdnSelectedRPOSCategoryID').val($(".ddlAdultCategory").val());
}

function animateToTray(obj) {
	var clickedItem = obj.closest(".draggable");
	var animationObj = clickedItem.clone();
	var myParentContainer = obj.closest("ul");
	var positionX = clickedItem.offset().left + "px";
	var positionY = clickedItem.offset().top + "px";
	var purchaseTray = $(".dottedBoxTop").offset();
	var endPosX = purchaseTray.left - 180;
	var endPosY = purchaseTray.top + 60;

	animationObj.css({
		'position': 'absolute',
		'top': positionY,
		'left': positionX,
		'width': myParentContainer.width(),
		'z-index': 9999
	});

	animationObj.appendTo("body");
	animationObj.animate({
		'top': endPosY,
		'left': endPosX
	}, 1000, function () {
			window.setTimeout(function () { addLessonToTray(animationObj); }, 1);

		$(this).fadeOut(function () {
			$(this).remove();
		});
		}
	);
}
