﻿/* Basket */

// Hide the button that replaces the add to shopping basket button after clicking it.
$(document).ready(function() { $("#replacementButton").hide(); });

// Gets a service proxy to the shopping basket service.
function GetBasketProxy() {
	return new ServiceProxy("/Shared/Services/ShoppingBasketService.svc/");
}

// Update the basket item count after the page is loaded.
//$(document).ready(function() {
//	GetBasketProxy().invoke("GetBasketItemCount", {},
//	function(numberOfItems) { $("#travelplannerItemCount").html(numberOfItems); });
//});

// Adds a bookable product to the shopping basket.
function AddBookableProductToBasket(sellableProductId, bookableProductId, clickedLink) {
	GetBasketProxy().invoke("AddBookableProductToShoppingBasket",
	{ sellableProductId: sellableProductId, bookableProductId: bookableProductId },
	function(message) { ShowBasketUpdate(message, clickedLink); });
}

// Adds a pickup location to the shopping basket.
function AddPickUpLocationToBasket(pickuplocationId, clickedLink) {
	GetBasketProxy().invoke("AddPickUpLocationToShoppingBasket",
	{ pickupLocationId: pickuplocationId },
	function(message) { ShowBasketUpdate(message, clickedLink); });
}

// Displays the added item animation in basket in the header.
function ShowBasketUpdate(numberOfItems, clickedLink) {
	$(".basketFilled").slideDown("2000", function() { setTimeout('$(".basketFilled").slideUp("4000");', 3000); });
	$("#travelplannerItemCount").html(numberOfItems);
	clickedLink.closest("div[class^='containerButton']").replaceWith($("#replacementButton").clone().show());
}

// Removes an item from the shopping basket.
function RemoveBasketItem(removeLink) {
	var lServiceRowToRemove = removeLink.closest('li');

	GetBasketProxy().invoke("RemoveItemFromShoppingBasket",
		{ id: lServiceRowToRemove.attr('itemId') },
		function(message) { BasketItemRemoved(message, lServiceRowToRemove); });
}

// Callback method used when an item is removed from the shopping basket.
function BasketItemRemoved(numberOfItems, serviceRowToRemove) {
	$("#travelplannerItemCount").html(numberOfItems);
	serviceRowToRemove.remove();
	
	// Display message when no items are left in the basket.
	if (numberOfItems == 0) {
		$(".noItemsPanel").toggle();
		$(".dragdropOverview").toggle();
	}
}

// Triggers a popup to set a remark on a basket item.
function EnterRemarkBasketItem(remarkLink) {
	var lServiceRowToRemark = remarkLink.closest('[itemId]');
	
	// Set the title.
	var lItemTitle = jQuery.trim($('.itemDescription', lServiceRowToRemark).text());
	$('#remarkItemTitle').text(lItemTitle);

	// Set the remark.
	$('#remarkItemText').val(decodeURIComponent(lServiceRowToRemark.attr('remark')));

	// Set the id.
	$('#remarkItemTitle').attr('itemId', lServiceRowToRemark.attr('itemId'));

	DisplayModelDialog('.overlayBackground', '.popupFormSpacing');
}

// Sumbits a new remark for a basket item.
function SubmitBasketItemRemark() {
	$('.overlayRemarkEnter').toggle(false);
	$('.overlayRemarkProcessing').toggle(true);
			
	var lNewRemark = $('#remarkItemText').val();
	var lItemId = $('#remarkItemTitle').attr('itemId');

	GetBasketProxy().invoke("SetItemRemark",
		{ id: lItemId, remark: lNewRemark },
		function(message) { SubmitBasketItemRemarkSuccess(lItemId, lNewRemark); },
		function(message) {
			new function() { $('.overlayRemarkProcessing').toggle(false); $('.overlayRemarkFailed').toggle(true); }
		});
}

// Callback method when the submit of a remark was succesfull.
function SubmitBasketItemRemarkSuccess(id, newRemark) {
	// Set the new remark on the li.
	$("[itemId='" + id + "']").attr('remark', encodeURIComponent(newRemark));
	// Hide the dialog.
	HideModelDialog('.overlayBackground', '.popupFormSpacing', function() { $('.overlayRemarkEnter').toggle(true); $('.overlayRemarkProcessing').toggle(false); });
}

// Updates the location of an item in the shopping basket.
function UpdateBasketItemPosition(id, prevId) {
	GetBasketProxy().invoke("UpdateItemPosition", { id: id, previousItemId: prevId });
}

// Adds or removes an additional item from the shopping basket.
function CheckAdditionalBasketItem(checkbox) {
	var lServiceToUpdate = checkbox.closest('tr');
	var lAdditionalServiceId = lServiceToUpdate.attr("itemId");

	if (checkbox[0].checked) {
		GetBasketProxy().invoke("AddAdditionalService", { id: lAdditionalServiceId },
			function(message) {
				$("#travelplannerItemCount").html(message);
				lServiceToUpdate.addClass('checked');
			},
			function() { checkbox[0].checked = false; });
	}
	else {
		GetBasketProxy().invoke("RemoveItemFromShoppingBasket", { id: lAdditionalServiceId },
			function(message) {
				$("#travelplannerItemCount").html(message);
				lServiceToUpdate.attr('remark', '');
				$('input', lServiceToUpdate).attr('value', '');
				lServiceToUpdate.removeClass('checked');
			},
			function() { checkbox[0].checked = true; });
	}
}

// Submit a new start or end date for an additional service in the shopping basket.
function SubmitAdditionalServiceDateTime(datetext, inputbox, startDate) {
	var lServiceToUpdate = $(inputbox).closest('tr');
	var lAdditionalServiceId = lServiceToUpdate.attr("itemId");

	GetBasketProxy().invoke("SetDateAdditionalService", { id: lAdditionalServiceId, dateTime: datetext, startDate: startDate },
	null, function() { $(inputbox).attr('value', ''); });
}

// Starts the date update mode of the travelplanner.
function StartChangeDatesTravelPlanner() {
	$('.dragdropOverview').addClass('edit');
}

// Ends the date update mode of the travelplanner.
function EndChangeDatesTravelPlanner() {
	// Add all added date change objects in a normal array.
	var lNonAssociativeDateChangeArray = new Array();
	for (var lKey in _DateChangeObjects) {
		lNonAssociativeDateChangeArray.push(_DateChangeObjects[lKey]);
	}

	GetBasketProxy().invoke("UpdateDateTravelPlannerItems", { changes: lNonAssociativeDateChangeArray },
		function(message) { EndChangeDatesTravelPlannerSuccess(message); });
}

// Clear the date change object and update all the date fields with the returned values.
function EndChangeDatesTravelPlannerSuccess(message) {
	_DateChangeObjects = new Object();
	$.each(message,
		function(index, item) {
			var lBasketItem = $("#dragdrop > li[itemId='" + item.Id + "']");
			$(".itemStartDate", lBasketItem).html(item.StartDateText);
			$(".itemEndDate", lBasketItem).html(item.EndDateText);
			$(".itemStartDateEdit > select:first", lBasketItem).val(item.StartMonthDropDownValue);
			$(".itemStartDateEdit > select:last", lBasketItem).val(item.StartDayDropDownValue);
			$(".itemEndDateEdit > select:first", lBasketItem).val(item.EndMonthDropDownValue);
			$(".itemEndDateEdit > select:last", lBasketItem).val(item.EndDayDropDownValue);
		}
	)
	$('.dragdropOverview').removeClass('edit');
}

// Create a list for date change object objects
var _DateChangeObjects = new Object();
var TravelPlannerDateChange = function(id, type, newValue) {
	this.Id = id;
	this.Type = type;
	this.Value = newValue;
}

// Event fired when a date has changed for a basket item.
function BasketItemDateChanged(type, dropdown) {
	var lServiceToUpdate = $(dropdown).closest('li');
	var lServiceId = lServiceToUpdate.attr("itemId");
	var lNewValue = dropdown.val();
	
	_DateChangeObjects[lServiceId + "|" + type] =
	new TravelPlannerDateChange(lServiceId, type, lNewValue);

	// Need to reset (disabled/enable) the day dropdown when changing month dates.
	if (type == 0 || type == 1) {
		var lDayDropDown = dropdown.next();
		if (lNewValue == '' && !lDayDropDown.attr("disabled")) {
			lDayDropDown.val('');
			lDayDropDown.attr("disabled", "disabled");
		}
		else if (lDayDropDown.attr("disabled")) {
			lDayDropDown.removeAttr("disabled");
		}
	}
}

/* Displays a model dialog for the given overlay and form */
function DisplayModelDialog(overlaySelector, formSelector) {
	var lOverlay = $(overlaySelector);
	var lForm = $(formSelector);

	lOverlay.height($(document).height());
	lForm.css({ 'left': ($(document).width() - lForm.width()) / 2 });
	lForm.css({ 'top': ($(document).scrollTop() + ($(window).height() - (lForm.height())) / 4) });
	lOverlay.toggle(true);
	lForm.fadeIn("def");
}

function HideModelDialog(overlaySelector, formSelector, callback) {
	$(formSelector).fadeOut("def", callback);
	$(overlaySelector).toggle(false);
}

/* Submit the send a friend data */
function SendAFriendSubmit(validationGroup, serviceUrl, clientIdSenderName, clientIdSenderEmail, clientIdRecieverEmail, clientIdMessage, itemKey) 
{
    if (Page_ClientValidate(validationGroup)) {
        SendAFriendDisplayPleaseWait();
        var lProxy = new ServiceProxy(serviceUrl + "/");
        lProxy.invoke("ProcessesSendAFriendRequest", 
        { sendAFriendData:
          {   
		    SenderName : $('#'+clientIdSenderName).val(),
		    SenderEmail: $('#' + clientIdSenderEmail).val(),
		    RecieverEmail: $('#' + clientIdRecieverEmail).val(),
		    Message: $('#' + clientIdMessage).val(),
	        ItemReferenceId : itemKey
           }
         },
		function(message) { SendAFriendRequestProcessed(message); });
    }
}

/*
Processes the result of the web service call
*/
function SendAFriendRequestProcessed(message)
{
  if (message)
      SendAFriendDisplaySuccess();
  else
		SendAFriendDisplayFailed();
}

/*
Display the please wait message
*/
function SendAFriendDisplayPleaseWait() {
  // SendAFriendPleaseWaitMessage
  $('.sendAFriendForm').toggle(false);
  $('.SendAFriendPleaseWaitMessage').toggle(true);
  $('.SendAFriendSuccessMessage').toggle(false);
  $('.SendAFriendFailedMessage').toggle(false);
}

/*
Display the success message
*/
function SendAFriendDisplaySuccess() {
	//SendAFriendSuccessMessage
	$('.sendAFriendForm').toggle(false);
	$('.SendAFriendPleaseWaitMessage').toggle(false);
	$('.SendAFriendSuccessMessage').toggle(true);
	$('.SendAFriendFailedMessage').toggle(false);
	SAFResetInitialValues();
}

/*
Display the failed message
*/
function SendAFriendDisplayFailed() {
	//SendAFriendFailedMessage
	$('.sendAFriendForm').toggle(false);
	$('.SendAFriendPleaseWaitMessage').toggle(false);
	$('.SendAFriendSuccessMessage').toggle(false);
	$('.SendAFriendFailedMessage').toggle(true);
}

/*
Reset all the visibilities
*/
function SendAFriendResetVisiblility() {
    $('.sendAFriendForm').toggle(true);
    $('.SendAFriendPleaseWaitMessage').toggle(false);
    $('.SendAFriendSuccessMessage').toggle(false);
    $('.SendAFriendFailedMessage').toggle(false);
}

function SAFResetInitialValues()
{
  if (SAFRecieverText != null && SAFRecieverClientId != null)
		$('#' + SAFRecieverClientId).val(SAFRecieverText);
		
	if(SAFMessageText != null && SAFMessageClientId != null)
		$('#' + SAFMessageClientId).val(SAFMessageText);
	
	if(SAFSenderEmailText != null && SAFSenderEmailClientId != null)
		$('#' + SAFSenderNameClientId).val(SAFSenderNameText);
	
	if(SAFSenderNameText != null && SAFSenderNameClientId != null)
		$('#' + SAFSenderEmailClientId).val(SAFSenderEmailText);
}

function SelectRouteSuggestionDayTab(index) {
	$('#routesuggestiontabs').tabs('select', 'program');
	$('#DayToDayProgramTabs').tabs('select', index);
}

function SelectHolidayDayTab(index) {
	$('#holidaytabs').tabs('select', 'program');
	$('#program').tabs('select', index);
}

/*
Begin Country Popups
*/
function GetSightSeeingProxy() {
	return new ServiceProxy("/Shared/Services/SightSeeingService.svc/");
}

// Adds a bookable product to the shopping basket.
function GetSightSeeing(itemId,targetDivId,contentId,popupId,path) 
{											
	//centering with css
	centerPopup("#"+popupId);
	//load popup
	loadPopup("#"+popupId);	
	
	GetSightSeeingProxy().invoke(
						"GetSightSeeing",
						{ itemKeyId: itemId, iconPath: path },
						function(result) 
						{																												
							var divSight = document.getElementById(targetDivId);							
							divSight.innerHTML = result;	
							document.getElementById(contentId).style.display = "block"; 																																																				
						});			
}

  //SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;

//loading popup with jQuery
function loadPopup(popupId){
	//loads popup only if it is disabled
	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopupIFrame").css({
		    "opacity": "0.7"
		});
		$("#backgroundPopup").show();
		$("#backgroundPopupIFrame").show();
		$(popupId).show();
		popupStatus = 1;		
	}
}

//disabling popup with jQuery
function disablePopup(popupId){		
	//disables popup only if it is enabled
	if(popupStatus==1){
		$(popupId).hide();
		$("#backgroundPopup").hide();
		$("#backgroundPopupIFrame").hide();
		$("#innerContent").text("Laden...");
		popupStatus = 0;
		// This is a IE8 hack to fix issue 9113: the div "button" had no marging-bottom when the popup is closed
		// setting the class name re-elavuates the css and the div is keeping its position
		$("#button")[0].className = ""; 
	}
}

var Browser = {
    Version: function() {
        var version = 999; // we assume a sane browser
        if (navigator.appVersion.indexOf("MSIE") != -1)
        // bah, IE again, lets downgrade version number
            version = parseFloat(navigator.appVersion.split("MSIE")[1]);
        return version;
    }
}

function UpdateBkgHeight() {
    if (Browser.Version() < 7) {
        $(document).ready(function() {
            $("#backgroundPopup").css({
                "height": $(document).height(),
                "width": $(document).width()
            });
            $("#backgroundPopupIFrame").css({
                "height": $(document).height(),
                "width": $(document).width()
            });
        });
    }
}

//centering popup
function centerPopup(popupId){
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;

	if (Browser.Version() < 7) {
	    UpdateBkgHeight();
	}
	var popupWidth = $(popupId).width();
	//centering
	$(popupId).css({
		"position": "absolute",
		"top": 350,
		"left": windowWidth/2-popupWidth/2
	});	
	
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){	  
	//LOADING POPUP
	//Click the button event!
	$("#button").click(function(){		
		//centering with css
		centerPopup("#popupCountry");		
		//load popup
		loadPopup("#popupCountry");
	});

	//CLOSING POPUP
	//Click the x event!
	$("#popupCountryClose").click(function(){
		disablePopup("#popupCountry");
	});	
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup("#popupCountry");
		}
	});

//CLOSING POPUP
	//Click the x event!
	$("#popupSightClose").click(function(){
		disablePopup("#popupSight");
	});	
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup("#popupSight");
		}
	});

});      
 


/*
End Country Popups
*/


/*Sight Seeing Links*/

function pleaseShow(sender){
	sender.children(".hideShowItem").slideToggle("fast");	
	sender.addClass("open");
		$("#linkShow").hide();
		$("#linkHide").show();
}
function pleaseHide(sender){
	sender.children(".hideShowItem").slideToggle("fast");		
	sender.removeClass("open");
	$("#linkHide").hide();
	$("#linkShow").show();		
}

/*End Sight Seeing Links*/

/*
SearchTextBox control (server code: see ANWB.Travelhome.TextSearch.SearchTextBox).
*/
function SearchTextBox(clientId, searchUrl, initialValue, resourceText) {
    this._SearchUrl = searchUrl;
    this._InitialValue = initialValue;
    this._ResourceText = resourceText;
    this._Element = document.getElementById(clientId);
}

SearchTextBox.prototype.focus = function() {
    if (this._Element != null) {
        if (this._Element.value == this._ResourceText) {
            this._Element.value = '';
            this._Element.style.color = '#091840';
        }
        else {
            this._Element.style.color = '#091840';
        }
    }
}

SearchTextBox.prototype.blur = function() {
    if (this._Element != null) {
        if (this._Element.value == '') {
            this._Element.value = this._ResourceText;
            this._Element.style.color = '#6b748c';
        }
    }
}

SearchTextBox.prototype.keyPress = function(event) {
    // FireFox: event.which, IE: event.keyCode
    var KeyCode = (event.which != null) ? event.which : event.keyCode;

    if (KeyCode == 13) {
        event.cancelBubble = true;
        event.returnValue = false;
        this.doSearch();
        return false;
    }
    return true;
}

SearchTextBox.prototype.doSearch = function() {
    if ((this._Element.value != "") && (this._Element.value != this._InitialValue)) {
        var SearchUrl = this._SearchUrl + this._Element.value;
        window.location = SearchUrl;
    }
}
/*
End of SearchTextBox control.
*/

function MenuSlideToggle(sender, container) {
    sender.parentNode.style.display = "none";
    container.addClass("open");
}