// Read a page's GET URL variables and return them as an associative array.

/**
* Converts the given data structure to a JSON string.
* Argument: arr - The data structure that must be converted to JSON
* Example: var json_string = array2json(['e', {pluribus: 'unum'}]);
* 			var json = array2json({"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}});
* http://www.openjs.com/scripts/data/json_encode.php
*/
function array2json(arr) {
    var parts = [];
    var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');

    for (var key in arr) {
        var value = arr[key];
        if (typeof value == "object") { //Custom handling for arrays
            if (is_list) parts.push(array2json(value)); /* :RECURSION: */
            else parts[key] = array2json(value); /* :RECURSION: */
        } else {
            var str = "";
            if (!is_list) str = '"' + key + '":';

            //Custom handling for multiple data types
            if (typeof value == "number") str += value; //Numbers
            else if (value === false) str += 'false'; //The booleans
            else if (value === true) str += 'true';
            else str += '"' + value + '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)
            parts.push(str);
        }
    }
    var json = parts.join(",");

    if (is_list) return '[' + json + ']'; //Return numerical JSON
    return '{' + json + '}'; //Return associative JSON
}









$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        return $.getUrlVars()[name];
    }
});

function ShowPreventPhotoCopyingMessage() {
    alert(PreventImageDownloadText);
}

$(document).ready(function () {
    $(".button-print").click(function (e) {
        window.print();
    })
});

// Cooltips slider
$(document).ready(function () {
    $(".cooltips").easySlider({
        auto: true,
        continuous: true,
        pause: 6000,
        prevId: 'cooltipprev',
        nextId: 'cooltipnext',
        prevText: '',
        nextText: ''
    });

    $("img").live('contextmenu', function (e) {
        ShowPreventPhotoCopyingMessage();
        e.preventDefault();
        return false;
    });

    // start the li scroller and fix the time it restarts
    var width = $(document).width();

    $("ul#ticker").css("left", width)


    $("ul#ticker").liScroll({ travelocity: 0.08 });
    var width = $(document).width();
    // $("ul#ticker").css("width", 100)
    // $("ul#ticker").css("width",300)
    // make sure the list is not shown until it's fully loaded so we don't see the list at the left side while loading the page
    $(".tickercontainer li").css("visibility", "visible")
});

$(function () {

    // browser check
    if (jQuery.browser.mozilla && jQuery.browser.version < "1.9") {
        $("#browser_warning").css("display", "block")
    }

    // language selector
    $('.language_selector').change(function () {
        //alert('Handler for .change() called.');   
        //$(".language_selector").click(function () {
        var lang = this.value;
        var url = document.location.href;
        if (-1 !== url.indexOf("?")) url = url.substr(0, url.indexOf("?"));
        url = url + "?lang=" + lang;
        if (url.toLowerCase() !== document.location.href.toLowerCase() && url.toLowerCase().replace("?lang=nl", "") !== document.location.href.toLowerCase()) document.location = url;
    });


    // current language selection
    var url = document.location.href;
    if (-1 !== url.indexOf("=")) {
        var current_lang = url.substr(url.indexOf("=") + 1).toLowerCase();
        $(".language_selector").val(current_lang);
    }

    // links from package to hotels should stay in the same language
    $(".package .detail a").each(function () {
        if (-1 < $(this).attr("href").indexOf("/hotel") && -1 == $(this).attr("href").indexOf("?lang=")) {
            lang = "nl";
            if (-1 < document.location.href.indexOf("?lang=")) lang = document.location.href.split("?lang=")[1];
            $(this).attr("href", $(this).attr("href") + "?lang=" + lang);
        }
    });

    $("#search-button").click(function () {
        document.location = "/zoeken/" + $("#search-text").val() + "?lang=" + $(".language_selector").val();
    });

    $("#search-text").keypress(function (e) {
        if (13 === e.which) {
            $("#search-button").click();
            return false;
        }
    });

    Navigation.select($(".content").attr("data-section"));

    Calendar.setDefaults();
    Calendar.init();

    $(".hotels-filter .filter input").click(function () {
        filterHotels(1, 1);
    });

    $(".accommodations-filter .filter input").click(function () {
        filterAccommodations(1, 1);
    });

    $(".upload-button").click(function () {
        $(".photo-background").css("height", $(document).height());
        $(".photo-upload").show();
        $(".photo-upload-content").css("left", (($(window).width() / 2) - ($(".photo-upload-content").width() / 2)) + "px");
        $(".photo-upload-content").css("top", (($(window).height() / 2) - ($(".photo-upload-content").height() / 2)) + "px");
    });

    $(".photo-upload-cancel").click(function () {
        $(this).parents(".photo-upload").hide();
    });

    $(".photos a:not(.upload-button)").click(function () {

        $("<div class='photo-layer'><div class='photo-background'></div><div class='photo-popup' ><img class='prev' alt='' src='/images/slider_blank.png' /><img class='next' alt='' src='/images/slider_blank.png' /><div class='photo-close'></div><img src='' /><h3 class='photo-creator'></h3><h4 class='photo-location'></h4><div><div class='photo-desc'></div><div></div>").appendTo("body");

        $(".photo-popup img:not(.prev):not(.next)").attr("src", $(this).attr("href"));
        $(".photo-popup").attr("id", "popup-" + $(this).parent().attr("id"));
        $(".photo-popup .photo-desc").html($(this).attr("data-desc"));
        $(".photo-popup .photo-creator").html($(this).attr("data-creator"));
        $(".photo-popup .photo-location").html($(this).attr("data-location"));

        var top = 200; // (($(window).height() / 2) - ($(".photo-popup").height() / 2));
        if (0 > top) top = 0;
        $(".photo-popup").css("left", (($(window).width() / 2) - ($(".photo-popup").width() / 2)) + "px");
        $(".photo-popup").css("top", top + "px");
        $(".photo-background").css("height", $(document).height());

        //$(".photo-popup").shadow({ width:5, startOpacity:60, endOpacity:10, cornerHeight:8, color:"#000000"});

        $(".photo-close").click(function () {
            $(".photo-layer").remove();
        });

        $(".photo-popup .prev").click(function () {
            var $curr = $("#" + $(".photo-popup").attr("id").replace("popup-", "") + " a");
            var $prev = $curr.parent().prev().find("a");

            if (null == $prev.html()) {
                $prev = $($curr.parent().nextAll()[$curr.parent().nextAll().size() - 1]).find("a");
            }

            if (null != $prev.html()) {
                $(".photo-popup img:not(.prev):not(.next)").attr("src", $prev.attr("href"));
                $(".photo-popup").attr("id", "popup-" + $prev.parent().attr("id"));
                $(".photo-popup .photo-desc").html($prev.attr("data-desc"));
                $(".photo-popup .photo-creator").html($prev.attr("data-creator"));
                $(".photo-popup .photo-location").html($prev.attr("data-location"));
            }
        });

        $(".photo-popup .next").click(function () {
            var $curr = $("#" + $(".photo-popup").attr("id").replace("popup-", "") + " a");
            var $next = $curr.parent().next().find("a");

            if (null == $next.html()) {
                $next = $($curr.parent().prevAll()[$curr.parent().prevAll().size() - 1]).find("a");
            }

            if (null != $next.html()) {
                $(".photo-popup img:not(.prev):not(.next)").attr("src", $next.attr("href"));
                $(".photo-popup").attr("id", "popup-" + $next.parent().attr("id"));
                $(".photo-popup .photo-desc").html($next.attr("data-desc"));
                $(".photo-popup .photo-creator").html($next.attr("data-creator"));
                $(".photo-popup .photo-location").html($next.attr("data-location"));
            }
        });

        $(".photo-background").click(function () {
            $(".photo-layer").remove();
        });


        return false;
    });

    // remove zoover border
    window.setTimeout(function () {
        if (0 < $(".reviews div").size()) {
            $($(".reviews div")[0]).css("border", "");
            $("#GadgetTitle").html($("#GadgetTitle").html().replace("Waardering ", "").replace("Appreciation ", "").replace("Gesamtwertung ", "").replace("Apreciación ", "").replace("Valutazione dei viaggiatori: ", "").replace("Värdering ", ""));
        }
    }, 1000);

});

function filterHotels(page, seed) {
    $("<div class='hotels-progress' ><div>").appendTo("body");
    var p = findPos($(".hotel-list")[0]);
    var pX = p[0];
    var pY = p[1];
    $(".hotels-progress").css({ left: pX, top: pY, width: 730, height: 200 });

    if (page == undefined) page = 1;
    if (seed == undefined) seed = Math.ceil(Math.random() * 65000);

    var lang = $(".content").attr("data-language");
    if (lang == undefined)
        lang = "NL"

    var url = "/hotellijst";
    var params = "lang=" + lang
                + "&page=" + page
		+ "&seed=" + seed
		+ "&zwembad=" + $(".filter input#zwembad:checked").size()
		+ "&internet=" + $(".filter input#internet:checked").size()
		+ "&restaurant=" + $(".filter input#restaurant:checked").size()
		+ "&bar=" + $(".filter input#bar:checked").size()
		+ "&terras=" + $(".filter input#terras:checked").size()
		+ "&parkeren=" + $(".filter input#parkeren:checked").size()
		+ "&lift=" + $(".filter input#lift:checked").size()
		+ "&huisdieren=" + $(".filter input#huisdieren:checked").size()
		+ "&allin=" + $(".filter input#allin:checked").size()
		+ "&castle=" + $(".filter input#castle:checked").size()
        + "&wellness=" + $(".filter input#wellness:checked").size()
		+ "&bicyclerental=" + $(".filter input#bicyclerental:checked").size()
		+ "&brabant=" + $(".filter input#brabant:checked").size()
		+ "&shertogenbosch=" + $(".filter input#shertogenbosch:checked").size()
		+ "&veluwe=" + $(".filter input#veluwe:checked").size()
		+ "&arnhem=" + $(".filter input#arnhem:checked").size()
		+ "&nijmegen=" + $(".filter input#nijmegen:checked").size()
		+ "&rivierenland=" + $(".filter input#rivierenland:checked").size()
		+ "&maasduinen=" + $(".filter input#maasduinen:checked").size()
		+ "&peelenmaas=" + $(".filter input#peelenmaas:checked").size()
		+ "&maasplassen=" + $(".filter input#maasplassen:checked").size()
		+ "&kleve=" + $(".filter input#kleve:checked").size()
		+ "&wesel=" + $(".filter input#wesel:checked").size()
		+ "&viersen=" + $(".filter input#viersen:checked").size()
		+ "&krefeld=" + $(".filter input#krefeld:checked").size()
		+ "&duisburg=" + $(".filter input#duisburg:checked").size()
		+ "&neuss=" + $(".filter input#neuss:checked").size()
		+ "&middenlimburg=" + $(".filter input#middenlimburg:checked").size();

    $.ajax({
        type: "GET",
        data: params,
        url: url,
        cache: false,
        dataType: "html",
        success: function (response) {
            $(".hotel-list").html(response);
            Map.clearPins();
            Map.showCurrentHotels();
            $(".hotels-progress").remove();
            Map.AddEntityCollectionToMap();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert(textStatus);
        }
    });
}

function filterAccommodations(page, seed) {
    $("<div class='hotels-progress' ><div>").appendTo("body");
    var p = findPos($(".hotel-list")[0]);
    var pX = p[0];
    var pY = p[1];
    $(".hotels-progress").css({ left: pX, top: pY, width: 730, height: 200 });

    if (page == undefined) page = 1;
    if (seed == undefined) seed = Math.ceil(Math.random() * 65000);

    var url = "/accommodatielijst";
    var params = "lang=" + $(".content").attr("data-language")
                + "&page=" + page
		+ "&seed=" + seed
		+ "&hotel=" + $(".filter input#hotel:checked").size()
		+ "&camping=" + $(".filter input#camping:checked").size()
		+ "&bnb=" + $(".filter input#bnb:checked").size()
		+ "&bungalowpark=" + $(".filter input#bungalowpark:checked").size()
		+ "&vakantiewoning=" + $(".filter input#vakantiewoning:checked").size()
		+ "&kampeerboerderij=" + $(".filter input#kampeerboerderij:checked").size()
		+ "&kasteel=" + $(".filter input#kasteel:checked").size()
		+ "&overig=" + $(".filter input#overig:checked").size()
		+ "&noordoostbrabant=" + $(".filter input#brabant:checked").size()
		+ "&'s-hertogenbosch=" + $(".filter input#shertogenbosch:checked").size()
		+ "&veluwe=" + $(".filter input#veluwe:checked").size()
		+ "&arnhem=" + $(".filter input#arnhem:checked").size()
		+ "&nijmegen=" + $(".filter input#nijmegen:checked").size()
		+ "&rivierenland=" + $(".filter input#rivierenland:checked").size()
		+ "&regiomaasduinen=" + $(".filter input#maasduinen:checked").size()
		+ "&regiopeelenmaas=" + $(".filter input#peelenmaas:checked").size()
		+ "&maasplassen=" + $(".filter input#maasplassen:checked").size()
		+ "&kreiskleve=" + $(".filter input#kleve:checked").size()
		+ "&kreiswesel=" + $(".filter input#wesel:checked").size()
		+ "&kreisviersen=" + $(".filter input#viersen:checked").size()
		+ "&krefeld=" + $(".filter input#krefeld:checked").size()
		+ "&duisburg=" + $(".filter input#duisburg:checked").size()
		+ "&rhein-kreisneuss=" + $(".filter input#neuss:checked").size()
		+ "&midden-limburg=" + $(".filter input#middenlimburg:checked").size();

    $.ajax({
        type: "GET",
        data: params,
        url: url,
        dataType: "html",
        success: function (response) {
            $(".hotel-list").html(response);
            Map.clearPins();
            Map.showCurrentHotels();
            $(".hotels-progress").remove();
            Map.AddEntityCollectionToMap();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert(textStatus);
        }
    });
}

var Navigation = {
    "select": function (item) {
        if (item) {
            $("." + item).addClass("selected");
        }
    }
};

$(function () {
    $("#calendar-year").change(function () {
        Calendar.year = $(this).val();
        Calendar.init();
    });

    $("#calendar-month").change(function () {
        Calendar.month = $(this).val();
        Calendar.init();
    });

    $(".calendar-prev").click(function () {
        if ("1" !== $("#calendar-month").val()) {
            $("#calendar-month").val(parseInt($("#calendar-month").val()) - 1);
        } else {
            $("#calendar-month").val(12);
            $("#calendar-year").val(parseInt($("#calendar-year").val()) - 1);
        }

        Calendar.month = $("#calendar-month").val();
        Calendar.year = $("#calendar-year").val();
        Calendar.init();
    });

    $(".calendar-next").click(function () {
        if ("12" !== $("#calendar-month").val()) {
            $("#calendar-month").val(parseInt($("#calendar-month").val()) + 1);
        } else {
            $("#calendar-month").val(1);
            $("#calendar-year").val(parseInt($("#calendar-year").val()) + 1);
        }

        Calendar.month = $("#calendar-month").val();
        Calendar.year = $("#calendar-year").val();
        Calendar.init();
    });

});

var Calendar = {
    "month": 1,
    "year": 1970,
    "row": null,
    "setDefaults": function () {
        $("#calendar-month").val(new Date().getMonth() + 1);
        $("#calendar-year").val(new Date().getFullYear());

        Calendar.month = $("#calendar-month").val();
        Calendar.year = $("#calendar-year").val();
    },
    "init": function () {
        if (0 == $(".calendar").size()) return;

        $("<div class='calendar-progress' ><div>").appendTo("body");
        var p = findPos($(".calendar")[0]);
        var pX = p[0];
        var pY = p[1];
        $(".calendar-progress").css({ left: pX, top: pY, width: 220, height: 250 });

        var url = "/kalender";
        var params = "jaar=" + Calendar.year + "&maand=" + Calendar.month + "&lang=" + $(".calendar").attr("data-language");

        $.ajax({
            type: "GET",
            data: params,
            url: url,
            dataType: "html",
            success: function (response) {
                $(".calendar table tbody").html(response.substr(response.indexOf(">") + 1).replace("</table>", ""));

                $(".calendar td.events").click(function (event) {
                    if ("1" == $("#calendar-tooltip-" + this.innerHTML).attr("data-fix")) {
                        $("#calendar-tooltip-" + this.innerHTML).attr("data-fix", "0");
                    } else {
                        $("#calendar-tooltip-" + this.innerHTML).attr("data-fix", "1");
                    }
                });
                $(".calendar td.events").mouseover(function (event) {
                    if (0 == $("#calendar-tooltip-" + this.innerHTML).size()) {
                        $(".calendar-tooltip").remove();
                        if ($(".calendar").parent().hasClass("right")) {
                            $("<div class='calendar-tooltip' id='calendar-tooltip-" + this.innerHTML + "'><div class='calendar-rightpointer'></div>" + $(this).attr("data-eventlist") + "</div>").appendTo("body");
                        } else {
                            $("<div class='calendar-tooltip' id='calendar-tooltip-" + this.innerHTML + "'><div class='calendar-leftpointer'></div>" + $(this).attr("data-eventlist") + "</div>").appendTo("body");
                        }
                        var pos = findPos(this);
                        var posX = pos[0] + 25;
                        var posY = pos[1] - 50;
                        if ($(".calendar").parent().hasClass("right")) posX = pos[0] - $("#calendar-tooltip-" + this.innerHTML).width() - 60;
                        $("#calendar-tooltip-" + this.innerHTML).css({ left: posX, top: posY });

                        $(".calendar-tooltip").click(function (event) {
                            $(this).attr("data-fix", "0");
                        });
                        $(".calendar-tooltip").mouseout(function (event) {
                            if (0 == $(this).attr("data-fix")) {
                                $(this).remove();
                            }
                        });
                    }
                });
                $(".calendar td.events").mouseout(function (event) {
                    if ("1" != $("#calendar-tooltip-" + this.innerHTML).attr("data-fix")) {
                        $("#calendar-tooltip-" + this.innerHTML).remove();
                    }
                });
                $(".calendar-progress").remove();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //alert(textStatus);
            }
        });
    }
};

function findPos(obj) {
    var curleft = curtop = 0;
    try {
        if (obj != null && obj.offsetParent != null && obj.offsetParent) {
            do {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
        }
    } catch (e) { }
    return [curleft, curtop];
}

function CloseOverlay(element) {
    if (typeof (element) != 'object') {
        $("#" + element).hide();
    } else {
        element.hide();
    }
}

//jQuery(function ($) {
$(document).ready(function () {
    if (0 < $('.slider').length) {

        $('.slider .prev').hide();
        $('.slider .next').hide();

        // bug in jquery 1.3.2, selector :has :gt returns 0 items
        //		$('.slider:has(.sections li:gt(2))').find('.next').show();
        $('.slider').each(function () {
            if (1 < $(this).find("li").size()) $(this).find('.next').show();
        });

        $('.slider').serialScroll({
            target: '.slider-content',
            items: 'li',
            prev: 'img.prev',
            next: 'img.next',
            axis: 'x',
            start: 0,
            duration: 750,
            force: true,
            exclude: 0,
            cycle: true,
            step: 1,
            lazy: true,
            interval: 2800,

            onBefore: function (e, elem, $pane, $items, pos) {
                // hide arrows at limits
                var $prev = $pane.parent().find('.prev');
                $next = $pane.parent().find('.next');

                $prev.add($next).show();
                if (pos == 0)
                    $prev.hide();
                else if (pos == $items.length - 1)
                    $next.hide();

                e.preventDefault();
                if (this.blur)
                    this.blur();
            },
            onAfter: function (elem) {
                //'this' is the element being scrolled ($pane) not jqueryfied
            }
        });


        $('.slider').trigger('start');

    }
});

function highlight(id, location, type, header, image, text, url, more, region, latlong) {
    this.id = id;
    this.location = location;
    this.type = type;
    this.header = header;
    this.image = image;
    this.text = text;
    this.url = url;
    this.more = more;
    this.mapid = 0;
    this.region = region;
    this.latlong = latlong;
}

var mapZoomTimeout;
var isAnimating = true;
var waitTimer;

var Map = {
    "map": null,
    "savedShapes": new Array(),
    "lat": "51.987456",
    "lon": "5.832848",
    "zoom": 10,
    "animateShapesTimeOut": 3000,
    "finalZoomLevel": 11,
    "highlights": new Array(),
    "pauseAnimation": function () {
        isAnimating = false;
        clearTimeout(waitTimer);
    },
    "restartAnimation": function () {
        isAnimating = true;
        clearTimeout(waitTimer);
        waitTimer = setTimeout('isAnimating = true;', 20000);
    },
    "allowRandomRegionHighlightShowing": true,
    //"EntityCollection": new Microsoft.Maps.EntityCollection(),
    "EntityCollection": null,
    "credentials": BINGMAPSCREDENTIALS,
    "init": function (item, newZoomLevel) {


        try {
            var center = new Microsoft.Maps.Location(Map.lat, Map.lon);
            Map.map = new Microsoft.Maps.Map(document.getElementById("mymap"),
            {
                credentials: this.credentials,
                center: center,
                mapTypeId: Microsoft.Maps.MapTypeId.road,
                zoom: Map.zoom,
                showCopyright: false,
                showLogo: false,
                showScalebar: true
            });
            Map.EntityCollection = new Microsoft.Maps.EntityCollection();
        } catch (e) { }
        if (undefined === Map.map) return;


        Map.setCenter(center);
        Map.setZoom(newZoomLevel);

        $(".map-legend input").click(function () {
            var checkedItems = $(".map-legend").find("input:checked");

            if (checkedItems.length > 0) {
                Map.clearPins();
                Map.EntityCollection = new Microsoft.Maps.EntityCollection();

                var type = "";
                checkedItems.each(function (e) {
                    type += ";" + $(this).attr("value");
                    Map.showHighlights("", type);
                });
                Map.AddEntityCollectionToMap();
            }
            else {
                Map.clearPins();
                Map.EntityCollection = new Microsoft.Maps.EntityCollection();
                Map.showHighlights("", undefined);
            }
        });

        // disable auto showing region highlights when mouse hovered the map
        try {
            Microsoft.Maps.Events.addHandler(Map.map, "onmousewheel", function (e) { e.preventDefault(); return false; });
            Microsoft.Maps.Events.addHandler(Map.map, 'mouseover', function (e) { Map.allowRandomRegionHighlightShowing = false; Microsoft.Maps.Events.removeHandler("mouseover") });
        } catch (e) { }
    },
    "ActiveRegionHighlights": new Array(),
    "panToRegion": function (lat, Long, zoom) {

        var regionCenterLocation = new Microsoft.Maps.Location(lat, Long);
        var regionZoom = zoom
        Map.setCenter(regionCenterLocation);
        Map.setZoom(regionZoom);
        if (Map.allowRandomRegionHighlightShowing) {
            Map.animateShapes();
        }
    },
    "GetActiveRegionHighlights": function (regionName) {
        // get all highlights of selected region     
        Map.ActiveRegionHighlights = new Array();
        for (i = 0; i < Map.highlights.length; i++) {
            var h = Map.highlights[i];
            if (h.region == regionName)
                Map.ActiveRegionHighlights.push(h);
        }
    },
    "panToRandomRegion": function (randomShowRegionHighlights) {
        var regions = new Array();
        //retrieve all regions
        for (i = 0; i < Map.highlights.length; i++) {
            var h = Map.highlights[i];
            regions.push(h.region);
        }
        var uniqueArray = $.uniqueArray(regions)
        var randomIndex = Random(uniqueArray.length) - 1
        var randomFoundRegion = uniqueArray[randomIndex]

        // get all highlights of selected region 
        Map.GetActiveRegionHighlights(randomFoundRegion);

        if (Map.ActiveRegionHighlights.length > 0) {
            var params = "regionName=" + randomFoundRegion;
            var getRegionUrl = "/WebServices/RegionService.svc/GetRegionMapInfoByName"
            $.ajax({
                type: "GET",
                data: params,
                url: getRegionUrl,
                cache: false,
                dataType: "json",
                success: function (response) {
                    if (response != "") {
                        var retrievedJsonArray = $.parseJSON(response.d);
                        if (retrievedJsonArray != null) {
                            if (randomShowRegionHighlights && Map.allowRandomRegionHighlightShowing) {
                                Map.panToRegion(retrievedJsonArray.Lat, retrievedJsonArray.Long, retrievedJsonArray.Zoom);
                            }
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //alert(textStatus);
                }
            });
        }
    },
    "AddFilteredEntityCollectionToMap": function (FilteredEntityCollection) {
        if (Map.map != undefined)
            Map.map.entities.push()
    },
    "AddEntityCollectionToMap": function () {
        if (Map.map != undefined)
            Map.map.entities.push(Map.EntityCollection)
    },
    "clearPins": function () {
        if (Map.map != undefined)
            Map.map.entities.clear();
    },
    "zoomIn": function () {
        //Map.ZoomIn();
    },
    "setCenter": function (centerLocation) {
        if (Map.map != undefined) {
            var viewOptions = { center: centerLocation };
            Map.map.setView(viewOptions);
        }
    },
    "CenterToPoiCenter": function () {
        if (Map.map != undefined) {
            var centerLocation = this.EntityCollection.get(0).getLocation();
            var viewOptions = { center: centerLocation };
            Map.map.setView(viewOptions);
        }
    },
    "setZoom": function (zoomValue) {
        if (Map.map != undefined) {
            var viewOptions = { zoom: zoomValue };
            Map.map.setView(viewOptions);
        }
    },
    "startZoomIn": function () {
        var currentZoomLevel;
        if (Map.map != null) {
            currentZoomLevel = Map.map.getZoom();
        } else {
            currentZoomLevel = Map.zoom;
        }
        if (currentZoomLevel < Map.finalZoomLevel) {
            // Start the timeout
            Map.zoomIn();
            Map.zoom++;
            mapZoomTimeout = setTimeout("Map.startZoomIn();", Map.animateShapesTimeOut);
        }
        else {
            // Stop the timeout
            clearTimeout(mapZoomTimeout);
            Map.showHighlights();
        }
    },
    "Counter": 0,
    "addPin": function (lat, lon, icon, header, infobox, type) {
        if (Map.map != undefined) {
            // Create Pushpin
            try {
                var pin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(lat, lon));
                //var headerElement = "<h2>" + header + "</h2>";
                // Create InfoBox
                var extendedInfobox = Microsoft.Maps.Ext.InfoBox(
                    header, /* <-- InfoBox Title to display */
                    infobox, /* <-- InfoBox Description to display */
                    Map.map /* <-- A refernce to the Map where the InfoBox will be displayed */
                );
                //Set the icon
                pin.setOptions({ icon: icon });
                // Add InfoBox to Pushpin
                pin.setInfoBox(extendedInfobox);
                Map.EntityCollection.push(pin);
            }
            catch (e) { }
        }
    },
    "GeoCodeURL": "http://dev.virtualearth.net/REST/v1/Locations/",
    "AddItemAndCenter": function (latLong, type, header, image, text, url, more) {
        if (Map.map != undefined) {
            var newItem = new highlight(0, null, type, header, image, text, url, more, more, latLong);
            Map.addItemH(newItem);
            var center = new Microsoft.Maps.Location(latLong[0], latLong[1]);
            Map.setCenter(center);
        }
    },
    "addItem": function (location, type, header, image, text, url, center, more, target, latlong) {
        var geocodeRequest = Map.GeoCodeURL + location + "?output=json&key=" + Map.credentials + "&jsonp=?";
        if (latlong == undefined || latlong == "") {
            $.getJSON(geocodeRequest, function (result) {
                if (result &&
                    result.resourceSets &&
                    result.resourceSets.length > 0 &&
                    result.resourceSets[0].resources &&
                    result.resourceSets[0].resources.length > 0) {
                    if (null != result.resourceSets[0].resources[0].point) {
                        var latLong = new Array();
                        latLong.push(result.resourceSets[0].resources[0].point.coordinates[0])
                        latLong.push(result.resourceSets[0].resources[0].point.coordinates[1])
                        Map.AddItemAndCenter(latLong, type, header, image, text, url, more);
                    }
                }
            });
        }
        else {
            var latLongArray = new Array()
            var splitted = latlong.split(',')
            latLongArray.push(splitted[0])
            latLongArray.push(splitted[1])
            Map.AddItemAndCenter(latLongArray, type, header, image, text, url, more);
        }
    },
    "addItemH": function (h) {
        var icon_file = "/images/pin_" + h.type + ".png";
        //var icon = "<div><img src='" + icon_file.replace(/\s/g, '_') + "' alt='pin' /></div>";
        var icon = icon_file.replace(/\s/g, '_');
        var infobox = "";
        if ("" !== h.text) {
            infobox += "<span><img src='" + h.image + "' alt='' /></span><p>"
				  + h.text + "</p>";
        }
        if ("" !== h.url) {
            var currentLang = $.getUrlVars()["lang"];

            if(h.url.toLowerCase().indexOf("http://bing.com/maps/default.aspx") < 0)
            {
                if (h.url.toLowerCase().indexOf("http://") < 0)
                    infobox += "<p class='details'><a href='" + h.url + "/?lang=" + currentLang + "'>" + h.more + "</a></p>";
                else
                    infobox += "<p class='details'><a href='" + h.url + "/?lang=" + currentLang + "' target='_blank'>" + h.more + "</a></p>";
            }
            else
            {
                infobox += "<p class='details'><a href='" + h.url + "' target='_blank'>" + h.more + "</a></p>";
            }
        }

        if (h.location != null) {
            var geocodeRequest = Map.GeoCodeURL + h.location + "?output=json&key=" + Map.credentials + "&jsonp=?";
            $.getJSON(geocodeRequest, function (result) {
                if (result &&
                    result.resourceSets &&
                    result.resourceSets.length > 0 &&
                    result.resourceSets[0].resources &&
                    result.resourceSets[0].resources.length > 0) {
                    if (null != result.resourceSets[0].resources[0].point) {
                        id = Map.addPin(result.resourceSets[0].resources[0].point.coordinates[0], result.resourceSets[0].resources[0].point.coordinates[1], icon, h.header, infobox, h.type);
                        h.mapid = id;
                    }
                }

            });
        } else {
            id = Map.addPin(h.latlong[0], h.latlong[1], icon, h.header, infobox, h.type);
            h.mapid = id;
        }
    },
    "addHighlight": function (id, location, type, header, image, text, url, more, region) {
        var h = new highlight(id, location, type, header, image, text, url, more, region);
        Map.highlights[Map.highlights.length] = h;
    },
    "addHighlightByLatLong": function (id, latlon, type, header, image, text, url, more, region) {
        var loc = latlon.split(",");
        var h = new highlight(id, null, type, header, image, text, url, more, region, loc);
        Map.highlights[Map.highlights.length] = h;
    },
    "showHighlights": function (theme, type) {
        for (i = 0; i < Map.highlights.length; i++) {
            var h = Map.highlights[i];

            if ("" != h.location && (undefined == type || "" == type || -1 != type.indexOf(h.type))) {
                Map.addItemH(h);
            }
        }

        if (type == undefined || type == "")
            Map.AddEntityCollectionToMap();
    },
    "addHighlightIcon": function (location, type, header, image, text) {
        if ("" != location) Map.addItem(location, type, header, image, text, "", true);
    },
    "addHotelIcon": function (location) {
        if ("" != location) Map.addItem(location, "hotel", "", "", "", "", true);
    },
    "showCurrentHotels": function () {
        $(".hotel-list .preview").each(function (i) {
            var h2 = $(this).children("h2:eq(0)");
            var img = $(this).children("a").children("img");
            if ("" != h2.attr("data-location")) Map.addItem(h2.attr("data-location"), "hotel", h2.attr("data-name"), img.attr("src"), h2.attr("data-description"), h2.attr("data-url"), false, h2.attr("data-more"));
        });
    },
    "animateShapes": function () {
        if (!isAnimating) {
            setTimeout(Map.animateShapes, Map.animateShapesTimeOut);
            return;
        }

        // get an random item from the saved current active region highlights
        var randomIndex = Random(Map.ActiveRegionHighlights.length) - 1;
        var foundRandomHighlight = Map.ActiveRegionHighlights[randomIndex];

        if (0 < Map.map.entities.getLength()) {

            var highlightLat = foundRandomHighlight.latlong[0]
            var highlightLong = foundRandomHighlight.latlong[1]
            var shape = null;

            // find the pin in the map by random highlight latlong
            for (i = 0; i < Map.map.entities.get(0).getLength(); i++) {
                var item = Map.map.entities.get(0).get(i);
                var itemLocation = item.getLocation();
                if (itemLocation.latitude == highlightLat && itemLocation.longitude == highlightLong) {
                    shape = item;
                }
            }

            if (Map.allowRandomRegionHighlightShowing) {
                if (undefined == shape || null == shape) {
                    setTimeout(Map.animateShapes, Map.animateShapesTimeOut);
                } else {
                    //var location = shape.getLocation();

                    // Map.map.setView({ center: new Microsoft.Maps.Location(location.latitude, location.longitude + 1.25) });
                    shape.infobox.show(shape);
                    //map.tryLocationToPixel();  // 0.69
                    setTimeout(function () { Map.animateShapes() }, Map.animateShapesTimeOut);
                }
            }
        }
    },
    "animateShapes2": function (shape) {
        //shape.infobox.show(this);
        //setTimeout(Map.animateShapes, 10000);
    },

    "FilterByIdArray": function (stringArray) {
        if (stringArray != undefined && stringArray.length > 0) {
            for (a = 0; a < stringArray.length; a++) {
                for (i = 0; i < Map.highlights.length; i++) {
                    var h = Map.highlights[i];
                    if (h.id == stringArray[a]) {
                        Map.addItemH(h);
                    }
                }
            }
        }
    }
};

function Random(r) {
    return Math.ceil(Math.random() * r);
}

function daysInMonth(month, year) {
    return 32 - new Date(year, month - 1, 32).getDate();
}

function ShowHideVideo(id) {
    //hide videos
    $(".videos").hide();
    $("#videowindow").empty()
    $("#ytvideo" + id).clone().appendTo($("#videowindow")).show();
}

var Lst;

function SelectedVideoLink(obj) {
    if (Lst) Lst.className = '';
    obj.className = 'selected';
    Lst = obj;
}

/* Loading animations */
function ShowOrHideElementLoadingScreen(show, element, duration) {
    if (show)
        $(element).css("display", "block")

    var opacity = show ? 1 : 0;
    $(element).animate
	(
		{
		    opacity: opacity
		},
		duration,
		function () {
		    if (!show)
		        $(element).css("display", "none")
		}
	)
}

var LoadingAnimationClassName = "LoadingAnimationContainer";
var HighlightsAnimationContainerId = "HighlightsAnimationContainer";
var HighlightsListContainer = "HighlightsContainer";

function ShowLoadingScreen(loadingParentElement, AnimationContainerId) {
    if (AnimationContainerId != "" && loadingParentElement != "") {
        var loadingElement = $("#" + AnimationContainerId);
        //check if element already exists
        if (loadingElement.length == 0) {
            loadingParentElement.prepend("<div class='" + LoadingAnimationClassName + "'></div>");
            loadingElement = loadingParentElement.children("'." + LoadingAnimationClassName + ":eq(0)'")
            loadingElement.attr("id", AnimationContainerId)
        }
        ShowOrHideElementLoadingScreen(true, loadingElement, 500);
    }
}
function HideLoadingScreen(AnimationContainerId) {
    var loadingElement = $("#" + AnimationContainerId);
    if (loadingElement.length > 0)
        ShowOrHideElementLoadingScreen(false, loadingElement, 500);
}

function ShowLoadingScreenForFilterHighlights() {
    ShowLoadingScreen($("#" + HighlightsListContainer), HighlightsAnimationContainerId);
}
function HideLoadingScreenForFilterHighlights() {
    HideLoadingScreen(HighlightsAnimationContainerId);
}



/* Loading animations */

/* TRAVELBAG */
var TravelBag = {
    "CookieName": "TravelBagItems",
    "Items": null,
    "Button": null,
    "ButtonItemId": "",
    "RedirectToTravelBagPageWhenAlreadyAdded": true,
    "SetText": function (text) {
        $(this.Button).text(text);
        $(this.Button).attr("title", text);
    },
    "DisableButton": function () {
        this.Button.addClass("AddToTravelBagButton-disabled");
    },
    "WriteItemsToCookie": function () {
        $.cookie(this.CookieName, $.toJSON(this.Items.TravelBagItems), { expires: 7, path: '/' });
        this.SetTravelBagItemsArrayByCookie();
    },
    "SetTravelBagItemsArrayByCookie": function () {

        TravelBag.Items = $.parseJSON('{"TravelBagItems":[]}');
        // get the json array from cookie
        try {
            if ($.cookie(this.CookieName) != "[]" && $.cookie(this.CookieName) != null && $.cookie(this.CookieName) != undefined && $.cookie(this.CookieName) != "" && $.cookie(this.CookieName) != '{}') {
                TravelBag.Items.TravelBagItems = $.parseJSON($.cookie(this.CookieName));
                if (TravelBag.Items.TravelBagItems.push == undefined || TravelBag.Items.TravelBagItems.push == null)
                    TravelBag.Items.TravelBagItems = $.parseJSON($.parseJSON($.cookie(this.CookieName)));
            }
        }
        catch (e) { }
    },
    "Init": function () {
        this.Button = $(".AddToTravelBagButton:eq(0)");
        this.SetTravelBagItemsArrayByCookie();

        if (this.Button.length > 0) {
            this.ButtonItemId = this.Button.attr("data-id");
            var alreadyAdded = false;
            if (this.Items.TravelBagItems != undefined) {
                $.each(this.Items.TravelBagItems, function (index, element) {
                    var id = element["id"];
                    if (TravelBag.ButtonItemId == id) {
                        alreadyAdded = true;
                    }
                })
            }

            if (alreadyAdded) {
                // if already added
                this.SetText(TRAVELBAGALREADYADDEDTEXT);
                this.DisableButton();
            }
            else {
                this.SetText(TRAVELBAGADDTEXT);
                //bind travelbag button click
                if (this.Button.length > 0) {
                    this.Button.click(function (e) {
                        TravelBag.Add(e);
                    });
                }
            }

            // if everything went well we show the button
            this.Button.css("display", "block");
            this.Button.animate
	        (
		        {
		            opacity: 1
		        },
		        400,
		        function () { }
	        )
        }
    },
    "Add": function (e) {
        if (TravelBag.RedirectToTravelBagPageWhenAlreadyAdded)
            e.preventDefault();

        // now add the item to the json array
        var id = this.Button.attr("data-id");
        var newJsonPart = { "id": id };

        if (TravelBag.Items.TravelBagItems.push == undefined) // check if travelbagitems is still an object/array
            TravelBag.Items.TravelBagItems = $.parseJSON(TravelBag.Items.TravelBagItems);

        //first check if item doesn't already exists in array
        var alreadyExists = false;
        if (TravelBag.Items.TravelBagItems != undefined) {
            $.each(TravelBag.Items.TravelBagItems, function (index, element) {
                var id = element["id"];
                if (TravelBag.ButtonItemId == id) {
                    alreadyExists = true;
                }
            })
        }

        var itemCountBeforePush = TravelBag.Items.TravelBagItems.length;

        if (!alreadyExists && TravelBag.Items.TravelBagItems.push != null && TravelBag.Items.TravelBagItems.push != undefined)// fixes concurrency problems
        {
            TravelBag.Items.TravelBagItems.push(newJsonPart);
            // write the updated json string to cookies
            TravelBag.WriteItemsToCookie();
        }

        // Check if push has succeeded
        if (itemCountBeforePush < TravelBag.Items.TravelBagItems.length) {
            // give message,change button text and unbind button click so it will redirect to travelbag page when clicked
            alert(TRAVELBAGSUCCESSFULLYADDEDTEXT);
            this.SetText(TRAVELBAGALREADYADDEDTEXT);
            TravelBagItemCount.SetCount(TravelBagItemCount.Count + 1);
        }
        else {
            alert(TRAVELBAGADDINGFAILEDBECAUSEITSFULL);
            this.SetText(TRAVELBAGFULLTEXT);
        }
        this.DisableButton();
        this.Button.unbind('click');

    },
    "Remove": function () {
        alert(TRAVELBAGSUCCESSFULLYREMOVEDTEXT);
    }
}

var TravelBagList = {
    "Id": "TravelBagItemList",
    "List": null,
    "AnimationDuration": 600,
    "DeleteItem": function (buttonElement, dataIdOfSaveTravelBagItem) {

        $(".DeleteTravelMapItem").css("display", "none") // remove temp all delete buttons in list so we dont get concurreny problems

        // now that the element is invisible we can remove it from the cookie
        try {
            var tempList = $.parseJSON('{"TravelBagItems":[]}');
            if (TravelBag.Items.TravelBagItems != undefined && TravelBagItemCount.Count > 1) {
                $.each($.parseJSON(TravelBag.Items.TravelBagItems), function (index, Element) {
                    var id = Element["id"];
                    if (dataIdOfSaveTravelBagItem != id) {
                        tempList.TravelBagItems.push(Element);
                    }
                })
            }
        } catch (e) { }

        TravelBag.Items.TravelBagItems = tempList.TravelBagItems;
        TravelBag.WriteItemsToCookie(); // write edited items to cookie
        TravelBagItemCount.SetCount(TravelBagItemCount.Count - 1);

        if (TravelBagItemCount.Count < 1) { // if travelbagItemcount is smaller then 0
            $("#TravelBagButtonPrint").css("display", "none")// hide print button
            $("#TravelBagEmptyDescription").css("display", "block") // show empty bag text
        }

        var parentPreviewEl = $(buttonElement).parents(".preview:eq(0)");
        $(parentPreviewEl).animate
	    (
		    {
		        height: 0
		    },
		    TravelBagList.AnimationDuration,
		    function () {
		        $(this).css("display", "none")
		        $(".DeleteTravelMapItem").css("display", "block") // remove temp all delete buttons in list so we dont get concurreny problems	       	        
		    }
	    )
    },
    "Init": function () {
        var currentLang = $.getUrlVars()["lang"];
        if (currentLang != "lang") {
            this.List = $("#" + this.Id);
            // check if we have items in cookie 
            var cookieResult = $.cookie(TravelBag.CookieName);
            if (cookieResult != null && cookieResult != undefined && cookieResult != "[]") {
                TravelBag.Items.TravelBagItems = $.cookie(TravelBag.CookieName);
                var travelBagWebserviceUrl = "/WebServices/TravelBagService.svc/GetTravelBagItems";
                var commaSeperatedIds = new Array();
                // get all saved ids
                $.each($.parseJSON(TravelBag.Items.TravelBagItems), function (index, Element) {
                    var id = Element["id"];
                    commaSeperatedIds.push(id);
                })
                var travelBagParams = "travelBagItemIds=" + commaSeperatedIds + "&lang=" + currentLang;

                //first retrieve the full json array by webservice
                $.ajax({
                    type: "GET",
                    data: travelBagParams,
                    url: travelBagWebserviceUrl,
                    cache: false,
                    dataType: "json",
                    success: function (response) {
                        if (response != "") {
                            var retrievedJsonArray = $.parseJSON(response.d);
                            var markup = "<div class='preview'><a data-id='${Id}' class='DeleteTravelMapItem'>" + TRAVELBAGDELETEITEM + "</a><img src='${Thumbnail}'/><h2><a href='${Url}'>${Title}</a></h2>";
                            markup += "<p class='short-description'>${ShortDescription}</p>";
                            markup += "<p class='description'>${Description}</p>";
                            markup += "<p class='address'>${Address}</p>";
                            markup += "<p class='read-more'><a href='${Url}'>" + READMORECOPY + "</a></p>";
                            markup += "</div>";

                            $.template("movieTemplate", markup);
                            $.tmpl("movieTemplate", retrievedJsonArray).appendTo("#" + TravelBagList.Id);

                            if ($("#" + TravelBagList.Id).length > 0) {
                                var items = $("#" + TravelBagList.Id)[0].children;
                                for (var i = 0; i < items.length; i++) {
                                    var descriptionElement = $(items[i]).children(".description:eq(0)");
                                    var encodedStr = descriptionElement.html();
                                    var decodedString = $('<div/>').html(encodedStr).text();
                                    descriptionElement.html(decodedString);
                                }
                            }

                            // now that the template is set we can bind the delete button with click event
                            $(".DeleteTravelMapItem").click(function (e) {
                                e.preventDefault();
                                TravelBagList.DeleteItem(this, $(this).attr("data-id"));
                            });
                            $("#TravelBagButtonPrint").css("display", "block")
                        }
                        else {
                            $("#TravelBagEmptyDescription").css("display", "block")
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        //alert(textStatus);
                    }
                });
            }
            else {
                $("#TravelBagEmptyDescription").css("display", "block")
            }
        }
    }
}

var TravelBagItemCount = {
    "Id": "TravelBagItemCount",
    "Button": null,
    "Count": 0,
    "SetCount": function (newCount) {
        TravelBagItemCount.Count = newCount;
        TravelBagItemCount.Button.text(newCount);
    },
    "Init": function () {
        TravelBagItemCount.Button = $("#" + this.Id);
        var count = 0;
        if (TravelBagItemCount.Button.length > 0 && TravelBag.Items != null && TravelBag.Items.TravelBagItems != null && $.parseJSON(TravelBag.Items.TravelBagItems) != null) {
            count = $.parseJSON(TravelBag.Items.TravelBagItems).length;
        }
        else if (TravelBag.Items.TravelBagItems.length != null) {
            count = TravelBag.Items.TravelBagItems.length;
        }
        TravelBagItemCount.SetCount(count);
    }
};

$(document).ready(function () {
    TravelBag.Init();
    TravelBagList.Init();
    TravelBagItemCount.Init();
});
/* END TRAVELBAG */
