﻿$(document).ready(function(){
 
 displaySaveToTripModal();
 
 AttachModalDialog(); 
 
 //attachSearchValidator();
 
 SetAgesOfPeople();
  
});

function SetAgesOfPeople(){
    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();
}

function attachSearchValidator(){
    $("[id$=btnSearch]").bind("click", function(e){
    var searchValidatorStatus=true;
    $(" label").removeClass("red");
     var Location = $("[id$=ddlMeetingLocation]");
        if ( $("[id$=ddlMeetingLocation] option").length > 1 && $(Location)[0].selectedIndex > 0 ){
                searchValidatorStatus=true;
                $(" #errRequired").html("").hide();
                $(Location).closest("li").find("label").removeClass("red");
        } else {
                $(" #errRequired").html("").hide();
                $("<p>Please complete the required fields:</p><ul></ul>").appendTo(" #errRequired");

                $("<li>" + $(Location).closest("li").find("label").html() + "</li>").appendTo(" #errRequired ul");  
                $(Location).closest("li").find("label").addClass("red");
                searchValidatorStatus=false;
                e.preventDefault();
                 $(" #errRequired").show();
                window.scrollTo( 0, $(" #errRequired").offset().top );// to setfocus on error messgae
        }
         return searchValidatorStatus;
    });
}

function GetPrivateLessonProductsDetails()
{
    var selectedsku="";
    var SKUList = [];
    var discipline = $(".topForm table[id$=Discipline] :checked").val();
    var saleLocation = $(".topForm select.selectMeetingLocation").val();
    var numPeople = $(".topForm select.selectPersonsIncluded").val();
    var productsku="";
    if (qsParm['sku']) {
    productsku = qsParm['sku'];
    }
    
    var checkRadio=$("#PrivateLessonsTypeContainer .radioButtonList ul li").find("input:radio").filter(':checked');
    if(checkRadio.length > 0)
    {
        checkRadio.each(function(){
            selectedsku=$(this).val();
    
            if(selectedsku!=""){
                SKUList.push(selectedsku);
            }
        });
        if(SKUList!="")
            selectedsku=SKUList.join(",");
        else 
            selectedsku="";
    }
    else
    {selectedsku="";}
                   
    $.ajax({
    type: "POST",
    url: "/vailresorts/sites/PlanningAndBooking/WebServices/PrivateLessonService.svc/GetPrivateLessonProducts",
    data: "{\"saleLocation\" : \""+saleLocation+"\",\"discipline\" : \"" + discipline + "\",\"productSKU\" : \"" + productsku+ "\",\"selectedSKU\" : \"" + selectedsku  + "\",\"numPeople\" : \""+numPeople  + "\"}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      $('#PrivateLessonsTypeContainer').html(msg.d); 
      AttachModalDialog();
      OpenMoreInfoModal();
      GetEmailLinkURL();      
    },
	error: function(xhr, status, error) {
		handlePnB_PrivateLessons_Error(xhr, status, error);
	}
  });
}

function checkValidations()
{
    var status=true;
    $(" #errRequired").html("").hide();
    $("<p>Please complete the required fields:</p><ul></ul>").appendTo(" #errRequired");

    $(".topForm .agesOfPeople .personDisplay").each(function() {
            if ($(this).find("input:text").val()=='')
            {
                $("<li>" + $(this).find("label").html() + "</li>").appendTo(" #errRequired ul");  
                $(this).find("label").addClass("red");
                status=false;
            }
            else
            {
                $(this).find("label").removeClass("red");
            }
        });
        
    //var Location = $(".topForm select.selectMeetingLocation");
    //if(Location.val()==0)
    //{
    //    $("<li>" + $(Location).closest("li").find("label").html() + "</li>").appendTo(" #errRequired ul");  
    //    $(Location).closest("li").find("label").addClass("red");
    //    status=false;
    //}
    //else
    //{
    //    $(Location).closest("li").find("label").removeClass("red");
    //}
    
    //if($("#PrivateLessonsTypeContainer").children().length == 0 || checkSelectedProducts() == false)
    //{
    //    $("<li>" + "Date and lesson type" + "</li>").appendTo(" #errRequired ul");  
    //    status=false;
    //} 

    if(!status)
    {
        $(" #errRequired").show();
        CheckAge();
        window.scrollTo( 0, $(" #errRequired").offset().top );// to setfocus on error messgae
        return false;
    }
    else if(!CheckAge())
    {
       return false;
    }
    else
        return true;
}

function GetSelectedProducts() 
{
if (checkValidations())
{
    var hiddenTxtBox = $(".privateLessonsExplore [id$=hdnSelectedProducts]");
    var prodList = [];
    var qsParm = new Array();
    var query = window.location.search.substring(1).toLowerCase();
    var parms = query.split('&');
    var prodIdInCart = '';
    var discipline = $(".topForm table[id$=Discipline] :checked").val();
    var meetingLocationid = $(".topForm select.selectMeetingLocation").val();
    var meetingLocationName = $("select.selectMeetingLocation option:selected").text();
    var personsIncluded = $(".topForm .personsIncluded select").val();
    var agesOfPeople = {};
    $(".topForm .agesOfPeople li").each(function() {
        agesOfPeople[$(this).attr("id")] = $(this).find("input:text").val();
    });
 
    var agesOfAdults = '';
    var i = 0;
    for (i = 1; i <= Number(personsIncluded); i++) {
        if ((Number(agesOfPeople["person" + i]) > 0)) {
            if (Number(agesOfAdults.length) > 0)
                agesOfAdults = agesOfAdults + ',' + agesOfPeople["person" + i];
            else
                agesOfAdults = agesOfPeople["person" + i];
        }
        else {
            if (Number(agesOfAdults.length) > 0)
                agesOfAdults = agesOfAdults + ',' + '0';
            else
                agesOfAdults = agesOfPeople["person" + i];
        }
    }
 
   
    for (var i = 0; i < parms.length; i++) {
        var pos = parms[i].indexOf('=');
        if (pos > 0) {
            var key = parms[i].substring(0, pos);
            var val = parms[i].substring(pos + 1);
            qsParm[key] = val;
        }
    }

    if (qsParm['cartproductid'] != undefined) {
        prodIdInCart = qsParm['cartproductid'];
    }
    else {
        prodIdInCart = "";
    }
    
    hiddenTxtBox.val(checkSelectedProducts());
	
	/* KR artf1041404 - To prevent multi clicks on the button  */
	if(checkSelectedProducts()){
		//var thisButton = $(arguments.callee.caller.arguments[0].target);
		var thisButton = $(".tripLinkAlign .continueButton");
		$("<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));
	}
    $.ajax({
        type: "POST",
        async: false,
        url: "/vailresorts/sites/PlanningAndBooking/WebServices/PrivateLessonService.svc/AddProductsToCartAndRedirectToTripSummary",
        data: "{\"selectedProductDetails\" : \"" + hiddenTxtBox.val() + "\",\"locationid\" : \"" + meetingLocationid + "\",\"locationName\" : \"" + meetingLocationName + "\",\"numberOfAdults\" : \"" + personsIncluded + "\",\"ages\" : \"" + agesOfAdults + "\",\"discipline\" : \"" + discipline + "\",\"cartProductGUID\" : \"" + prodIdInCart + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            document.location.href = msg.d;
        },
	    error: function(xhr, status, error) {
		    handlePnB_PrivateLessons_Error(xhr, status, error);
	    }
    });
    return (false);
}
}

function checkSelectedProducts()
{
var hiddenTxtBox = $(".privateLessonsExplore [id$=hdnSelectedProducts]");

var prodList = [];
  $("#PrivateLessonsTypeContainer .radioButtonList").each(function() {
        var startdate = $.trim($(this).find("h5").html().split(",")[1]);    
        var startdatetime = $.trim($(this).find("h6").html());
        var enddatetime = $.trim($(this).find("span.endDate").html());
        var LessonTime = $.trim($(this).find("span.LessonTime").html());
        var value="";
        var name="";
        var price="";
        if ($(this).find(":radio").length > 0) {
            value = $.trim($(":radio:checked", this).val());
            name = $.trim($(":radio:checked", this).siblings("span.product").html());
            price = $.trim($(":radio:checked", this).siblings("label").html().split("$")[1]);
        }      
        else if($(this).find(".noresults").hasClass("hideDiv")!=true){
        }  
        else {
            //value = $(".lessonTypesDays ul li input[type=hidden]").eq(0).val();
            price = $.trim($(this).find("label").html().split("$")[1]);
            name = $.trim($(this).find("span.product").html());
        }
        
        //if any product is not selected/found then don't add them in array
        //if(value!="" && price!="" && name!=""){
        if(price!="" && name!=""){
            prodList.push(startdate + "|" + startdatetime + "|" + enddatetime + "|" + price + "|" + name);
        }
    });
    hiddenTxtBox.val(prodList.join("~"));
    if(hiddenTxtBox.val()!=""){
        return hiddenTxtBox.val();
    }
    else{
        return false;
    }
}

function handlePnB_PrivateLessons_Error(xhr, status, error)
{
    var errMsg = getErrorMessage(xhr,status,error);
    $("#errRequired").html('<div class="largeGboxContainer"><span class="errorMessage">' + errMsg + '</span></div>');
}

/*********************
Function for reading querystring for Childcare nursery page
*********************/
var qsParm = new Array();
function GetQueryStringValues() {
    var query = window.location.search.substring(1).toLowerCase();
    var parms = query.split('&');
    for (var i = 0; i < parms.length; i++) {
        var pos = parms[i].indexOf('=');
        if (pos > 0) {
            var key = parms[i].substring(0, pos);
            var val = parms[i].substring(pos + 1);
            qsParm[key] = val;
        }
    }
}

function OpenMoreInfoModal()
{
    // Handle "Lesson Type More Info" modal window
   $('a.lessonMoreInfo').click(function(event) {
   event.preventDefault();
   var urlContent = $(this).next("input[type=hidden]").val();
   $('.MoreInfoContentWrapper').text(urlContent); 
   
   try {
        $('.lessonTypeModal01').dialog('open');
    } catch(e){}
   //$(".MoreInfoContentWrapper").gBox({ theme:"whiteBox"});
  });
}

function AttachModalDialog()
{
  if ( $('.lessonTypeModal01').length > 0 && $('body > .ui-dialog .lessonTypeModal01').length == 0 ){
      $('.lessonTypeModal01').eq(0).dialog({
      bgiframe: true,
      autoOpen: false,
      width: 500,
      modal: true,
      resizable: false,
      position: 'center',
      closeOnEscape: true
     });
 }
}


//Function Name : displaySaveToTripModal
//Purpose : This function is used to open modal window for Save to trip.
//Parameters : NA

function displaySaveToTripModal(){
    
    if ( $('.saveToTripDialog').length > 0 && $('body > .ui-dialog .saveToTripDialog').length == 0 ){
        $('.saveToTripDialog').eq(0).dialog({
	       bgiframe: true,
		    autoOpen: false,
		    width: 960,
		    height:450,
		    modal: true,
		    resizable: false,
		    position: 'center',
		    closeOnEscape: true
	    });
    }	
       
	$("[id$='lnkSaveToTrip']").unbind("click").bind("click", function(e) {
	    e.preventDefault();
        if (checkValidations())
        {
        
            var discipline = $(".topForm table[id$=Discipline] :checked").val();
            var locationid = $(".topForm select.selectMeetingLocation").val();
            var locationName = $("select.selectMeetingLocation option:selected").text();
            var personsCount = $(".topForm .personsIncluded select").val();
            
            // grabs url from href and loads it into the modal window
	        var urlContent = $(this).attr('href') + "&ProductDetails=" + GetProductDetails() + "&LocationId=" + locationid + "&LocationName=" + locationName + "&AdultsCount=" + personsCount + "&Ages=" + GetAges() + "&Discipline=" + discipline;   
	        $('.saveToTripDialog iframe')
	           .attr('src',urlContent)
	           .attr('width','100%')
	            .attr('height','100%')
	            .attr('scrolling','no');
    	        
            try {
                $('.saveToTripDialog').dialog('open');
             }catch(e){}
            return false;
        }
    })
  }


function GetProductDetails()
{
    var hiddenTxtBox = $(".privateLessonsExplore [id$=hdnSelectedProducts]");
    var prodList = [];
    var value;
    $("#PrivateLessonsTypeContainer .radioButtonList").each(function() {
        var startdate = $.trim($(this).find("h5").html().split(",")[1]);
        var startdatetime = $.trim($(this).find("h6").html());
        var enddatetime = $.trim($(this).find("span.endDate").html());
        var LessonTime = $.trim($(this).find("span.LessonTime").html());
        if ($(this).find(":radio").length > 0) 
        {
            value = $(this).find(":radio:checked").siblings("span.product").text();                                   
        } else 
        {
			// Get the product name from span            
            value = $.trim($(this).find("span.product").html());
        }
        if($(this).find("label").html()!=null)
        {
            var price = $(this).find("label").html().split("$")[1];
            prodList.push(startdate + "|" + startdatetime + "|" + enddatetime + "|" + value  + "|" + price + "|" + LessonTime);
        }
    });

    hiddenTxtBox.val(prodList.join("~"));
    
    return hiddenTxtBox.val();
}


function GetAges()
{
    var agesOfPeople = {};
    var personsCount = $(".topForm .personsIncluded select").val();
    $(".topForm .agesOfPeople li").each(function() {
        agesOfPeople[$(this).attr("id")] = $(this).find("input:text").val();
    });

    var agesOfAdults = '';
    var i = 0;
    for (i = 1; i <= Number(personsCount); i++) {
        if ((Number(agesOfPeople["person" + i]) > 0)) {
            if (Number(agesOfAdults.length) > 0)
                agesOfAdults = agesOfAdults + ',' + agesOfPeople["person" + i];
            else
                agesOfAdults = agesOfPeople["person" + i];
        }
        else {
            if (Number(agesOfAdults.length) > 0)
                agesOfAdults = agesOfAdults + ',' + '0';
            else
                agesOfAdults = agesOfPeople["person" + i];
        }
    }
    
    return agesOfAdults;
}

function SetUniqueRadioButton(nameregex, current)
{
   re = new RegExp(nameregex);
   
   for(i = 0; i < document.forms[0].elements.length; i++)
   {
      elm = document.forms[0].elements[i]
      
      if (elm.type == 'radio')
      { 
         if (re.test(elm.name))
         {
            elm.checked = false;
         }
      }
   }
   current.checked = true;
}


function CheckAge()
{
    var status=true;
    var isNum = 1;
    $(" #errAge").html("").hide();
        $("<p>You have entered the following invalid data:</p><ul></ul>").appendTo(" #errAge");

    $(".topForm .agesOfPeople .personDisplay").each(function() { 
            try
            {           
                if($(this).find("input:text").val().indexOf('.')  != -1)
                {
                $("<li>[ " + $(this).find("input:text").val() + " ] - Only integers should be entered." + "</li>").appendTo(" #errAge ul");  
                $(this).find("label").addClass("red");
                status=false;
                }
                else
                {
                    isNum = eval($(this).find("input:text").val()); 
                }
            }
            catch(Error)
            {                
                isNum = '';
            }           
            if ( isNum == '' ) // If not an integer
            {
                $("<li>[ " + $(this).find("input:text").val() + " ] - Only integers should be entered." + "</li>").appendTo(" #errAge ul");  
                $(this).find("label").addClass("red");
                status=false;
            }  
            else if ( isNum < 1 || isNum > 99 ) 
            {
                $("<li>[ " + $(this).find("input:text").val() + " ] - Only values between 1 and 99 are entered." + "</li>").appendTo(" #errAge ul");  
                $(this).find("label").addClass("red");
                status=false;
            }            
            else if ($(this).find("input:text").val()!='')
            {
               $(this).find("label").removeClass("red");
            }
        });
        
   
    if(!status)
    {
        $(" #errAge").show();
        window.scrollTo( 0, $(" #errAge").offset().top );// to setfocus on error messgae
        return false;
    }
    else
        return true;
}

