﻿/*
*******************************************************
****** CLIENT API OF THE FAVORITES-BOX *******
*******************************************************
*/

//this class represents the favorite-box
function FavoriteBox() {
	var self = this;
	
	//members
	this.ajaxServiceUrl = "";   
	this.isFavoritePanelCollapsed = true;
	this.contentHeight = 60;
	this.speed = 10;
	this.stepHeight = 10;
	this.divFavoriteBoxContentContainer = $("#divFavoriteBoxContentContainer");
	this.divFavoritePanelBottom = $("#FavoritePanelBottom");
	this.divFavoritesContentBlock = $("#divFavoritesContentBlock");
	this.animationIntervalID = null;
	this.scrollIntervalID = null;
	this.currentPage = 1;
	this.isScrolling = false;
	this.httpRequestObj = null;
	this.maxNumberOfElements = 20;
	this.season = 0;
	this.remoteCallResult = null;
	this.birdImagePath = "";
	this.txtAlertExistsInFavoriteBox = "";
	this.txtAlertMaximumFavoriteBox = "";
	this.isSearchResultPage = false;
	this.isFavoriteListPage = false;
	this.isMyCataloguePage = false;
	this.isSearchPanelPage = false;
	this.isTellAFriendPage = false;
	this.yesButtonText = "";
	this.noButtonText = "";
	this.birdIsFlying = false;
	this.comparePageUrl = "";
	this.isAddingProcessRunning = false;
	this.btnViewListUrl = "";
	this.btnMyBrochureUrl = "";
	this.btnTellAFriendUrl = "";
	this.reportSuiteCode = "";
	this.emptyFavoritePictureUrl = "";
	this.btnDeleteUrl = "";
	this.birdLandedClear = "";
	this.lblAddFavorite = "";
	this.lblNotedFavorite = "";


	//expand/collapse the favorites panel
	this.SwitchFavoritePanel = function(SendToSiteCatalyst) {

	    if (self.isFavoritePanelCollapsed) {
	        //open the favorite list
	        $("#divFavoriteBoxContentContainer").slideDown(400, function(target) { return function() { target.OnFavoritePanelOpened(); }; } (self));
	        self.isFavoritePanelCollapsed = false;
	        //change the arrow
	        $("#lnkOpenFavoriteBox").attr("class", "SwitchFavoritePanel_close");

	        if (SendToSiteCatalyst) {
	            self.DoSiteCatalystCommand("View");
	        }

	        if (self.isSearchResultPage)
	            document.cookie = "IsFavoriteBoxCollapsed=no;";
	    }
	    else {
	        //close the favorite list
	        $("#divFavoriteBoxContentContainer").slideUp(400);
	        self.isFavoritePanelCollapsed = true;
	        //change the arrow
	        $("#lnkOpenFavoriteBox").attr("class", "SwitchFavoritePanel_open");


	        if (self.isSearchResultPage)
	            document.cookie = "IsFavoriteBoxCollapsed=yes;";
	    }

	    return false;
	}

	//this function is called when the favorites panels scrolls down and reached the end position
	this.OnFavoritePanelOpened = function() {
	if (self.GetNumberOfFavorites() == 0 && self.isSearchResultPage && self.isAddingProcessRunning == false) {
			self.ShowIntroduction1();
			self.SetScrollBtnVisibility("right", false);
		}
		else if (self.GetNumberOfFavorites() == 0 && self.isAddingProcessRunning == false) {
			self.ShowIntroduction2();
			self.SetScrollBtnVisibility("right", false);
		}
		else
			self.SetScrollBtnVisibility("right", true);
	}

	//starts the scroll animation
	this.Scroll = function(direction) {
		//preparing before scrolling
		if (self.isScrolling)
			return false;


		self.isScrolling = true;

		if (direction == "right") {
			if (self.GetFavoritesContentBlockLeft() == 0) {
				return false;
			}

			$("#divFavoritesContentBlock").animate({ "left": "+=" + self.GetScrollDistancePerPage() + "px" }, "slow", function(target) { target.isScrolling = false; } (self));
		}
		else {

			if (self.currentPage == 5) {
				return false;
			}


			$("#divFavoritesContentBlock").animate({ "left": "-=" + self.GetScrollDistancePerPage() + "px" }, "slow", function(target) { target.isScrolling = false; } (self));
		}

		//set the currentPage after scrolling
		if (direction == "right") {
			if (self.currentPage > 1)
				self.currentPage--;
		}
		else {
			if (self.currentPage < 5)
				self.currentPage++;
		}

		//handle the visibility of the scroll-buttons
		if (self.currentPage == 5)
			self.SetScrollBtnVisibility("right", false);
		else if (self.currentPage == 1)
			self.SetScrollBtnVisibility("left", false);
		else {
			self.SetScrollBtnVisibility("right", true);
			self.SetScrollBtnVisibility("left", true);
		}

		return false;
	}

	this.DoSiteCatalystCommand = function(command) {
		if (self.reportSuiteCode == "") {
			return;
		}

		try {
			var s = s_gi(self.reportSuiteCode);

			switch (command) {
				case "View":
					if (self.isFavoriteListPage)
						return;

					//alert("track view");
					s.linkTrackVars = "events";
					s.linkTrackEvents = "scView";
					s.events = "scView";
					s.tl(true, "o", "Short list - View");
					//alert("end track view");
					break;
				case "Add":
					s.linkTrackVars = "products,events";
					s.products = self.remoteCallResult.CountryCode.toUpperCase() + "-" + self.remoteCallResult.Region + ";" + self.remoteCallResult.AccommodationCode;

					if (self.remoteCallResult.NbrStoredFavorites == 1) //go here when its the first element in the favoritebox
					{
						//alert("track new");
						s.linkTrackEvents = "scOpen,scAdd";
						s.events = "scOpen,scAdd";
						s.tl(true, "o", "Short list - New");
						//alert("end track new");
					}
					else {
						//alert("track add one");
						s.linkTrackEvents = "scAdd";
						s.events = "scAdd";
						s.tl(true, "o", "Short list - Add");
						//alert("end track add one");
					}

					break;
				case "Delete":
					//alert("track delete");
					s.linkTrackVars = "products,events";
					s.linkTrackEvents = "scRemove";
					//alert(this.remoteCallResult.CountryCode.toUpperCase() + "-" + this.remoteCallResult.Region + ";" + this.remoteCallResult.AccommodationCode);
					s.products = self.remoteCallResult.CountryCode.toUpperCase() + "-" + self.remoteCallResult.Region + ";" + self.remoteCallResult.AccommodationCode;
					s.events = "scRemove";
					s.tl(true, "o", "Short list - Remove");
					//alert("end track delete");
					break;
			}
		}
		catch (ex) { }
	}

	//call this function, to verify that every function button
	//has the correct state(enabled or disabled)
	this.EnsureFunctionButtonState = function () {
		//first disable all function buttons
		var functionButtons = $("#heart a");
		functionButtons.eq(0).attr("class", "favoritePanelButtonInActive").removeAttr("href");
		functionButtons.eq(0).css('display', 'none');
		functionButtons.eq(1).attr("class", "favoritePanelButtonInActive").removeAttr("href");
		functionButtons.eq(1).css('display', 'none');
		functionButtons.eq(2).attr("class", "favoritePanelButtonInActive").removeAttr("href");
		functionButtons.eq(3).attr("class", "favoritePanelButtonInActive").removeAttr("href");




		if (self.GetNumberOfFavorites() > 0) {
			//enable following buttons: ViewList, MyCatalogue, TellAFriend
			functionButtons.eq(0).attr("class", "favoritePanelButtonActive").attr("href", self.btnViewListUrl);
			functionButtons.eq(2).attr("class", "favoritePanelButtonActive").attr("href", self.btnMyBrochureUrl);
			functionButtons.eq(3).attr("class", "favoritePanelButtonActive").attr("href", self.btnTellAFriendUrl);



			//enable the compare function button
			if (self.GetNumberOfFavorites() > 1) {
				functionButtons.eq(1).attr("class", "favoritePanelButtonActive").attr("href", "");
			}


			//disable some button on a special page
			var button = null
			if (self.isFavoriteListPage)
				button = functionButtons.eq(0);
			else if (self.isMyCataloguePage)
				button = functionButtons.eq(2);
			else if (self.isTellAFriendPage)
				button = functionButtons.eq(3);

			if (button != null) {
				button.attr("class", "favoritePanelButtonInActive");
				button.removeAttr("href");
			}
		}
	}

	//gets you the distance to scroll for one page
	this.GetScrollDistancePerPage = function() {
		var favoriteWidth = self.GetFavoriteObjectWidth();
		return (4 * favoriteWidth);
	}

	//gets the width of an single favorite object block
	this.GetFavoriteObjectWidth = function() {
		return $(self.divFavoritesContentBlock).children().eq(0).width();
	}

	//gets the current left position of the favorites content block
	this.GetFavoritesContentBlockLeft = function() {
		return $(self.divFavoritesContentBlock).position().left;
	}

	//sets the current left position of the favorites content block
	this.SetFavoritesContentBlockLeft = function(position) {
		$(self.divFavoritesContentBlock).css('left', parseInt(position) + "px");
	}

	//hide and show the right/left scroll button of the favorite-box
	this.SetScrollBtnVisibility = function(btnType, isVisible) {

		var divScrollButton = (btnType == "right") ? $("#divlnkMoveRight") : $("#divlnkMoveLeft");
		divScrollButton.find("a").css("display", ((isVisible) ? "block" : "none"));
	
	}


	//deletes the selected favorite from the list
	this.DeleteFavorite = function(param) {

		var selectedAccoCode = "";

		//ensure showing favorites
		self.ShowFavoriteThumbs();

		if (typeof (param) == "object") {
			//get all hidden field values
			hiddenFields = param.parentNode.getElementsByTagName("input");
			selectedAccoCode = hiddenFields[0].getAttribute("value");
		}
		else if (typeof (param) == "string") {
			selectedAccoCode = param;
		}

		//delete here the favorite on the server with an ajax call
		/********************************************************/
		if (selectedAccoCode != "") {
			self.FavoriteBoxRemoteCall("delete", selectedAccoCode);
		}



		return false;
	}

	//shows an message-box as an inline-element before the senderElement
	this.ShowMessage = function (senderElement, alertMessage, origin, aCode, isConfirmation) {

	    //if there is already an alert visible or active, then remove it
	    if ($("#favoriteItemAlert"))
	        $("#favoriteItemAlert").remove();

	    //create the alert within the DOM
	    if (origin == 'List') {

	        $(senderElement).before("<div id='favoriteItemAlert'>" + alertMessage + "</div>");
	        $("#favoriteItemAlert").css({ 'background-color': 'White', 'color': 'Black', 'padding': '5px', 'display': 'none', 'text-align': 'left', 'position': 'absolute', 'width': '230px', 'top': '-57px', 'border': 'solid 2px #C8D7EA' });

	    }
	    else if (origin == 'Map') {
	        $(senderElement).before("<div id='favoriteItemAlert'><b>" + alertMessage + "</b></div>");
	        $("#favoriteItemAlert").css({ 'background-color': 'White', 'color': 'Black', 'border': 'solid 2px #CDCDCD', 'padding-left': '5px', 'padding-right': '5px', 'display': 'none', 'text-align': 'left' });
	    }
	    else if (origin == 'ObjectDetailHeader') {
	        $(senderElement).before("<div id='favoriteItemAlert'>" + alertMessage + "</div>");
	        $("#favoriteItemAlert").css({ 'width': '285px', 'background-color': 'White', 'color': 'Black', 'display': 'none', 'text-align': 'left'
                                          , 'border': '1px solid #C8C8C8', 'padding': '5px 5px 5px 5px', 'margin-bottom': '10px'});
	    }

	    //append the yes and no buttons
	    if (isConfirmation)
	        $("#favoriteItemAlert").append("&nbsp;&nbsp;&nbsp;&nbsp;<b><a href='#' onClick=\"favoriteBox.DeleteFavorite('" + aCode + "'); $(this).parent().parent().eq(0).hide(); return false;\">" + self.yesButtonText + "</a>&nbsp;&nbsp;/&nbsp;&nbsp;<a href='#' onClick='$(this).parent().parent().eq(0).hide(); return false;'>" + self.noButtonText + "</a></b>");

	    //fade the alert               
	    $("#favoriteItemAlert").fadeIn(250);
	}

	//adds a favorite to the list
	this.AddFavorite = function (btnAddFavorite, aCode, pictureID, origin) {
	    if (self.birdIsFlying) {
	        return;
	    }

	    //show favorite thumbs
	    self.ShowFavoriteThumbs();

	    //check if the maximum of favorites is reached        
	    if (self.GetNumberOfFavorites() == self.maxNumberOfElements) {
	        if (self.isFavoritePanelCollapsed)
	            self.SwitchFavoritePanel(false);

	        self.ShowMessage(btnAddFavorite, self.txtAlertMaximumFavoriteBox, origin, aCode, false);
	        return;
	    }

	    //check if the new favorite already exists in the list
	    if (self.FavoriteBoxContains(aCode)) {
	        if (self.isFavoritePanelCollapsed)
	            self.SwitchFavoritePanel(false);

	        self.ShowMessage(btnAddFavorite, self.txtAlertExistsInFavoriteBox, origin, aCode, true);
	        return;
	    }


	    //show the right scroll arrow, because it was maybe unvisible during showing the introduction
	    self.SetScrollBtnVisibility("right", true);

	    self.isAddingProcessRunning = true;
	    self.remoteCallResult = null

	    //add here the favorite on the server with an ajax call
	    /********************************************************/
	    self.FavoriteBoxRemoteCall("add", aCode, pictureID);


	    //if the favorite-box is not already open, then open it
	    if (self.isFavoritePanelCollapsed)
	        self.SwitchFavoritePanel(false);

	    //ensure that there is a empty favorite, where the bird can fly to
	    self.JumpToFirstPageWithEmptyFavorites();

	    //let the bird fly to the favorite list
	    self.LetBirdFly(btnAddFavorite);

	    self.SwitchAddToFavoriteLinksStyle(aCode, "added");
	}

	//changes the style of the buttons, which are used when someone
	//adds an favorite to the list.
	this.SwitchAddToFavoriteLinksStyle = function(aCode, action) {

	    var addFavoriteButtons = null;


	    if (!aCode) {
	        addFavoriteButtons = $("a[onClick*='favoriteBox.AddFavorite']");
	        var accommodationInFavoriteBox = new Array();
	        var hiddenFieldAccommodations = $("#divFavoritesContentBlock div input");

	        if (hiddenFieldAccommodations == null)
	            return;

	        //get all favorites from the box
	        for (var i = 0; i < hiddenFieldAccommodations.length; i++) {
	            if (hiddenFieldAccommodations.eq(i).attr('value') != '')
	                accommodationInFavoriteBox[i] = hiddenFieldAccommodations.eq(i).attr('value');
	        }



	        for (var i = 0; i < accommodationInFavoriteBox.length; i++) {
	            for (var x = 0; x < addFavoriteButtons.length; x++) {
	                var onClickString = String(addFavoriteButtons.eq(x).attr('onClick'));
	                if (onClickString.indexOf(accommodationInFavoriteBox[i]) != -1) {

	                    //set the link to already 'gemerkt', if the favorite is already in the FavoriteBox
	                    addFavoriteButtons.eq(x).html("<span class=\"ui-icon ui-icon-heart-red left ma003\"></span>" + this.lblNotedFavorite + " <strong class=\"x_delete\">x</strong>");
	                    addFavoriteButtons.eq(x).removeClass();
	                    addFavoriteButtons.eq(x).addClass("merkliste_remove");
	                }
	            }
	        }
	    }
	    else {
	        addFavoriteButtons = $("a[onClick*='favoriteBox.AddFavorite'][onClick*='" + aCode + "']");
	        if (action == 'delete') {
	            addFavoriteButtons.removeClass();
	            addFavoriteButtons.html("<span class=\"ui-icon ui-icon-heart left ma003\"></span>" + this.lblAddFavorite);           	            
	        }
	        else if (action == 'added') {
	            addFavoriteButtons.html("<span class=\"ui-icon ui-icon-heart-red left ma003\"></span>" + this.lblNotedFavorite + " <strong class=\"x_delete\">x</strong>");
	            addFavoriteButtons.removeClass();
	            addFavoriteButtons.addClass("merkliste_remove");	 	            
	        }
	    }
	}

	this.FavoriteBoxRemoteCall = function(command, aCode, pictureID) {


		//create the proxy for the ajax-call                
		var proxy = new ServiceProxy(self.ajaxServiceUrl);
		var webMethodeName = (command == "add") ? "AddToFavorites" : "DeleteFromFavorites";

		//create and populate the data-parameters
		var dataContainer = new Object();
		dataContainer.inputValues = {
			AccommodationCode : aCode,
			Season : self.season,
			PictureID : (pictureID) ? pictureID : 0
		};

	//invoke the webService
	var callBackSuccessfull = (command == "add") ? self.OnAddToFavoritesSuccessful : self.OnDeleteFromFavoritesSuccessful;
	var callBackError = (command == "add") ? self.OnAddFavoriteError : self.OnDeleteFavoriteError;
	proxy.invoke(webMethodeName,
							 dataContainer,
							 callBackSuccessfull,
							 callBackError);

}
	
	this.OnAddFavoriteError = function(error) {
		//alert("An error occurred, while adding favorite-item:\r\n" + error.Message);
	}
	
	this.OnDeleteFavoriteError = function(error) {
		//alert("An error occurred, while deleting favorite-item:\r\n" + error.Message);
	}

	this.OnGetFavoriteItemsError = function(error) {
		//alert("An error occurred, while getting favorite-items:\r\n" + error.Message);
	}

	//this is the callback function after getting the favorite items
	this.OnGetFavoriteItemsSuccessful = function(remoteCallResult) {

		//create all favorite items
		//alert("test");
		//alert($("#divFavoritesContentBlock"));
		$("#divFavoritesContentBlock").children().remove();
		for (var i = 0; i < remoteCallResult.length; i++) {
			//built the content string
			var favoriteItemContent = "";
			favoriteItemContent += "<div style=\"background-color:#EFEFEF; float:left; width:145px; margin:0px; padding:0px; text-align:center; position:relative;\">";

			var favoriteDesc = remoteCallResult[i].favoriteDesc;
			if (favoriteDesc.length > 20)
				favoriteDesc = favoriteDesc.substr(0, 17) + "...";

			favoriteItemContent += "<div><span>" + favoriteDesc + "</span></div>";

			if (remoteCallResult[i].aCode == "")
				favoriteItemContent += "<a href=\"#\" onClick=\"return false;\">";
			else
				favoriteItemContent += "<a href=\"" + remoteCallResult[i].favoriteThumbUrl + "\">";


			if (remoteCallResult[i].favoriteThumbSrc != "") {
				favoriteItemContent += "<img src=\"" + remoteCallResult[i].favoriteThumbSrc + "\" id=\"imgFavoriteThumb\" style=\"width:40px; height:40px; border:none;\" alt=\"\"/>";
			}
			else {
				favoriteItemContent += "<img src=\"" + self.emptyFavoritePictureUrl + "\" id=\"imgFavoriteThumb\" style=\"width:40px; height:40px; border:none;\" alt=\"\"/>";
			}


			favoriteItemContent += "</a>";

			if (remoteCallResult[i].aCode == "")
				favoriteItemContent += "<a style=\"display:none\" onClick=\"favoriteBox.DeleteFavorite(this); return false;\" href=\"#\" class=\"FavoriteBoxBtnDelete\" id=\"lnkBtnDelete\">";
			else
				favoriteItemContent += "<a onClick=\"favoriteBox.DeleteFavorite(this); return false;\" href=\"#\" class=\"FavoriteBoxBtnDelete\" id=\"lnkBtnDelete\">";

			favoriteItemContent += "<img src=\"" + self.btnDeleteUrl + "\" border=\"0\">";
			favoriteItemContent += "</a>";
			if (remoteCallResult[i].aCode == "")
				favoriteItemContent += "<input type=\"hidden\" id=\"aCode\" />";
			else
				favoriteItemContent += "<input type=\"hidden\" id=\"aCode\" value=\"" + remoteCallResult[i].aCode + "\" />";

			favoriteItemContent += "</div>";

			//append it
			$("#divFavoritesContentBlock").append(favoriteItemContent)

		}

		self.SwitchAddToFavoriteLinksStyle();

		self.SetNumberOfFavoritesDisplay(self.GetNumberOfFavorites());

		self.SetScrollBtnVisibility("left", false);


		//make some preparing for the special pages
		if (self.isSearchResultPage) {
			if (self.GetNumberOfFavorites() == 0) {
				self.ShowIntroduction1();
				self.SetScrollBtnVisibility("right", false);
			}
			else {
				self.ShowFavoriteThumbs();
			}

			var makeSwitch = false;
			var isPanelCollapsedForUser = (document.cookie.indexOf('IsFavoriteBoxCollapsed=yes') >= 0) ? true : false;

			if (self.isFavoritePanelCollapsed != isPanelCollapsedForUser)
				makeSwitch = true;

			if (makeSwitch || document.cookie.indexOf('IsFavoriteBoxCollapsed') == -1)
				self.SwitchFavoritePanel(false);
		}
		else if (self.isMyCataloguePage) {
			if (self.GetNumberOfFavorites() == 0) {
				self.ShowIntroduction2();
				self.SetScrollBtnVisibility("right", false);
			}
			else
				self.ShowFavoriteThumbs();

			if (self.isFavoritePanelCollapsed)
				self.SwitchFavoritePanel(false);
		}
		else if (self.isFavoriteListPage || self.isTellAFriendPage) {
			if (self.GetNumberOfFavorites() == 0) {
				self.ShowIntroduction1();
				self.SetScrollBtnVisibility("right", false);
			}
			else
				self.ShowFavoriteThumbs();

			if (self.isFavoritePanelCollapsed)
				self.SwitchFavoritePanel(false);
		}
		else {
			if (self.GetNumberOfFavorites() == 0) {
				self.ShowIntroduction2();
				self.SetScrollBtnVisibility("right", false);
			}
			else {
				self.ShowFavoriteThumbs();
			}
		}

		self.EnsureFunctionButtonState();
	}

	//this is the callback function after the adding a favorite
	this.OnAddToFavoritesSuccessful = function(remoteCallResult) {


		if (!remoteCallResult.OK) {
			//alert(remoteCallResult.Error);
			return;
		}

		self.remoteCallResult = remoteCallResult;

		self.DoSiteCatalystCommand("Add");
	}

	//this is the callback function after delete a favorite
	this.OnDeleteFromFavoritesSuccessful = function(remoteCallResult) {

		self.remoteCallResult = remoteCallResult;

		//get favorite element to delete
		var favorites = self.GetFavoriteElements();
		var favoriteToDelete = null;
		for (var i = 0; i < favorites.length; i++) {
			if (favorites[i].getElementsByTagName("input")[0].getAttribute("value") == remoteCallResult.AccommodationCode) {
				favoriteToDelete = favorites[i];
			}
		}

		//add the removedFavorite empty at the end of the favorite-list
		/**************************************************************/
		//reset the detailLink
		$(favoriteToDelete).children("a").eq(0).attr("href", "#").one("click", function() { return false; });
		//clear the housname

		$(favoriteToDelete).find("span").html("&nbsp;");

		//change favorite to an empty image
		$(favoriteToDelete).find("img").eq(0).attr("src", self.emptyFavoritePictureUrl);

		//hide the delete button
		$(favoriteToDelete).find("a").eq(1).css("display", "none");

		//clear aCode hiddenfield
		$(favoriteToDelete).find("input").attr("value", "");

		//set the display
		self.SetNumberOfFavoritesDisplay(self.GetNumberOfFavorites());

		self.SwitchAddToFavoriteLinksStyle(remoteCallResult.AccommodationCode, "delete");


		if (self.isFavoriteListPage) {
			//delete in the normal list
			$(".ListObjectBoxInfoImage span:contains('" + remoteCallResult.AccommodationCode + "')").parent().parent().parent().remove();
			//delete in the thumbnail list below the map
			$("table[class='ThumbnailsPerPage'] tbody tr td span:contains('" + remoteCallResult.AccommodationCode + "')").parent().html('');
		}

		self.DoSiteCatalystCommand("Delete");

		self.EnsureFunctionButtonState();
	}

	this.FavoriteBoxContains = function(aCode) {
		var favorites = self.GetFavoriteElements();
		for (var i = 0; i < favorites.length; i++) {
			if (favorites[i].getElementsByTagName("input")[0].getAttribute("value") == aCode)
				return true;

		}

		return false;
	}

	//scroll to the first page with empty favorites on it
	this.JumpToFirstPageWithEmptyFavorites = function() {
		var favorites = self.GetFavoriteElements();

		var foundOnPage = 0;
		//find the first empty element and count the 
		for (var i = 0; i < favorites.length; i++) {
			if (i % 4 == 0)
				foundOnPage++;

			if (favorites[i].getElementsByTagName("input")[0].getAttribute("value") == null || favorites[i].getElementsByTagName("input")[0].getAttribute("value") == "" || favorites[i].getElementsByTagName("input")[0].getAttribute("value") == "&nbsp;")
				break;
		}

		//jump to this page
		self.SetFavoritesContentBlockLeft(((foundOnPage - 1) * self.GetScrollDistancePerPage()) * -1);

		//set the currentPage
		self.currentPage = foundOnPage;

		//reset scroll-buttons
		if (self.currentPage == 1) {
			self.SetScrollBtnVisibility("left", false);
			self.SetScrollBtnVisibility("right", true);
		}
		else if (self.currentPage == 5) {
			self.SetScrollBtnVisibility("right", false);
			self.SetScrollBtnVisibility("left", true);
		}
		else {
			self.SetScrollBtnVisibility("left", true);
			self.SetScrollBtnVisibility("right", true);
		}

	}

	//set the number of favorits in the heart-display
	this.SetNumberOfFavoritesDisplay = function(numberOfFavorites) {

		//var display = this.divFavoritePanelBottom.getElementsByTagName("strong");
		//display[0].innerHTML = numberOfFavorites;
		$(self.divFavoritePanelBottom).find('strong').html(numberOfFavorites);
	}

	//Get you the number of all favorites within the list
	this.GetNumberOfFavorites = function() {
		var favorites = self.GetFavoriteElements();

		var numbers = 0;
		for (var i = 0; i < favorites.length; i++) {
			var hiddenfield = $(favorites[i]).find('input');
			if (hiddenfield.attr("value") != null &&
                hiddenfield.attr("value") != "" &&
                hiddenfield.attr("value") != "&nbsp;") {
				numbers++;
			}
		}
		
		return numbers;
	}

	//gets all favorite elements
	this.GetFavoriteElements = function() {

		var favElements = $(self.divFavoritesContentBlock).children();
		return favElements;
	}

	//Initialize is loaded after the object was created
	self.Initialize = function() {
		self.BindFavorites();
	}

	//binds the favorite-item collection
	this.BindFavorites = function() {

		//create the proxy for the ajax-call                
		var proxy = new ServiceProxy(self.ajaxServiceUrl);
		var webMethodeName = 'GetItemsForFavoriteBox';

		//create and populate the data-parameters
		var dataContainer = new Object();

		//invoke the webService
		proxy.invoke(webMethodeName,
                         dataContainer,
                         self.OnGetFavoriteItemsSuccessful,
                         self.OnGetFavoriteItemsError);

	}

	//ensures that the thumbs are showed
	this.ShowFavoriteThumbs = function() {
		//alert("ShowFavoriteThumbs called");

		//hide introductions
		$("#idFavoritesIntroduction1").css("visibility", "hidden");
		$("#idFavoritesIntroduction1").css("display", "none");
		$("#idFavoritesIntroduction2").css("visibility", "hidden");
		$("#idFavoritesIntroduction2").css("display", "none");

		//show favorites
		$("#divFavoritesContentBlock").css("visibility", "visible");
		$("#divFavoritesContentBlock").css("display", "block");
	}

	//ensures that the text with meaning 'click on add to favorite button' appears
	this.ShowIntroduction1 = function() {
		//alert("ShowIntroduction1 called");

		//hide favorites and introduction
		$("#divFavoritesContentBlock").css("visibility", "hidden");
		$("#divFavoritesContentBlock").css("display", "none");
		$("#idFavoritesIntroduction2").css("visibility", "hidden");
		$("#idFavoritesIntroduction2").css("display", "none");

		//show introduction
		$("#idFavoritesIntroduction1").css("visibility", "visible");
		$("#idFavoritesIntroduction1").css("display", "block");
		$("#idFavoritesIntroduction1").css("text-align", "center");
	}

	//ensures that the text with meaning 'make a search and add you favorite here into the favorite-box' appears
	this.ShowIntroduction2 = function() {
		//alert("ShowIntroduction2 called");
		//hide favorits and introduction
		$("#divFavoritesContentBlock").css("visibility", "hidden");
		$("#divFavoritesContentBlock").css("display", "none");
		$("#idFavoritesIntroduction1").css("visibility", "hidden");
		$("#idFavoritesIntroduction1").css("display", "none");

		//show introduction
		$("#idFavoritesIntroduction2").css("visibility", "visible");
		$("#idFavoritesIntroduction2").css("display", "block");
	}

	//Shows all the favorites within the box on the compare-site
	this.CompareFavorites = function() {
		var favElements = self.GetFavoriteElements();
		var aCodes = new Array();
		for (var i = 0; i < favElements.length; i++) {
			if ($(favElements[i]).children("input").attr("value") != "")
				aCodes[i] = $(favElements[i]).children("input").attr("value");
		}

		if (aCodes.length < 2)
			return false;

		//open the compare-page to compare the favorite-objects 
		//alert("comparePageUrl=" + this.comparePageUrl + "&aCodes=" + aCodes.join(','));                
		if (aCodes.length != 0)
			window.open(self.comparePageUrl + "&aCodes=" + aCodes.join(','), "CompareWindow", "height=600, width=800, menubar=no, resizable=yes, scrollbars=yes, status=yes, location=yes");

		return false;
	}

	//lets the bird-icon flying to the favorite list
	this.LetBirdFly = function(btnAddFavorite) {
		//create the bird-object
		var birdManager = new BirdManager();
		var bird = birdManager.CreateBirdIcon(self.birdImagePath);

		var birdTargetElement = self.GetBirdTargetElement();


		//place the bird to the start position
		$(bird).offset({ top: $(btnAddFavorite).offset().top, left: $(btnAddFavorite).offset().left });


		var birdLocationX = $(bird).offset().left;
		var birdTargetLocationX = $(birdTargetElement).offset().left;
		var birdLocationY = $(bird).offset().top;
		var birdTargetLocationY = $(birdTargetElement).offset().top;


		var disX = Math.abs(birdLocationX - birdTargetLocationX);
		var disY = Math.abs(birdLocationY - birdTargetLocationY);


		//QUICK AND DIRTY ACHTUNG
		/************************/
		if (disY >= 2200)
			time = 3000;
		else if (disY >= 1900 && disY < 2200)
			time = 2500;
		else if (disY >= 1000 && disY < 1900)
			time = 2000;
		else if (disY >= 700 && disY < 1000)
			time = 1500;
		else
			time = 1000;
		/*************************/

		//let the bird fly   
		self.birdIsFlying = true;
		if (birdLocationX > birdTargetLocationX && birdLocationY > birdTargetLocationY)
			$(bird).animate({ "left": "-=" + disX + "px", "top": "-=" + disY + "px" }, time, function(target) { return function() { target.OnBirdLanded(target); }; } (self));
		else if (birdLocationX < birdTargetLocationX && birdLocationY < birdTargetLocationY)
			$(bird).animate({ "left": "+=" + disX + "px", "top": "+=" + disY + "px" }, time, function(target) { return function() { target.OnBirdLanded(target); }; } (self));
		else if (birdLocationX < birdTargetLocationX && birdLocationY > birdTargetLocationY)
			$(bird).animate({ "left": "+=" + disX + "px", "top": "-=" + disY + "px" }, time, function(target) { return function() { target.OnBirdLanded(target); }; } (self));
		else if (birdLocationX > birdTargetLocationX && birdLocationY < birdTargetLocationY)
			$(bird).animate({ "left": "-=" + disX + "px", "top": "+=" + disY + "px" }, time, function(target) { return function() { target.OnBirdLanded(target); }; } (self));
	}

	//gets the element, where to bird has to fly to
	this.GetBirdTargetElement = function() {

		var favorites = self.GetFavoriteElements();
		var emptyFavorite = self.GetFirstEmptyFavoriteFromList(favorites);
		return emptyFavorite.getElementsByTagName("img")[0];

	}

	//get the first empty favorite from a favorites-list
	this.GetFirstEmptyFavoriteFromList = function(favorites) {
		var foundOnPage = 0;
		//find the first empty element and count the page
		for (var i = 0; i < favorites.length; i++) {
			if (i % 4 == 0)
				foundOnPage++;

			if (favorites[i].getElementsByTagName("input")[0].getAttribute("value") == null || favorites[i].getElementsByTagName("input")[0].getAttribute("value") == "" || favorites[i].getElementsByTagName("input")[0].getAttribute("value") == "&nbsp;")
				return favorites[i];
		}

		return null;
	}

	//is called, when the bird has landed
	this.OnBirdLanded = function(favPanel) {
	    if (favPanel == null)
	        return;
	        
	    //when we have to wait too long for the asynchron webservice call (FavoritBox) due to performance problems, it can occur, that
	    //remoteCallResult is null, so we have to wait until the remoteCallResult contains the result
	    if (favPanel.remoteCallResult == null) {
	        //every half second the OnBirdLanded is called and will check again, if there is a result
	        birdLandedClear = setInterval("OnBirdLandedRetarded()", 500);
	    }
	    else {
	        //fade the bird out
	        if (self.isAddingProcessRunning) {
	            $("#divFlyBirdIcon").fadeOut(1000, function(target) { return function() { target.ShowAccommodationPicture(target); }; } (self));
	            self.isAddingProcessRunning = false;
	        }
	    }
	}

    //function used for retarding the Bird Landing Process: we need a result from the webserive in order to continue
	OnBirdLandedRetarded = function() {
	    if (self.remoteCallResult != null) {
	        clearInterval(birdLandedClear);
	        
	        //fade the bird out
	        if (self.isAddingProcessRunning) {
	            $("#divFlyBirdIcon").fadeOut(1000, function(target) { return function() { target.ShowAccommodationPicture(target); }; } (self));
	            self.isAddingProcessRunning = false;
	        }
	    }
	}

	this.ShowAccommodationPicture = function(favPanel) {
		//create the birdManager and remove the bird from the DOM
		var birdManager = new BirdManager();
		birdManager.RemoveBirdIcon();

		//show the accommodation thumb picture and show the delete button
		var emptyFavorite = favPanel.GetFirstEmptyFavoriteFromList(favPanel.GetFavoriteElements());

		var houseName = favPanel.remoteCallResult.HouseName;
		if (houseName.length > 20)
			houseName = houseName.substr(0, 17) + "...";
		emptyFavorite.getElementsByTagName("span")[0].innerHTML = houseName;

		emptyFavorite.getElementsByTagName("img")[0].setAttribute("src", favPanel.remoteCallResult.FavoritePictureUrl);
		emptyFavorite.getElementsByTagName("input")[0].setAttribute("value", favPanel.remoteCallResult.AccommodationCode);
		emptyFavorite.getElementsByTagName("a")[1].style.display = "inline";
		$(emptyFavorite).children("a").eq(0).removeAttr("onclick");
		$(emptyFavorite).children("a").eq(0).attr("href", favPanel.remoteCallResult.detailUrl);

		//increment the numbers within the heart-display
		favPanel.SetNumberOfFavoritesDisplay(favPanel.GetNumberOfFavorites())

		self.EnsureFunctionButtonState();

		self.birdIsFlying = false;
	}
}

//this class is responsible to to animate the fyling bird
function BirdManager() {
	//creates the bird icon within the DOM
	this.CreateBirdIcon = function(birdImagePath) {
		//create the container for the flying bird
		var birdIcon = $('<div></div>')
            .css({
            	width: "40px",
            	height: "40px",
            	position: "absolute",
            	left: "0px",
            	top: "0px"
            })
            .attr('id', 'divFlyBirdIcon');

		//append the flying bird image to the container            
		birdIcon.append(
            $('<img>').attr('src', birdImagePath)
        );

		//apend the flying bird container to the body
		$('body').append(birdIcon);

		return birdIcon[0];
	}

	//removes the bird icon from the DOM
	this.RemoveBirdIcon = function() {
		$('#divFlyBirdIcon').remove();
	}
};        


