﻿function handlePnBChildcareError(xhr,status, error)
{
    var errMsg = getErrorMessage(xhr, status, error);
    $("[id$='_exceptionMessageContainer']").removeClass("hide");
    $("[id$='_exceptionMessageContainer']").html('<div class="largeGboxContainer"><span class="errorMessage">' + errMsg + '</span></div>');
}

//script to open modal window for view map
$(document).ready(function() {

    if ($("input[id$=hdnIsChildcareSaleable]").val() == 'False') {
        $(".childCareRoundSection").addClass("hideDiv");
    }


    //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
    $('.imgChildcareNurseryMapModal').dialog({
        bgiframe: true,
        autoOpen: false,
        width: w,
        modal: true,
        resizable: false,
        position: 'center',
        closeOnEscape: true
    });
    
    displayPrivateLessonMap(w);   
    //alert($('[id$=drdLocation] option').length)
    if($('[id$=drdLocation] option').length==2)
    {
        $('[id$=drdLocation]').attr('selectedIndex', 1);        
        bindAgeOptions($('[id$=drdLocation]').attr('id'),$('[id$=drdageGroup]').attr('id'));
    }
    
 
});

//Function Name : displayPrivateLessonMap
//Purpose : This function is used to bind click even for opening modal window.
//Parameters : width of modal window
function displayPrivateLessonMap(w){
	$('[id$=hrefViewMap].viewMap').click(function(e) {
		e.preventDefault();
		// grabs url from href and loads it into the modal window
		var urlContent = $(this).attr('href');
		$(".imgChildcareNurseryMapModal img").attr("src", "").attr("src", urlContent).attr("width", w-20).load(function(){
			$('.imgChildcareNurseryMapModal').dialog('open');
		});
		//$('#iframeloadMap').attr('src',urlContent).attr('width','100%').attr('height','100%').attr('scrolling','auto');
		
		return false;
	})
};

//This function binds age group drop down with age group options obtained from Ajax call.
function bindAgeOptions(drdLocations,drdAgeGroup) {
    
    var value = $("#" + drdLocations).val();
    if (Number(value) > 0) {
        $.ajax({
            type: "POST",
            url: "/vailresorts/sites/PlanningAndBooking/WebServices/ChildcareNurseryService.svc/BindAgeGroupDropdown",
            data: "{\"childCareCenter\" : \"" + value + "\"}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                var ageOptions = msg.d.split(":");
                var ageDropDown = document.getElementById(drdAgeGroup);                
                ageDropDown.length = 0;
                for (var i = 0; i < ageOptions.length; i++) {
                    var ageOptionTextValue = ageOptions[i].split(",");
                    if (ageOptionTextValue[1] != undefined) {
                        var ageListItem = document.createElement("option");
                        ageListItem.text = ageOptionTextValue[0];
                        ageListItem.value = ageOptionTextValue[1];
                        ageDropDown.options.add(ageListItem);
                    }
                }
            },
            error: function(xhr, status, error) {
                handlePnBChildcareError(xhr,status, error);
            }   
        });
    }
    else {
        var ageDropDown = document.getElementById(drdAgeGroup);
        ageDropDown.length = 0;
        var ageListItem = document.createElement("option");
        ageListItem.text = "Select";
        ageListItem.value = "0";
        ageDropDown.options.add(ageListItem);
    }
}

//This is client side event handler for age group custom validator.
function ValidateAgeGroup(val, args) {
    if (Number((document.getElementById(val.controltovalidate)).value) > 0) {
        args.IsValid = true;
        return true;
    }
    else {
        args.IsValid = false;
        return false;
    }
}

//This is client side event handler for Location custom validator.
function ValidateLocation(val, args) {
    if (Number((document.getElementById(val.controltovalidate)).value) > 0) {
        args.IsValid = true;
        return true;
    }
    else {
        args.IsValid = false;
        return false;
    }
}

//this function adds selected dates by the user to a hidden field and makes an ajax call
//function GetChildCareProductsAjaxCall(controlId, strselectedDate, locationCode, ageGroupCategoryCode)
//{
//    if(strselectedDate.length > 0)
//    {
//        strselectedDate = strselectedDate + '|';
//    }

//    if(document.getElementById(controlId).value.length > 0)
//    {
//        if(document.getElementById(controlId).value.indexOf(strselectedDate) != -1)
//        {
//            document.getElementById(controlId).value = document.getElementById(controlId).value.replace(strselectedDate, '');
//        }
//        else
//        {
//            document.getElementById(controlId).value += strselectedDate;
//        }
//    }
//    else
//    {
//        document.getElementById(controlId).value = strselectedDate;
//    }

//    if(document.getElementById(controlId).value.length > 0)
//    {
//      GetChildCareNurseryProducts(document.getElementById(controlId).value, locationCode, ageGroupCategoryCode);
//    }
//    
//}

function GetChildCareNurseryProducts(locationCode, ageGroupCategoryCode) {
    $.ajax({
        type: "POST",
        url: "/vailresorts/sites/PlanningAndBooking/WebServices/ChildcareNurseryService.svc/GetChildcareNurseryProducts",
        data: "{\"locationCode\" : \"" + locationCode + "\",\"ageGroupCategoryCode\" : \"" + ageGroupCategoryCode + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $('#ChildCareTypeContainer').html(msg.d);
            GetEmailLinkURL(); 
        },
        error: function(xhr, status, error) {
            handlePnBChildcareError(xhr,status, error);
        } 
    });
}

function GetSelectedProducts(doRedirectToTripSummary) {
    
    var hiddenTxtBox = $(".childCareNursery [id$=hdnSelectedProducts]");
    var prodList = [];
    var qsParm = new Array();
    var prodGUIDInCart = "";
    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;
        }
    }

    if (qsParm['cartproductid'] != undefined) {
        prodGUIDInCart = qsParm['cartproductid'];
    }
    else {
        prodGUIDInCart = "";
    }
    
    $("#ChildCareTypeContainer .radioButtonList").each(function() {
        var key = $.trim($(this).find("h5").html().split(",")[1]);
        if ($(this).find(":radio").length > 0) {
            var value = $(this).find(":radio:selected").val();
            var name = "";
        } else {
            var value = $(this).find(":hidden:eq(0)").val();
            var name = $(this).find("label").html();
        }
        var price = $(this).find("span").html().split("$")[1];
        var strProd = key + "|" + value + "|" + price;
        if (name.length > 0) {
            strProd += "|" + name;
        }
        prodList.push(strProd);
    });
    
    hiddenTxtBox.val(prodList.join(","));

    if (hiddenTxtBox.val().length > 0) {
	
		/* KR - To prevent multi clicks on the button [begin] */
		//var thisButton = $(arguments.callee.caller.arguments[0].target);
		var thisButton = $(".continueRequest .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/ChildcareNurseryService.svc/AddProductsToCartAndRedirectToTripSummary",
            data: "{\"productDetails\" : \"" + hiddenTxtBox.val() + "\",\"redirectToTripSummary\" : \"" + doRedirectToTripSummary + "\",\"location\" : \"" + qsParm['location'] + "\",\"ageGroup\" : \"" + qsParm['agegroup'] + "\",\"cartProductGUID\" : \"" + prodGUIDInCart + "\"}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                document.location.href = msg.d;
            },
            error: function(xhr, status, error) {
                handlePnBChildcareError(xhr, status, error);
            }
        });
    }
   return (false);
}

