// disabled this on ONE behalf by wrapping in an uncalled method
// will stop 3 extra pages calls per page

function removeShortlistFunctionality() {
$(document).ready(SetupShortlist);

function SetupShortlist() {
    if ($.browser.msie) {
        _isIE = true;

        if ($.browser.version <= 6.0) {
            _isIE6 = true;

            var html =
		  "<iframe style=\"position: absolute; display: block; " +
		  "z-index: -1; width: 360px; height: 100%; top: 0; left: 0;" +
		  "filter: mask(); background-color: #ffffff; border:none; \"></iframe>";

            $("#shortlistContainer").append(html);
            $("#shortlistContainer").show();
            $("#shortlistContainer").hide();
        }
    }

    //If visitor arrives onto the "shortlist-home" page (which means user is
    //authenticated) and there are open short lists to save, save them straight
    //away
    //Other wise, just update the shortlist panel.
    if (window.location.href.indexOf("//shortlist-home") != -1 && GetOpenShortlist()) {
        jQuery.get("http://" + window.location.host + "//shortlist-ajax?epaction=savedms", function(data) {
            UpdateActiveShortlistPanel();
        });
    } else {
        UpdateActiveShortlistPanel();
    }
}

var shortlistCount = 0;
var shortlistItemsCount = 0;
var g_isLoggedIn = false;
var g_currentShortlistItems;
var _noShortlistOverviewMessage = "You have not yet created a shortlist.";
var _shortlistOverviewQuantityMessage = "There {quantity} in your shortlist.";
var _shortlistInstructionsUrl = "//my-shortlist-instructions";
var _defaultShortlistNameRegex = /^My Shortlist [0-9]+$/;
var _isIE6 = false;
var _isIE = false;

// sorry about this !
var g_pdfTypes = new Object();
g_pdfTypes["accommodation"] = "1";
g_pdfTypes["what-to-see-and-do/activities"] = "2";
g_pdfTypes["what-to-see-and-do/attractions"] = "3";
g_pdfTypes["what-to-see-and-do/entertainment"] = "3";
g_pdfTypes["what-to-see-and-do/shopping"] = "3";
g_pdfTypes["what-to-see-and-do/food-and-drink"] = "3";
g_pdfTypes["what-to-see-and-do/events"] = "3";
g_pdfTypes["what-to-see-and-do/tours-and-guided-tours"] = "3";
g_pdfTypes["what-to-see-and-do/search-results"] = "3";


var shortlistHeights = new Object();
shortlistHeights[0] = 0;
shortlistHeights[1] = 7;
shortlistHeights[2] = 14;
shortlistHeights[3] = 21.5;
shortlistHeights[4] = 29;

//Set the current shortlist on the server side
function setServerCurrentShortlist(shortlistID, successHandler) {
    jQuery.get("http://" + window.location.host + "//shortlist-ajax?epaction=loaddms&epkey=" + shortlistID, successHandler);
}

function StoreCurrentShortlist(id, successEventHandler) {
    //alert("Store current shortlist");
    $.cookie("currentShortlist", id, { path: "/" });

    //Also set the Current Shortlist on the Server Side, so that when fetching the "shortlist-current", it returns the correct one
    setServerCurrentShortlist(id, successEventHandler);
}

function GetCurrentShortlist() {
    //alert("Get current shortlist");
    return $.cookie("currentShortlist");
}

function StoreOpenShortlist(isOpen) {
    //alert("Stored open shortlist");
    $.cookie("openShortlist", isOpen, { path: "/" });
}

function GetOpenShortlist() {
    //alert("Get open shortlist: "+($.cookie("openShortlist") == "true"));
    if ($.cookie("openShortlist") == null)
        return false;
    else if ($.cookie("openShortlist") == "true")
        return true;
    else
        return false;
}

function InitShortList() {
    var timestamp = new Date();

    $("#shortlistIntro").hide();
    $("#shortlistTemp").hide();
    $("#shortlistSelect").hide();
    $("#shortlistItems").hide();
    $("#shortlistOptions").hide();
    $("#EmailForm").hide();
    $("#noItems").hide();

    if (g_isLoggedIn)
        $("#dataload").load("//shortlist-ajax?t=" + timestamp.getTime() + " #myShortlists", {}, LoadShortlists);
    else
        LoadShortlists();
}

function DisplayShortlist(visible) {
    //$("#shortlist").toggleClass("expanded");

    if (visible) //if REQUEST is to make it visible
    {
        $("#toggleShortlistLink").html("Loading Shortlist...");
        $("#toggleShortlistLink").click(null);
        SetIsLoggedIn();
        InitShortList();
    }
    else {
        //$("#closePanel").unbind("click").hide();
        //StoreOpenShortlist(false);

        $("#toggleShortlistLink").html("View Shortlist <img src='/images/shortlist/arrow_down.gif' alt='View Shortlist' />");

        $("#shortlistIntro").hide();
        $("#shortlistTemp").hide();
        $("#shortlistSelect").hide();
        $("#shortlistOptions").hide();
        $("#EmailForm").hide();
        $("#pleaseLogin").hide();
        $("#shortlistItems").hide();
        $("#shortlistContainer").animate({ height: "0px", width: "19em", opacity: "0", padding: "0em", margin: "0em" }, 500, function() {
            $(this).hide();
            $("#toggleShortlistLink").click(ToggleShortlist);
            $("#shortlistOverview").show();

            g_openingShortList = false;
        });
    }

    g_shortListOpen = visible;
}

function SetIsLoggedIn() {
    var resText;

    resText = $.ajax({ async: false, cache: false, url: "//shortlist-home" }).responseText;
    g_isLoggedIn = resText.indexOf("Shortlist Login") < 0;
}


//Method responsible for setting the Shortlist overview message.
//e.g. "There are n items in your shortlist"
//"hasAShortlist" = Boolean value refering to whether the user has at least one shortlist
//"numberOfItemsOnTheShortlist" = Value refering to the amount of itinerary items the user have on the current shortlist.
function SetShortlistOverviewMessage(hasAShortlist, numberOfItemsOnTheShortlist) {
    var shortlistObject = $("p#shortlistOverview");
    var shortlistMessage = "";

    if (!hasAShortlist) {
        shortlistMessage += _noShortlistOverviewMessage;
    } else {
        shortlistMessage += _shortlistOverviewQuantityMessage;

        if (numberOfItemsOnTheShortlist == 1) {
            shortlistMessage = shortlistMessage.replace("{quantity}", "is <span id='shortlistItemCount'>1</span> item");
        } else {
            shortlistMessage = shortlistMessage.replace("{quantity}", "are <span id='shortlistItemCount'>" + numberOfItemsOnTheShortlist + "</span> items");
        }
    }

    shortlistObject.html(shortlistMessage);

}

function DisplayLoading(visible) {
    if (visible) //if request is to make it visible
    {
        $("#shortlistContainer").css("background", "url(/images/loading.gif) no-repeat center #FFFFFF");
        $("#shortlistContainer").children().fadeTo(0, ".2");
    }
    else {
        $("#shortlistContainer").css("background", "#FFFFFF");
        $("#shortlistContainer").children().fadeTo(0, "1");
    }
}

function RegisterLogin() {
    StoreOpenShortlist(true);

    window.location.href = "//shortlist-login";

    return false;
}

function LoadShortlists() {
    var id = 0;

    if (g_isLoggedIn) {
        if ($("#dataload").html().length != 0) {
            shortlistCount = BuildShortlists();

            if (shortlistCount > 0) {
                //Set the current shortlist as selected.
                selectAppropriateShortlist();
            }
        }
    }

    var timestamp = new Date();

    if (id != 0) {
        $.ajax(
		{
		    type: "GET",
		    url: "//shortlist-ajax?epaction=loaddms&epkey=" + id,
		    cache: false,
		    success: function() {
		        $("#dataload").load("//shortlist-current?t=" + timestamp.getTime() + " #myShortlist", {}, LoadCurrentShortlist);
		    }
		});
    } else {
        $("#dataload").load("//shortlist-current?t=" + timestamp.getTime() + " #myShortlist", {}, LoadCurrentShortlist);
    }
}

/* loads the shortlists */
function GetShortlists() {
    shortlists = new Array();
    var count = 0;
    var currentShortlistID = GetCurrentShortlist();
    var highestShorlistDefaultNumberName = 0;
    
    //Find the highest default shortlist name number
    $("#dataload #myShortlists div.ItryActions p a").each(function() {
        var shortlistName = $(this).parent().parent().prev().prev().prev("h3").html();

        if (_defaultShortlistNameRegex.test(shortlistName)) {
            try {
                var thisShortlistNameNumber = parseInt(shortlistName.match(/[0-9]+/));
                highestShorlistDefaultNumberName = 
                    thisShortlistNameNumber > highestShorlistDefaultNumberName ? thisShortlistNameNumber : highestShorlistDefaultNumberName;
            } catch (e) { }
        }
    });

    $("#dataload #myShortlists div.ItryActions p a").each(function() {
        id = ParseShortlistID($(this).attr("href"));
        name = $(this).parent().parent().prev().prev().prev("h3").html();
        $(this).parent().parent().prev().attr("id", "itinerary_" + id); //apply this lists ID to its product list element for future reference
        if (name == null || name == "null" || name.length == 0) {
            //If the default shortlist name was previously used, set the new list name to be the last number +1, otherwise simply append the count number
            name = "My Shortlist " + (highestShorlistDefaultNumberName + 1);

            //Update highest shortlist name number, in case there are more shortlists without a name
            highestShorlistDefaultNumberName++;

            //Save the Shortlist provisional name. The Ajax call must be synchronous, as the current shortlist must be set correctly before renaming it.
            $.ajax(
	        {
	            type: "GET",
	            url: "http://" + window.location.host + "//shortlist-ajax?epaction=loaddms&epkey=" + id,
	            cache: false,
	            async: false,
	            success: function() {
	                $.ajax({
	                    type: "POST",
	                    cache: false,
	                    url: "http://" + window.location.host + "//shortlist-current",
	                    data: { epaction: "savename", txtName: name },
	                    async: false
	                });
	            }
	        });
        }

        shortlists[count] = new Shortlist(id, name);
        count++;
    });
    
    //Set the correct current shortlist again, as it has changed on server side to set the shortlist names to unnamed ones
    if(currentShortlistID != null && currentShortlistID != 0)
    {
        $.ajax(
	    {
	        type: "GET",
	        url: "http://" + window.location.host + "//shortlist-ajax?epaction=loaddms&epkey=" + currentShortlistID,
	        cache: false,
	        async: false
	    });
	}


    return shortlists;
}


function BuildShortlists() {
    var shortlists = GetShortlists();

    dropdownlist = $("#shortlistSelect select");
    dropdownlist.empty();

    //First sort the shortlist names alphabettically
    shortlists.sort(SortShortlistsByName);

    for (i = 0; i < shortlists.length; i++) {
        dropdownlist.append("<option value='" + shortlists[i].GetID() + "'>" + shortlists[i].GetName() + "</option>");
    }
    
    return shortlists.length;
}

//Method responsible for sorting an array of shortlists alphabetically
function SortShortlistsByName(shortlistSelObjOne, shortlistSelObjTwo) {
    var shortlistNameOne = shortlistSelObjOne.GetName();
    var shortlistNameTwo = shortlistSelObjTwo.GetName();
    var numberPattern = /[0-9]+/;
    var valueToCompareObjOne = shortlistNameOne;
    var valueToCompareObjTwo = shortlistNameTwo;
    
    //If comparison of default shortlist names, make int comparison
    if (_defaultShortlistNameRegex.test(shortlistNameOne) && _defaultShortlistNameRegex.test(shortlistNameTwo)) {
        var objectOneDefaultNameNumber = shortlistNameOne.match(numberPattern);
        var objectTwoDefaultNameNumber = shortlistNameTwo.match(numberPattern);

        valueToCompareObjOne = parseInt(objectOneDefaultNameNumber);
        valueToCompareObjTwo = parseInt(objectTwoDefaultNameNumber);
    }

    if (valueToCompareObjOne < valueToCompareObjTwo) return -1;
    else if (valueToCompareObjOne > valueToCompareObjTwo) return 1;
    else return 0;
}

/* parses the shortlist ID from the delete itineray link */
function ParseShortlistID(url) {
    url = url.substring(url.indexOf("epkey=") + 6);
    return url;
}

function LoadCurrentShortlist() {
    if ($("#dataload").html().length != 0) {
        shortlistItemsCount = BuildShortlist();

        SetShortlistOverviewMessage(shortlistCount > 0, shortlistItemsCount >= 0 ? shortlistItemsCount : 0);

        if (shortlistItemsCount > 0 || shortlistCount > 0) {
            DisplayContent("shortlistItems");
        }
        else {
            DisplayContent("shortlistIntro");
        }
    }
    else {
        DisplayContent("shortlistIntro");
    }
}

function UpdateActiveShortlistPanel() {
    SetIsLoggedIn();

    //alert("UpdateActiveShortlistPanel");
    var timestamp = new Date();

    //alert("Update Panel");

    $("#dataload").load("//shortlist-current?t=" + timestamp.getTime() + " #myShortlist", {}, function() {
        if ($("#dataload").html().length != 0) {
            shortlistItemsCount = BuildShortlist();
            //if(g_isLoggedIn){toggleLoginLink(true);}
            if (shortlistItemsCount > 0) {
                SetShortlistOverviewMessage(true, shortlistItemsCount);

                $("div#shortlist div.tab_header a.tabTitleMap").attr("href", _siteMapUrl);

                if (!$("#shortlist").hasClass("open")) {
                    $("#shortlist").addClass("open");
                }

                if (!$("#shortlist").hasClass("expanded")) {
                    resizeShortlistPanel(shortlistItemsCount);
                }
                if (g_isLoggedIn) { customFadeout($("#loginLink")); }
            } else if (g_isLoggedIn) {
                //alert("State 2");
                $("#dataload").load("//shortlist-ajax?t=" + timestamp.getTime() + " #myShortlists", {}, function() {
                    if ($("#dataload").html().length != 0) {
                        //get the users collection of shortlists
                        shortlistCount = BuildShortlists();
                        var id = 0;

                        $("div#shortlist div.tab_header a.tabTitleMap").attr("href", _siteMapUrl);

                        if (shortlistCount > 0) {
                            var currentShortlist = GetCurrentShortlist();
                            var obj;
                            var objCount = 0;
                            selectAppropriateShortlist(); //Setting the current shortlist item as selected

                            //If currentShortlist has not been selected, the current shortlist itinerary items is the last one from the list
                            if (currentShortlist == null || currentShortlist == -1) {
                                obj = $(".itineraryItems:last li");
                            }
                            else {
                                obj = $("#itinerary_" + currentShortlist + " ol li");
                            }

                            try {
                                objCount = obj.length;
                            } catch (e) { }

                            //$("#shortlistItemCount").html(objCount);
                            SetShortlistOverviewMessage(true, objCount);
                        } else {
                            //$("#shortlistOverview").html("You have not yet created a shortlist.");
                            SetShortlistOverviewMessage(false, 0);
                        }

                        if (!$("#shortlist").hasClass("open")) {
                            $("#shortlist").addClass("open");
                        }
                    }

                    customFadeout($("#loginLink"));
                });
            } else {
                //If there are no items in the shortlist and user is not logged in, the Shortlist button directs user to instructions page.
                $("div#shortlist div.tab_header a.tabTitleMap").attr("href", _shortlistInstructionsUrl);
            }
        }
    }

	);
}

//Event handler called when the shortlist is updated (added / removed a product), 
//which then decides whether the UpdateActiveShortlist or InitShortlist method is called.
function ShortlistUpdatedEventHandler() {
    if (g_shortListOpen) InitShortList();
    else UpdateActiveShortlistPanel();
}

//Method responsible for setting the shortlist which currently needs to be displayed.
function selectAppropriateShortlist() {
    var currentShortListSelected = GetCurrentShortlist();

    try {
        //if the user does not have any shortlists currently selected, set the last one as selected
        if (currentShortListSelected == null || currentShortListSelected == -1) {
            document.getElementById("ddlShortlists").selectedIndex = document.getElementById("ddlShortlists").options.length - 1;
            StoreCurrentShortlist($("#ddlShortlists").selectedValues());
        }
        else { //If a shortlist is to be displayed, mark that shortlist as selected
            $("#ddlShortlists").selectOptions(currentShortListSelected);
        }
    } catch (e) { }
}

//Method responsible for customizing the JQUERY fadeout method, so that when complete, it simply sets
//the visibility to hidden and does not set display to none.
function customFadeout(jqueryObject) {
    $(jqueryObject).fadeOut(400, function() { $(this).css("visibility", "hidden").css("display", "inline"); });
}


/* displays the specified content div */
function DisplayContent(contentDiv) {
    containerHeight = 0;
    shortlistHeight = 0;

    $("#shortlistOverview").hide();

    switch (contentDiv) {
        case "shortlistIntro":
            containerHeight = 7;
            $("#toggleShortlistLink").html("Close <img src='/images/shortlist/arrow_up.gif' alt='Close Shortlist' />");

            break;
        case "shortlistItems":

            $("#shortlistItems").css("height", "auto");
            $("#shortlistItems").css("width", "auto");

            if (shortlistItemsCount == 0) {
                shortlistHeight = shortlistHeights[0];
            } else if (shortlistItemsCount == 1) {
                shortlistHeight = shortlistHeights[1];
            } else if (shortlistItemsCount == 2) {
                shortlistHeight = shortlistHeights[2];
            } else if (shortlistItemsCount == 3) {
                shortlistHeight = shortlistHeights[3];
            } else if (shortlistItemsCount == 4) {
                shortlistHeight = shortlistHeights[4];
            } else if (shortlistItemsCount > 4) {
                shortlistHeight = shortlistHeights[4];
                $("#shortlistItems").css("overflow-y", "auto");
                $("#shortlistItems").css("overflow-x", "hidden");
            }

            containerHeight = g_isLoggedIn ? shortlistHeight + 6 : shortlistHeight + 12;

            $("#shortlistItems").css("height", shortlistHeight + "em");

            $("#toggleShortlistLink").html("Close Shortlist <img src='/images/shortlist/arrow_up.gif' alt='Close Shortlist' />");

            break;
        default: containerHeight = 4; break;
    }

    //this is now handled in the shortlistHeight array
    //	if( g_isLoggedIn ){
    //		containerHeight -= 5; //accounts for login message being hidden later
    //	}

    var openAnimationProperties;

    if (!_isIE6)
        openAnimationProperties = { height: containerHeight + "em", width: "34em", opacity: "1", padding: "1em", margin: "0.5em" };
    else {
        openAnimationProperties = { height: containerHeight + "em", width: "34em" };

        $("#shortlistContainer").css("opacity", "1");
        $("#shortlistContainer").css("padding", "1em");
        $("#shortlistContainer").css("margin", "0.5em");
        $("#shortlistContainer").css("position", "relative");
    }

    $("#shortlistContainer").animate(openAnimationProperties,
        { duration: 500, step: function() { if (!_isIE6) $("div#shortlist div.tab_content").css("width", "100%"); }, complete: function() {
            IECompatibleFadeIn($("#" + contentDiv), 500);

            //Chrome Safari tweak to make the Shortlist open to the left
            if (!_isIE6)
                $("div#shortlist div.tab_content").css("width", "auto");

            //IE fix: remove filter after opacity is 100%, as it causes bad text rendering
            if (_isIE)
                $("#shortlistContainer, div#noItems, div#shortlistSelect, #shortlistContainer div, #shortlistContainer div *, #shortlistContainer p").css("filter", "alpha(enabled='false')");

            switch (contentDiv) {
                case "shortlistIntro":

                    $("#shortlistTemp").hide();
                    $("#shortlistSelect").hide();
                    $("#noItems").hide();
                    $("#shortlistItems").hide();
                    $("#shortlistOptions").hide();
                    $("#EmailForm").hide();
                    IECompatibleFadeIn($("#pleaseLogin"), 600);

                    break;

                case "shortlistItems":

                    $("#shortlistIntro").hide();

                    if (!g_isLoggedIn) {
                        IECompatibleFadeIn($("#pleaseLogin"), 600);
                    }
                    else {
                        $("#pleaseLogin").hide();
                    }

                    if (shortlistCount > 0) {
                        IECompatibleFadeIn($("#shortlistSelect"), 600);
                        IECompatibleFadeIn($("#btnMap"), 600);
                        IECompatibleFadeIn($("#shortlistOptions"), 600);
                        $("#btnNew").show();
                        $("#btnSave").hide();
                        $("#shortlistTemp").hide();
                    }
                    else {
                        $("#btnNew").hide();
                        $("#btnSave").show();
                        IECompatibleFadeIn($("#shortlistTemp"), 600);
                        IECompatibleFadeIn($("#shortlistOptions"), 600);
                        $("#btnMap").hide();
                    }

                    if (shortlistItemsCount > 0) {
                        $("#noItems").hide();
                        $("#btnMap").show();
                        $("#btnPrint").removeAttr("disabled");

                        if (g_isLoggedIn) {
                            $("#btnSend").removeAttr("disabled");
                            $("#btnBrochure").removeAttr("disabled");
                        }
                        else {
                            $("#btnBrochure").attr("disabled", true);
                            $("#btnSend").attr("disabled", true);
                        }
                        //update quantity message
                        //$("#shortlistItemCount").html(shortlistItemsCount);
                        SetShortlistOverviewMessage(true, shortlistItemsCount);
                    }
                    else {
                        $("#btnMap").hide();
                        IECompatibleFadeIn($("#noItems"), 600);
                        //					$("#btnPrint").attr("disabled", true);
                        //					$("#btnBrochure").attr("disabled", true);
                        //					$("#btnSend").attr("disabled", true);
                        $("#shortlistOptions").hide();
                    }

                    break;
            }

            g_openingShortList = false;

        }
        });

    //UpdateActiveShortlistPanel();
    DisplayLoading(false);
}

/* builds the shortlist from data on the page and returns the number of items */
function BuildShortlist() {
    GetShortlistItems();
    $("#shortlistItems").empty();

    for (i = 0; i < g_currentShortlistItems.length; i++) {
        OutputShortlistItem(g_currentShortlistItems[i], i != 0, i < g_currentShortlistItems.length - 1, i);
    }
    SetItinaryButtons();

    return g_currentShortlistItems.length;
}

//Method responsible for fading an object in. This method is IE compatible, as when alpha = 100%, it disables the filter
//(which prevents text being rendered badly).
function IECompatibleFadeIn(jqueryObject, duration) {
    $(jqueryObject).fadeIn(duration, function() {
        if (_isIE) $(this).css("filter", "alpha(enabled='false')");
    });
}


function GetShortlistItems() {
    g_currentShortlistItems = new Array();
    var count = 0;
    var block = true;
    var obj;
    var objCount;

    obj = $("#dataload #myShortlist .ItnryItems table.ItnryTbl tbody tr");
    objCount = obj.length;

    obj.each(function() {
        var name = $(this).find("td.item a.number").html();
        if (name != null) {
            var url = $(this).find("td.item a.number").attr("href");
            var id = ParseID(url);
            var type = ParseType(url);

            var description = $("ol.searchResults li h2 a[href*='" + id + "']").parent().parent().find("div.desc p").html();
            var imageUrl = $("ol.searchResults li h2 a[href*='" + id + "']").parent().parent().find("div.thumbnail img").attr("src");
            url = $("ol.searchResults li h2 a[href*='" + id + "']").attr("href");

            g_currentShortlistItems[count] = new ShortlistItem(id, type, name, description, url, imageUrl);

            count++;
        }
    });

    //alert(objCount+", "+count);
}

/* parses the product id from the product Url */
function ParseID(url) {
    if (url.indexOf("?") != -1)
        url = url.substring(0, url.indexOf("?"));

    return url.substring(url.lastIndexOf("-") + 2);
}

/* parses the product type from the product Url */
function ParseType(url) {
    var type;
    var start;
    var end;

    url = url.replace("http://", "");
    url = url.replace(window.location.hostname, "");

    start = url.indexOf("/", 1);
    end = url.indexOf("/", start + 1);

    type = url.substring(start + 1, end);

    if (type != "accommodation") {
        end = url.indexOf("/", end + 1);
        type = url.substring(start + 1, end);
    }

    return type;
}

/* outputs a new shortlist item */
function OutputShortlistItem(shortlistItem, canMoveUp, canMoveDown, index) {
    newItem = $("#shortlistItemTemplate").clone();

    newItem.attr("id", shortlistItem.GetID());
    newItem.removeClass("template");
    newItem.attr("style", "");

    newItem.find(".info h2 a").append(shortlistItem.GetName());
    newItem.find(".info h2 a").attr("href", shortlistItem.GetUrl());
    newItem.find(".info p").append(shortlistItem.GetDescription());
    newItem.find(".image img").attr("src", shortlistItem.GetImageUrl());
    newItem.find(".image img").attr("alt", shortlistItem.GetName());

    $("#shortlistItems").append(newItem);
}

function SetItinaryButtons() {
    count = 0;
    $("#shortlistItems .shortlistItem").each(function() {
        id = $(this).attr("id");


        $(this).find(".options a.remove").unbind();
        $(this).find(".options a.up").unbind();
        $(this).find(".options a.down").unbind();

        $(this).find(".options a.remove").attr("i", id);
        $(this).find(".options a.remove").click(function() { return RemoveItineryItem($(this).attr("i")); });

        button = $(this).find(".options a.up");
        if (count > 0) {
            button.attr("i", id);
            button.attr("p", count);
            button.click(function() { MoveItineryItem("u", $(this).attr("i"), $(this).attr("p")); return false; })
            button.find("img").attr("src", "/images/shortlist/move-up.png");
        }
        else
            button.find("img").attr("src", "/images/shortlist/move-up-disabled.png");

        button = $(this).find(".options a.down");
        if (count < $("#shortlistItems .shortlistItem").length - 1) {
            button.attr("i", id);
            button.attr("p", count);
            button.click(function() { MoveItineryItem("d", $(this).attr("i"), $(this).attr("p")); return false; });
            button.find("img").attr("src", "/images/shortlist/move-down.png");
        }
        else
            button.find("img").attr("src", "/images/shortlist/move-down-disabled.png");

        $(this).removeClass("even");
        $(this).removeClass("odd");

        if (count % 2 == 0)
            $(this).addClass("even");
        else
            $(this).addClass("odd");

        count++;
    });
}

/* removes the itinery item from the current shortlist */
function RemoveItineryItem(id) {
    /*
    * Attention: remove the item and save the shortlist before fecthing the content for the
    * "dataload" object. This avoids making the system delete and save the item over and over.
    * 
    * Now in case there is only one item left in the shortlist, it is necessary to remove the 
    * Shortlist itself, as there is a bug when attempting to remove an item from a
    * Shortlist with a single itinerary. The system simply does not delete it completely.
    */

    //If this is not the only itinerary item, simply remove it from the current shortlist
    //If user is not logged, perform standard action (as there is no shortlist name).
    if (!g_isLoggedIn || shortlistItemsCount > 1) {

        $.ajax(
	    {
	        type: "GET",
	        url: "//shortlist-current?epaction=ctrlremove&epkey=" + id,
	        cache: false,
	        success: function() {
	            $.get("//shortlist-current?epaction=savedms", function() {

	                var timestamp = new Date();
	                $("#dataload").load("//shortlist-current?t=" + timestamp.getTime() + " #myShortlist", {}, function() {
	                    UpdateActiveShortlistPanel();
	                });

	                $("#" + id).slideUp("normal", function() {
	                    $(this).remove();
	                    if ($("#shortlistItems .shortlistItem").length == 0) {
	                        DisplayLoading(true);
	                        InitShortList();
	                    }
	                    else
	                        SetItinaryButtons();
	                });
	            });
	        }
	    });
    } else { //If this is the only itinerary item, delete the shortlist and create another one with the same name.
        RebuildAnotherShortlistWithSameName(InitShortList);
    }

    return false;
}

/* 
* Method responsible for deleting the current shortlist and creating another one with
* the same name. 
*/
function RebuildAnotherShortlistWithSameName(completeEventHandler) {
    //First fetch the currentshortlist ID and the currentShortlistName (as this will be used to rename the new one)
    var newId = 0;
    var currentShortlistID = GetCurrentShortlist();
    var currentShortlistName = $("#ddlShortlists option[value*='" + currentShortlistID + "']").html();

    //In case the "ddlShortlists" Select panel has not yet been loaded, fetch name from "dataload"
    if (currentShortlistName == null) {
        currentShortlistName = $("div#dataload div#myShortlist div.ItnryIntro h2").html();
    }

    DisplayLoading(true);

    //Ajax call to delete the current shortlist
    $.ajax(
		{
		    type: "GET",
		    url: "//shortlist-ajax?epaction=deldms&epkey=" + currentShortlistID,
		    cache: false,
		    success: function() {

		        //When done, remove the current shortlist option from the select control
		        $("#ddlShortlists").removeOption(currentShortlistID);

		        //Another Ajax call to add a new shortlist with the same name
		        $.ajax(
	            {
	                type: "GET",
	                url: "//shortlist-ajax?epaction=new",
	                cache: false,
	                success: function() {

	                    //After creating the shortlist, make another Ajax call to Save it.
	                    $.ajax(
			            {
			                type: "GET",
			                cache: false,
			                url: "//shortlist-ajax?epaction=savedms",
			                success: function() {
			                    var timestamp = new Date();

			                    //The Ajax call to populate the "#dataload" item with the new shortlist names and ids.
			                    $("#dataload").load("//shortlist-ajax?t2=" + timestamp.getTime() + " #myShortlists", {}, function() {
			                        if ($("#dataload").html().length != 0) {
			                            lists = GetShortlists();

			                            //Store the Current Shortlist as the new one (both on client and server side)
			                            StoreCurrentShortlist(lists[lists.length - 1].GetID(), function() {

			                                //Last, make an Ajax call to rename the newly create shortlist to be the same as the deleted one.
			                                jQuery.post("http://" + window.location.host + "//shortlist-current",
			                                { epaction: "savename", txtName: currentShortlistName }, completeEventHandler);
			                            });
			                        }
			                    });
			                }
			            });
	                }
	            });

		    }
		});
}

function resizeShortlistPanel(itemCount) {
    //$("#shortlistItemCount").html(itemCount);
    SetShortlistOverviewMessage(true, itemCount);

    //var loginMsgSpace = g_isLoggedIn ? 5 : 0; //accounts for login message being hidden later

    try {
        if (itemCount <= 4) {
            var containerHeight = g_isLoggedIn ? shortlistHeights[itemCount] + 6 : shortlistHeight + 12;
            $("#shortlistItems").css("height", shortlistHeights[itemCount] + "em");
            $("#shortlistContainer").css("height", containerHeight + "em");
            $("#shortlistItems").css("overflow-y", "");
            $("#shortlistItems").css("overflow-x", "");
        } else {
            var containerHeight = g_isLoggedIn ? shortlistHeights[4] + 6 : shortlistHeight + 12;
            $("#shortlistItems").css("height", shortlistHeights[4] + "em");
            $("#shortlistContainer").css("height", containerHeight + "em");
            $("#shortlistItems").css("overflow-y", "auto");
            $("#shortlistItems").css("overflow-x", "hidden");
        }
    } catch (e) { }
}

/* moves the itinery item */
function MoveItineryItem(direction, id, position) {
    var epaction;
    var shortlistItem;
    itineryItem = $("#" + id);
    itineryItem.remove();

    if (direction == "u") {
        shortlistItem = g_currentShortlistItems[position];
        g_currentShortlistItems.splice(position, 1);

        epaction = "moveup";
        position--;
        $("#shortlistItems .shortlistItem:eq(" + position + ")").before(itineryItem);

        g_currentShortlistItems.splice(position, 0, shortlistItem);
    }

    if (direction == "d") {
        shortlistItem = g_currentShortlistItems[position];
        g_currentShortlistItems.splice(position, 1);
        epaction = "movedown";
        $("#shortlistItems .shortlistItem:eq(" + position + ")").after(itineryItem);
        g_currentShortlistItems.splice(position + 1, 0, shortlistItem);
    }

    $.ajax(
	{
	    type: "GET",
	    cache: false,
	    url: "//shortlist-current?epaction=" + epaction + "&epkey=" + id,
	    success: function() {
	        $.get("//shortlist-current?epaction=savedms");
	    }
	});

    SetItinaryButtons();
}

function DisplayToolTip(e, tooltip) {
    $(".tooltip").hide();
    $(tooltip).css("left", e.pageX + 10);
    $(tooltip).css("top", e.pageY + 10);
    IECompatibleFadeIn($(tooltip), 600);
}

function HideToolTip(tooltip) {
    $(tooltip).fadeOut();
}

function DisplaySendEmailForm(display) {
    if (display) {

        // check that the user is logged in
        if (!g_isLoggedIn) {
            StoreOpenShortlist(true);
            window.location.href = "//shortlist-login";
        }
        else {
            $("#shortlistOptions").hide();
            $("#EmailForm input#txtFrEmail").val("Enter friend's email");

            $("#EmailForm input#txtFrEmail").focus(function() {
                if ($(this).val() == "Enter friend's email")
                    $(this).val("");
            });

            $("#EmailForm input#txtFrEmail").blur(function() {
                if ($(this).val() == "")
                    $(this).val("Enter friend's email");
            });

            IECompatibleFadeIn($("#EmailForm"), 600);
        }
    }
    else {
        $("#EmailForm").hide();
        IECompatibleFadeIn($("#shortlistOptions"), 600);
        $("#EmailForm input[type='text']").unbind("focus").unbind("blur");
    }
}

function SendEmail() {
    $("#btnSendEmail").val("Sending...");
    $("#btnSendEmail").attr("disabled", true);

    jQuery.post("http://" + window.location.host + "//shortlist-ajax", { "epaction": "emailfr", "txtFrEmail": $("#txtFrEmail").val() }, function() {
        $("#btnSendEmail").removeAttr("disabled");
        DisplaySendEmailForm(false);
        $("#btnSendEmail").val("Send");
    });
}

/* saves the current shortlist */
function SaveShortlist() {

    DisplayLoading(true);

    if (!g_isLoggedIn) {
        // user is not logged in, forward to login page and set cookie to 
        // keep shortlist open
        StoreOpenShortlist(true);
        StoreCurrentShortlist(-1);
        window.location.href = "//shortlist-login";
    }
    else {
        // user l is logged in so save basket and reload the shortlists
        jQuery.get("http://" + window.location.host + "//shortlist-home?epaction=savedms");
        InitShortList();
    }

}

function loadMapView() {
    DisplayLoading(true);
    StoreOpenShortlist(true);
    window.location.href = "//shortlist-map";
}

/* saves the new name for the current shortlist */
function SaveShortlistName() {
    $("#btnSaveName").attr("disabled", true);
    $("#btnSaveName").val("Saving...");

    jQuery.post("http://" + window.location.host + "//shortlist-current", { epaction: "savename", txtName: $("#txtShortlistName").val() }, function() {
        $("#btnSaveName").removeAttr("disabled");
        DisplayRenameShortlist(false);
        $("#btnSaveName").val("Save");
    });

}

/* displays the rename options */
function DisplayRenameShortlist(display) {
    if (display) {
        $("#ddlShortlists").hide();
        $("#btnRename").hide();
        IECompatibleFadeIn($("#txtShortlistName"), 600);
        IECompatibleFadeIn($("#btnSaveName"), 600);
        $("#txtShortlistName").val($("#ddlShortlists").selectedOptions().html());
        $("#txtShortlistName").focus();
        $("#txtShortlistName").select();
    }
    else {
        $("#txtShortlistName").hide();

        $("#btnSaveName").hide();
        IECompatibleFadeIn($("#ddlShortlists"), 600);
        IECompatibleFadeIn($("#btnRename"), 600);

        $("#ddlShortlists").selectedOptions().html($("#txtShortlistName").val());
    }
}

/* loads the shortlist from the dropdown */
function LoadShortlist() {
    DisplayLoading(true);

    var timestamp = new Date();
    var id = $("#ddlShortlists").selectedValues()[0];
    StoreCurrentShortlist(id);

    jQuery.get("http://" + window.location.host + "//shortlist-ajax?epaction=savedms", function() {
        jQuery.get("http://" + window.location.host + "//shortlist-ajax?epaction=loaddms&epkey=" + id, function(data, textStatus) {
            $("#dataload").load("//shortlist-current?t=" + timestamp.getTime() + " #myShortlist", {}, LoadCurrentShortlist);
        });
    });
}

function DeleteShortlist() {
    if (confirm("Are you sure you want to delete this list?")) {

        $("#btnDelete").attr("disabled", true);

        var newId = 0;
        var id = $("#ddlShortlists").val();

        $.ajax(
		{
		    type: "GET",
		    url: "//shortlist-ajax?epaction=deldms&epkey=" + id,
		    cache: false,
		    success: function() {
		        DisplayLoading(true);
		        $("#btnDelete").val("Delete");
		        $("#btnDelete").removeAttr("disabled");
		        $("#ddlShortlists").removeOption(id);

		        if ($("#ddlShortlists").find("option").length > 0) {
		            newId = $("#ddlShortlists").selectedValues()[0];
		            StoreCurrentShortlist(newId);
		        }
		        else
		            StoreCurrentShortlist(0);



		        if (newId > 0) {
		            $.ajax(
					{
					    type: "GET",
					    url: "//shortlist-ajax?epaction=loaddms&epkey=" + newId,
					    cache: false,
					    success: function() {
					        InitShortList();
					    }
					});
		        }
		        else {
		            InitShortList();
		        }
		    }
		});

    }
}

/* prints the current short list */
function PrintShortlist() {
    window.open("http://" + window.location.hostname + "//shortlist-print");
}

/* creates a new shortlist */
function NewShortlist() {
    DisplayLoading(true);

    var timestamp = new Date();

    $.ajax(
	{
	    type: "GET",
	    url: "//shortlist-ajax?epaction=new",
	    cache: false,
	    success: function() {
	        $.ajax(
			{
			    type: "GET",
			    cache: false,
			    url: "//shortlist-ajax?epaction=savedms",
			    success: function() {
			        $("#dataload").load("//shortlist-ajax?t2=" + timestamp.getTime() + " #myShortlists", {}, function() {
			            if ($("#dataload").html().length != 0) {
			                lists = GetShortlists();
			                StoreCurrentShortlist(lists[lists.length - 1].GetID());
			                jQuery.get("http://" + window.location.host + "//shortlist-ajax?epaction=loaddms&epkey=" + lists[lists.length - 1].GetID(), function() {
			                    InitShortList();
			                });
			            }
			        });
			    }
			});
	    }
	});
}

function GenerateBrochure() {
    var buttonWidth;

    if (g_isLoggedIn) {
        buttonWidth = $("#btnBrochure").css("width");
        $("#btnBrochure").attr("disabled", true);
        $("#btnBrochure").val("Generating Brochure...");
        $("#btnBrochure").css("width", "145px");

        var productUrl;
        var pageUrl;

        var ThisPageURL = location.href;

        if (ThisPageURL.indexOf('au.vne.nmdemo.net') != -1) {
            pageUrl = "http://one-tourism-int.different-digital.co.uk/generate-brochure.aspx?" +
            //pageUrl = "http://localhost/ONE-Tourism/generate-brochure.aspx?" +
				"filename=" + $("#ddlShortlists").selectedOptions().html() +
				"&url=" + escape("http://" + window.location.host + "//");

        }
        else if (ThisPageURL.indexOf('nz.vne.nmdemo.net') != -1) {
            pageUrl = "http://one-tourism-nz.different-digital.co.uk/generate-brochure.aspx?" +
            //pageUrl = "http://localhost/ONE-Tourism/generate-brochure.aspx?" +
				"filename=" + $("#ddlShortlists").selectedOptions().html() +
				"&url=" + escape("http://" + window.location.host + "//");

        }
        else {
            pageUrl = "http://one-tourism.different-digital.co.uk/generate-brochure.aspx?" +
            //pageUrl = "http://localhost/ONE-Tourism/generate-brochure.aspx?" +
				"filename=" + $("#ddlShortlists").selectedOptions().html() +
				"&url=" + escape("http://" + window.location.host + "//");
        }

        for (var i = 0; i < g_currentShortlistItems.length; i++) {
            productUrl = g_currentShortlistItems[i].GetUrl();
            productUrl = productUrl.substr(productUrl.lastIndexOf("/") + 1);

            pageUrl += "&url" + (i + 1) + "=" + productUrl;
            pageUrl += "&t" + (i + 1) + "=" + g_pdfTypes[g_currentShortlistItems[i].GetType()];
        }

        $("#dataload").empty();
        $("#dataload").append("<iframe id='brochureIframe' src='" + pageUrl + "' onload='BrochureDownloadingEvtHandler()'></iframe>");

        // ie doesn't fire the load event for iframe to download a file, so use readystatchange event.
        if ($.browser.msie) {
            var iframe = document.getElementById("brochureIframe");
            iframe.onreadystatechange = function() {
                if (iframe.readyState == "interactive") BrochureDownloadingEvtHandler();
            }
        } else if ($.browser.safari) {//Chrome / Safari do not fire onload / onreadystatechange event, so it is not possible to know when the file starts downloading.
            setTimeout(BrochureDownloadingEvtHandler, 15000); //Reenable brochure button after 15 seconds.
        }
    }
    return false;
}

/* Event hanlder for when the browser starts downloading the Brochure. This method simply reenables the Brochure button. */
function BrochureDownloadingEvtHandler() {
    $("#btnBrochure").removeAttr("disabled");
    $("#btnBrochure").val("Create Brochure");
    $("#btnBrochure").css("width", "120px");
}

/**
* ShortlistItem class
**/

function ShortlistItem(id, type, name, description, url, imageUrl) {
    this._id = id;
    this._name = name;
    this._description = description;
    this._url = url;
    this._imageUrl = imageUrl;
    this._type = type;
}

ShortlistItem.prototype._name;
ShortlistItem.prototype.GetName = function() { return this._name; }
ShortlistItem.prototype._description;
ShortlistItem.prototype.GetDescription = function() { return this._description; }
ShortlistItem.prototype._id;
ShortlistItem.prototype.GetID = function() { return this._id; }
ShortlistItem.prototype._url;
ShortlistItem.prototype.GetUrl = function() { return this._url; }
ShortlistItem.prototype._imageUrl;
ShortlistItem.prototype.GetImageUrl = function() { return this._imageUrl; }
ShortlistItem.prototype._type;
ShortlistItem.prototype.GetType = function() { return this._type; }

/**
* Shortlist class
**/
function Shortlist(id, name) {
    this._id = id;
    this._name = name;
}

Shortlist.prototype._id;
Shortlist.prototype.GetID = function() { return this._id; }
Shortlist.prototype._name;
Shortlist.prototype.GetName = function() { return this._name; }

};
