﻿var current_section = 1;

/*  maps section    */
$(window).load(function() {

	var config = {
		"trailsId": "trails",
		"trailTypes": [["Trails", "12"], ["Cycle Routes", "22"]]
	};

	$('#accTypes').mousemove(
        function(e) {
        	$('#hoverInfo').show();
        	var y = e.pageY + 10;
        	$('#hoverInfo').css('top', y + 'px');
        	$('#hoverInfo').css('left', e.pageX + 'px');
        });
	$('#accTypes').mouseout(
        function(e) {
        	$('#hoverInfo').hide();
        });

	$('.plan_your_visit_control_clear_button').click(function() {
		clearMap();  // redraw attractions
		$('input[id*="location_search_input"]').val('Location / Postcode');
		$("input[type*='checkbox']").each(function() {
			this.checked = false;
		});
	});

	$('#tailCollection > input').click(function() {
		$('#tailCollection > input').each(function() {
			if (parseInt($(this).attr('value'))) {
				if (this.checked)
					GetTrailInfo($(this).attr('value'));
			}
			else {
				GetSites(this, $(this).attr('value'));
			}
		});
	});

	$('.show_accommodationType_panel_map input[type="checkbox"]').click(function() {
		$('.bottom_map_toolbar #text').html('<span class="loading">Loading...</span>');

		var removeLoading = function() {
			$('.bottom_map_toolbar .loading').remove();
		};

		var latlng = map.getCenter();
		$.ajax({
			url: "js/ajaxhandler.aspx",
			data: "Method=GetAccFromFilter&ID=" + this.value + "&Lat=" + map.getCenter().y + "&Lon=" + map.getCenter().x + "&Date=" + new Date().getSeconds(),
			success: function(xml) {
				clearMap();
				var chris = new Array();
				if ($(xml).find("Attraction").text() != "") {
					$(xml).find("Attraction").each(function() {
						chris.push(new Array($(this).find("Name").text(),
                                            $(this).find("ImageName").text(),
                                            $(this).find("Lat").text(),
                                            $(this).find("Lon").text(),
                                            $(this).find("Description").text(),
                                            $(this).find("ContactTel").text(),
                                            $(this).find("ContactFax").text(),
                                            $(this).find("Facilities").text(),
                                            $(this).find("Ratings").text(),
                                            $(this).find("Awards").text(),
                                            $(this).find("Owner").text(),
                                            $(this).find("Address").text(),
                                            $(this).find("Website").text(),
                                            new Array($(this).find("Lat").text(), $(this).find("Lon").text()),
                                            $(this).find("linkNumber").text()));
					});
					var bounds = new GLatLngBounds;
					for (var i = 0; i < chris.length; i++) {
						plotTabbedMarker(chris[i]);
						var latlng = new GLatLng(chris[i][13][0], chris[i][13][1]);
						bounds.extend(latlng);
					}
					map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
				}
				else {
					alert("No Results Found");
				}
				removeLoading();
			},
			error: function() {
				removeLoading();
			}
		});
	});

	$('.page_title_toolbar #accTypes').click(function() {
		if ($(".show_accommodationType_panel_map").css("display") == "none") {
			if ($(".show_accommodationType_panel_error").css("display") != "none") {
				$(".show_accommodationType_panel_error").slideUp("normal");
			}
			else {
				if (parseInt(map.getZoom()) >= 10) {
					$(".show_accommodationType_panel_error").slideUp("normal");
					$(".show_accommodationType_panel_map").slideDown("normal");
				}
				else {
					$(".show_accommodationType_panel_map").slideUp("normal");
					$(".show_accommodationType_panel_error").slideDown("normal");
				}
			}
		}
		else {
			$(".show_accommodationType_panel_map").slideUp("normal");
		}
	});

	initialize();

	$("#location_search_input").keyup(function(event) {
		if (event.keyCode == 13) {//enter
			beginLocationSearch();
		}
	});

	// search box functions
	$("#location_search_input").focus(function() {
		if ($(this).val() == "Location / Postcode") {
			$(this).val("");
		}
	});
	$("#location_search_input").blur(function() {
		if ($(this).val() == "") {
			$(this).val("Location / Postcode");
		}
	});
	// end of search box functions

	// controlled search functions
	$(".show_controlledsearch").click(function(e) {
		if ($(".show_controlledsearch_panel").css("display") == "none")
			$(".show_controlledsearch_panel").slideDown("normal");
		else
			$(".show_controlledsearch_panel").slideUp("normal");
	});

	$("#close_show_controlledsearch").click(function(e) {
		$(".show_controlledsearch_panel").slideUp("normal");
	});

	$(".left_container > ul > li").click(function() {
		$(".left_container > ul > li").removeClass("selected");
		$(this).addClass("selected");
		if ($(this).attr('id') === config.trailsId) {
			var types = config.trailTypes;
			var $container = $('.type_container');
			$container.html('');
			for (var i = 0; i < types.length; i++) {
				$container.append('<div class="scroll_container" id="' + types[i][1] + '" >' + types[i][0] + '</div>');
			}
			scrollLength = ($('.scroll span > div').length);
			selectedIndex = 0;
			$("#arrow_next, #arrow_prev").unbind('click');
			attachScrollEvents("TrailSearch");
			var firstChildID = config.trailTypes[0][1];
			$.ajax({
				url: "js/ajaxhandler.aspx",
				data: "Method=TrailSearch&ID=" + firstChildID,
				success: function(html) {
					displayContent(html);
				}
			});
			$('#chkSelectAll').change(function() {
				$("input[type*='checkbox']").each(function() {
					this.checked = true;
				});
			});
		} else {
			$.ajax({
				url: "js/ajaxhandler.aspx",
				data: "ID=" + $(this).attr('ID') + "&Method=MenuSelector",
				type: "GET",
				dataType: "xml",
				success: function(xml) {
					$('.type_container').html('');
					$(xml).find("Type").each(function() {
						$('.type_container').append("<div class=\"scroll_container\" id=\"" + $(this).find("Code").text() + "\">" + $(this).find('Title').text() + "</div>");
					});
					scrollLength = ($('.scroll span > div').length);
					selectedIndex = 0;
					//$('#type').scrollLeft($('.scroll div:eq(' + selectedIndex + ')'), 600, { axis: 'x' });
					$('.scroll_container').hide();
					$('.scroll div:eq(' + selectedIndex + ')').show();
					$("#arrow_next, #arrow_prev").unbind('click');
					var firstChildID = $(xml).find("Code:first").text();
					switch ($(xml).find("MenuItem").text()) {
						case "acc":
							attachScrollEvents("CategoryTypeSearch");
							$.ajax({
								url: "js/ajaxhandler.aspx",
								data: "Method=CategoryTypeSearch&ID=" + firstChildID,
								success: function(html) {
									clearMap();
									displayContent(html);
								}
							});
							break;
						case "front":
							attachScrollEvents("FrontierSearch");
							$.ajax({
								url: "js/ajaxhandler.aspx",
								data: "Method=FrontierSearch&ID=" + firstChildID,
								success: function(html) {
									clearMap();
									displayContent(html);
								}
							});
							break;
						case "attr":
							attachScrollEvents("GetAttractions");
							$.ajax({
								url: "js/ajaxhandler.aspx",
								data: "Method=GetAttractions&ID=" + firstChildID,
								success: function(html) {
									clearMap();
									displayContent(html);
								}
							});
							break;

						default:
							$('.search_ContentArea').html("No Results Found");
							break;
					}

					$('#chkSelectAll').change(function() {
						$("input[type*='checkbox']").each(function() {
							this.checked = true;
						});
					});
				}
			});
		}
	});

	// end of controlled search functions
});

scrollLength = ($('.scroll span > div').length);
selectedIndex = 0;
function attachScrollEvents(method) {
	$("#arrow_next").click(function() {
		selectedIndex = (selectedIndex == (scrollLength - 1)) ? 0 : (selectedIndex + 1);
		//$('#type').scrollLeft($('.scroll div:eq(' + selectedIndex + ')'), 600, { axis: 'x' });
		$('.scroll_container').hide();
		$('.scroll div:eq(' + selectedIndex + ')').show();
		$.ajax({
			url: "js/ajaxhandler.aspx",
			data: "Method=" + method + "&ID=" + $('.scroll div:eq(' + selectedIndex + ')').attr('ID'),
			success: function(html) {
				displayContent(html);
			}
		});
	});
	$("#arrow_prev").click(function() {
		selectedIndex = (selectedIndex == 0) ? (scrollLength - 1) : (selectedIndex - 1);
		//$('#type').scrollLeft($('.scroll div:eq(' + selectedIndex + ')'), 600, { axis: 'x' });
		$('.scroll_container').hide();
		$('.scroll div:eq(' + selectedIndex + ')').show();
		$.ajax({
			url: "js/ajaxhandler.aspx",
			data: "Method=" + method + "&ID=" + $('.scroll div:eq(' + selectedIndex + ')').attr('ID'),
			success: function(html) {
				displayContent(html);
			}
		});
	});
}

function displayContent(html) {
    if (typeof (html) == "string") {
        $('.search_ContentArea').html(html);
    }
    else if (typeof (html) == "object") {
        PlotAttractions();
        if ($(html).find("Description").text() != "") {
            var description = $(html).find("Description").text() + "<br /><a href='page.aspx?page_id=" + $(html).find("Link").text() + "'>Click here</a> to view the experience";
            $('.search_ContentArea').html(description);
        }
        var color = $(html).find("LineColor").text();
        var latLngArr = new Array();
        var bounds = new GLatLngBounds;
        $(html).find("CoOrdinate").each(function() {
            var lat = $(this).find("Lat").text();
            var lng = $(this).find("Lon").text();
            var latLng = new GLatLng(lat, lng);
            bounds.extend(latLng);
            latLngArr.push(latLng);
        });

        $(html).find("Plot").each(function() {
            var lat = $(this).find("Lat").text();
            var lng = $(this).find("Lng").text();
            var latLng = new GLatLng(lat, lng);
            var siteIcon = new GIcon();
            var iconPath = 'images/icons/';
            var iconImg = '';
            if ($(this).find("Type").text() == "1") {
                iconImg = 'frontierIcon.png';
            } else {
                iconImg = 'frontierIconWall.png';
            }
            siteIcon.image = iconPath + iconImg;
            siteIcon.transparent = iconPath + iconImg;
            siteIcon.iconAnchor = new GPoint(10, 10);
            var marker = new GMarker(latLng, { icon: siteIcon, title: $(this).find("Name").text() });
            map.addOverlay(marker);

        });
        var polyLine = new GPolyline(latLngArr, color);
        map.addOverlay(polyLine);
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    }
    attachShowHide();
}



/*  end of maps section */

/*  14 Attractions  */

function PlotAttractions() {
    for (var i = 0; i < attractions.length; i++) {
        var latlng = new GLatLng(attractions[i][2][0], attractions[i][2][1]);
        
        //create start GIcon
        var attractionIcon = new GIcon();
        var img = new Image();
        img.src = "images/Icons/" + attractions[i][1];
        attractionIcon.image = img.src;

        (function() {
                var currentAttration = attractions[i];
                $("img").ready(function() {
                    //img.onload = function() {
                    //alert("img loaded");
                    //console.log("width " + this.width);
                    //var centerWidth = this.width / 2;
                    //var centerHeight = this.height / 2;

                    //var iconScale = 0.5;

                    //var newHeight = this.height * iconScale;
                    //var newWidth = this.width * iconScale;


                    //attractionIcon.iconSize = new GSize(newWidth, newHeight);
                    //attractionIcon.iconAnchor = new GPoint(centerWidth, centerHeight);
                    attractionIcon.infoWindowAnchor = new GPoint(5, 1);
                    if (currentAttration[1] == "") {
                        var marker = new GMarker(latlng);
                        map.addOverlay(marker);
                    } else {
                        //alert("..plotTabbedMarker");
                        plotTabbedMarker(currentAttration);
                    };


                    // };
                });
            })();      
        
    }

}

var sitesArray = new Array();
var wallSitesArray = new Array();
function GetSites(target, remains) {
    $('.bottom_map_toolbar #text').html('<span class="loading">Loading...</span>');

    var removeLoading = function() {
        $('.bottom_map_toolbar .loading').remove();
    };
    if(remains=="true"){
        //alert("plot sites with walls: " + remains + " target = " + target);
        if (target.checked) {
            $.ajax({
                type: "GET",
                url: "js/ajaxhandler.aspx",
                data: "Method=GetSites_wall&Date=" + new Date().getTime(),
                dataType: "xml",
                success: function(xml) {
                    sitesArray = new Array();
                    $(xml).find('Site').each(function() {
                        var img = "images/icons/frontierIconWall.png";
                        var siteIcon = new GIcon();
                        icon.image = img;
                        siteIcon.transparent = img;
                        siteIcon.iconAnchor = new GPoint(10, 10);
                        var lat = $(this).find("Lat").text();
                        var lng = $(this).find("Lng").text();
                        var latLng = new GLatLng(lat, lng);
                        var name = $(this).find("Name").text();
                        var marker = new GMarker(latLng, { icon: siteIcon, title: name });
                        if (sitesArray.indexOf(marker) > -1) {
                            wallSitesArray[sitesArray.indexOf(marker)].show();
                        } else {
                            wallSitesArray.push(marker);
                            map.addOverlay(marker);
                        }
                        removeLoading();    
                    }); //close each
                }, //success
                error: function() {
                    removeLoading();
                }
            });        //ajax
        }else{
            for (var i = 0; i < wallSitesArray.length; i++) {
                wallSitesArray[i].hide();
            }
            removeLoading();
        }
    } else {

        if (target.checked) {
            $.ajax({
                type: "GET",
                url: "js/ajaxhandler.aspx",
                data: "Method=GetSites_noWall&Date=" + new Date().getTime(),
                dataType: "xml",
                success: function(xml) {
                    sitesArray = new Array();
                    $(xml).find('Site').each(function() {
                        var img = "images/icons/frontierIcon.png";
                        var siteIcon = new GIcon();
                        icon.image = img;
                        siteIcon.transparent = img;
                        siteIcon.iconAnchor = new GPoint(10, 10);
                        var lat = $(this).find("Lat").text();
                        var lng = $(this).find("Lng").text();
                        var name = $(this).find("Name").text();
                        var latLng = new GLatLng(lat, lng);
                        var marker = new GMarker(latLng, { icon: siteIcon, title: name });
                        if (sitesArray.indexOf(marker) > -1) {
                            sitesArray[sitesArray.indexOf(marker)].show();
                        } else {
                            sitesArray.push(marker);
                            map.addOverlay(marker)
                        }
                    }); //close each
                    removeLoading();
                }, //success
                error: function() {
                    removeLoading();
                }
            });     //ajax
        } else {
            for (var i = 0; i < sitesArray.length;  i++) {
                sitesArray[i].hide();
            }
            removeLoading();
        }
    }
}
function PlotSites(wall) {
    var targArr = new Array();
    var img = "images/icons/";
    if (wall) {
        targArr = wallSitesArray;
        img += "frontierIcon.jpg";
    } else {
        targArr = sitesArray;
        img += "frontierIconWall.jpg";
    }
    for (var i = 0; i < targArr.length; i++) {
        
    }
}

   var _plainMarkerArr = new Array();


   function plotTabbedMarker(attraction) {
       //alert("plotting tabbed marker");
       //create start GIcon
       var attractionIcon = new GIcon();
      
       var marker;
       (function() {
               //alert("plotTabbed Marker,"+attraction[1]);
               var currentAttration = attraction[0];
               var img = new Image();
               img.src = "images/Icons/" + attraction[1];
               attractionIcon.image = img.src;
               //alert("called!");
               $("img").ready(function() {
                   //img.onload = function() {
                   //console.log("width " + this.width);
                   // alert("ffWidth = "+this.width)
                   //alert("width: " + img.width);
                   //var centerWidth = (this.width * 0.25);
                   //var centerHeight = (this.height * 0.25);

                   var iconScale = 0.5;

                   //var newHeight = this.height * iconScale;
                   //var newWidth = this.width * iconScale;

                   //alert("width"+newWidth);
                   if (attraction[1] != "" && attraction[1] != null) {

                       attractionIcon.image = "images/Icons/" + attraction[1];
                       //attractionIcon.iconSize = new GSize(50,50);


                       //attractionIcon.iconSize = new GSize(newWidth, newHeight);
                       //attractionIcon.iconAnchor = new GPoint(centerWidth, centerHeight);
                       //attractionIcon.iconAnchor = new GPoint(0, 0);
                       //                       attractionIcon.infoWindowAnchor = new GPoint(5, 1);
                       //                       marker = new GMarker(new GLatLng(attraction[12][0], attraction[12][1]), { icon: attractionIcon, title: attraction[0] });
                       //                   }
                       //IMAGE MAPS

                       //var thisWidth = this.width * 0.5;
                       //var thisHeight = this.height * 0.5;
                       //EXCEPTIONS FOR THREE VINODLANDA, ROMAN ARMY, BIRDOSWALD

                       switch (attraction[0]) {
                           case "Roman Vindolanda":
                               attractionIcon.infoWindowAnchor = new GPoint(10, 0);
                               attractionIcon.iconAnchor = new GPoint(10, 0);
                               break;
                           case "Roman Army Museum":
                               attractionIcon.infoWindowAnchor = new GPoint(0, 0);
                               attractionIcon.iconAnchor = new GPoint(0, 0);
                               break;
                           case "Northumberland Nation Park Centre, Once Brewed":
                               attractionIcon.infoWindowAnchor = new GPoint(0, 0);
                               attractionIcon.iconAnchor = new GPoint(0, 0);
                               break;
                           case "Birdoswald Roman Fort":
                               attractionIcon.infoWindowAnchor = new GPoint(17, 12);
                               attractionIcon.iconAnchor = new GPoint(17, 12);
                               break;
                           case "Housesteads Roman Fort":
                               attractionIcon.infoWindowAnchor = new GPoint(17, 12);
                               attractionIcon.iconAnchor = new GPoint(17, 12);
                               break;
                           case "The Great North Museum":
                               attractionIcon.infoWindowAnchor = new GPoint(20, 10);
                               attractionIcon.iconAnchor = new GPoint(20, 10);
                               break;
                           default:
                               attractionIcon.infoWindowAnchor = new GPoint(0, 0);
                               attractionIcon.iconAnchor = new GPoint(0, 0);
                               break;


                       }
                       marker = new GMarker(new GLatLng(attraction[13][0], attraction[13][1]), { icon: attractionIcon, title: attraction[0] });

                   }
                   else {
                       marker = new GMarker(new GLatLng(attraction[13][0], attraction[13][1]), { title: attraction[0] });
                       _plainMarkerArr.push(marker);
                   }

                   var title = attraction[0];

                   //description
                   var description = jQuery.trim(attraction[4]);
                   description = description.replace(/\"/g, '');
                   description = description.replace(/\'/g, '');
                   description = description.replace(/\r/g, '');
                   description = description.replace(/\t/g, ' ');
                   description = description.replace(/\n/g, '<br />');

                   //var roomTypes = poi[trail][pointOfInterest][4][1]; //"<table><tr><td>Room Type</td><td>Min</td><td>Max</td></tr><tr><td>The Stabels Cottage</td><td>£400</td><td>£710</td></tr></table>";
                   //Facilities
                   var facilities_icons = attraction[7];
                   var awards_icons = attraction[8];
                   var ratings_icons = attraction[9];
                   //contact
                   //debugger;
                   var proprietor = attraction[10];
                   var address = attraction[11];
                   var tel = attraction[5];
                   var fax = attraction[6];
                   var website = jQuery.trim(attraction[12]);
                   var webstr = ((website == "") || (website == null)) ? "No Website" : "<a href=" + website + "> " + website + "</a>";
                   var titleLink = (attraction[14] != null) ? "<a href=" + attraction[14] + ">" + title + "</a>" : title;

                   var cont_desc = "<h2>" + titleLink + "</h2><h3>Description:</h3>" + description + "";
                   var cont_fac = "<h2>" + titleLink + "</h2><h3>Facilities:</h3><div id=infoWindow_fac>" + facilities_icons + "</div>";
                   var cont_awd = "<h3>Awards</h3><div id=infoWindow_awards>" + awards_icons + "</div>";
                   var cont_contact = "<h2>" + titleLink + "</h2><h3>Proprietor / Manager:</h3><p>" + proprietor + "</p><br /><h3>Address</h3><p>" + address.replace(/\|\|/g, '<br />') + "</p><br /><h3>Contact</h3><p><b>Tel:</b> " + tel + "<br /><b>Fax:</b> " + fax + "<br /><b>Website:</b> " + webstr + "</p>";
                   cont_desc = cont_desc.replace(/\"/g, '');
                   cont_desc = cont_desc.replace(/\'/g, '');
                   cont_fac = cont_fac.replace(/\"/g, '');
                   cont_fac = cont_fac.replace(/\'/g, '');
                   cont_awd = cont_fac.replace(/\"/g, '');
                   cont_awd = cont_fac.replace(/\'/g, '');

                   var fac_icons = new Array();
                   var this_split = new Array();
                   var my_icons = attraction[7];
                   my_icons = my_icons.replace(/\|\|/g, '|');
                   my_icons = my_icons.replace(/\"/g, '');
                   my_icons = my_icons.replace(/\'/g, '');
                   my_icons = my_icons.replace(/\n/g, '<br />');
                   fac_icons = my_icons.split('|');
                   my_icons = "";
                   for (faci = 0; faci < fac_icons.length; faci++) {
                       this_split = fac_icons[faci].split("~");
                       if (this_split[0] != "") {
                           my_icons += '<img style=\\\'border-width: 0px;\\\' src=\\\'/images/ENet/facilities_icons/' + this_split[0] + '.gif\\\' alt=\\\'' + this_split[1] + '\\\' title=\\\'' + this_split[1] + '\\\' />';
                       }
                   }
                   cont_fac = "<h2>" + titleLink + "</h2><h3>Facilities:</h3><div id=infoWindow_fac><span>" + my_icons + "</span></div>";

                   // Redo for Awards
                   var awd_icons = new Array();
                   my_icons = attraction[9];
                   my_icons = my_icons.replace(/\|\|/g, '|');
                   my_icons = my_icons.replace(/\"/g, '');
                   my_icons = my_icons.replace(/\'/g, '');
                   my_icons = my_icons.replace(/\n/g, '<br />');
                   awd_icons = my_icons.split('|');
                   my_icons = "";
                   for (faci = 0; faci < (awd_icons.length - 1); faci++) {
                       this_split = awd_icons[faci].split("~");
                       if (this_split[0] != "" && this_split[1] != "undefined") {
                           my_icons += '<img style=\\\'border-width: 0px;\\\' src=\\\'/images/ENet/support_icons/' + this_split[1] + '\\\' alt=\\\'' + this_split[0] + '\\\' title=\\\'' + this_split[0] + '\\\' />';
                       }
                   }
                   cont_awd = "<h3>Awards:</h3><div id=infoWindow_awards><span>" + my_icons + "</span></div>";

                   if (my_icons != 0) {
                       cont_awd = "<h3>Awards:</h3><div id=infoWindow_awards><span>" + my_icons + "</span></div>";
                   }
                   else {
                       cont_awd = "";
                   }

                   // Redo for Ratings
                   var rat_icons = new Array();
                   my_icons = attraction[8];
                   my_icons = my_icons.replace(/\|\|/g, '|');
                   my_icons = my_icons.replace(/\"/g, '');
                   my_icons = my_icons.replace(/\'/g, '');
                   my_icons = my_icons.replace(/\n/g, '<br />');
                   rat_icons = my_icons.split('|');
                   my_icons = "";
                   for (faci = 0; faci < (rat_icons.length - 1); faci++) {
                       this_split = rat_icons[faci].split("~");
                       if (this_split[0] != "" && this_split[1] != "undefined") {
                           my_icons += '<img style=\\\'border-width: 0px;\\\' src=\\\'/images/ENet/support_icons/' + this_split[1] + '\\\' alt=\\\'' + this_split[0] + '\\\' title=\\\'' + this_split[0] + '\\\' />';
                       }
                   }
                   cont_rat = "<h3>Ratings:</h3><div id=infoWindow_awards><span>" + my_icons + "</span></div>";

                   if (my_icons != 0) {
                       cont_rat = "<h3>Ratings:</h3><div id=infoWindow_awards><span>" + my_icons + "</span></div>";
                   }
                   else {
                       cont_rat = "";
                   }
                   //                   cont_awd = "";

                   cont_contact = cont_contact.replace(/\"/g, '');
                   cont_contact = cont_contact.replace(/\'/g, '');
                   cont_contact = cont_contact.replace(/\r/g, '');
                   cont_contact = cont_contact.replace(/\t/g, ' ');
                   cont_contact = cont_contact.replace(/\n/g, '<br />');

                   var test = '<div id=infoWindowHeader >hello</div>';
                   var infoHeader = "<div id='infoWindowHeader'><a id='link_desc' class='tab' onclick=\"changeContent('" + cont_desc + "','desc_img')\"><img id=\"desc_img\" src=\"images/googleMapsIcons/Description_sel.png\" /></a><a class=\"tab\" id=\"link_fac\" onclick=\"changeContent('" + cont_fac + cont_rat + cont_awd + "','fac_img')\"><img id=\"fac_img\" src=\"images/googleMapsIcons/Facilities.png\" /></a><a class=\"tab\" id=\"link_cont\" onclick=\"changeContent('" + cont_contact + "','cont_img')\"><img id=\"cont_img\" src=\"images/googleMapsIcons/Contact.png\" /></a><a class=\"tab\" ><img id=\"closeBtn\" src=\"images/googleMapsIcons/close.png\" onclick=\"javascript:map.closeInfoWindow();return false;\" /></a></div>";

                   //                   cont_awd = "";

                   var infoWindowContent = infoHeader + "<div id='contentDiv' >" + cont_desc + "</div>";

                   GEvent.addListener(marker, "click", function() {
                       map.setCenter(marker.getPoint());
                       map.setZoom(15);

                       _lastPosBeforeInfoWindow = map.getCenter();

                       marker.openInfoWindowHtml(infoWindowContent);
                       //hide top of infowindow using jQuery
                       /*$("#map_canvas>div>div>div:eq(9)>div>div:eq(0)").css("display", "none");
                       $("#map_canvas>div>div>div:eq(9)>div>div:eq(1)").css("display", "none");
                       $("#map_canvas>div>div>div:eq(9)>div>div:eq(5)").css("display", "none");*/

                       //IE6 css fix                  
                       //$("#contentDiv").css("padding", "0");
                       //$("#contentDiv").css("margin", "0");
                       //$("#infoWindowHeader").css("padding", "0");
                       //$("#infoWindowHeader").css("margin", "0");



                       $("#map_canvas>div>div>div:eq(9)>div>div:eq(6)").css("width", "270px");
                       //$("#infoWindowHeader").css("overflow", "scroll");
                       //$("#infoWindowHeader<div").css("padding", "none");
                       //$("#infoWindowHeader<div").css("margin", "0px");
                       $("#closeBtn").click(function() {
                           marker.closeInfoWindow();
                       });
                       $("#link_desc").mouseover(function() {
                           this.style.cursor = 'pointer';
                       });
                       $("#link_desc").mouseout(function() {
                           this.style.cursor = 'default';
                       });
                       $("#link_cont").mouseover(function() {
                           this.style.cursor = 'pointer';
                       });
                       $("#link_cont").mouseout(function() {
                           this.style.cursor = 'default';
                       });
                       $("#link_fac").mouseover(function() {
                           this.style.cursor = 'pointer';
                       });
                       $("#link_fac").mouseout(function() {
                           this.style.cursor = 'default';
                       });
                       $("#closeBtn").mouseover(function() {
                           this.style.cursor = 'pointer';
                       });
                       $("#closeBtn").mouseout(function() {
                           this.style.cursor = 'default';
                       });
                       GEvent.addListener($('#closeBtn'), "click", function() {
                           marker.closeInfoWindow();
                       });

                   });
                   GEvent.addListener(marker, "visibilitychanged", function() {
                       marker.closeInfoWindow();
                   });
                   GEvent.addListener(marker, "infowindowbeforeclose", function() {
                       map.panTo(_lastPosBeforeInfoWindow);
                   });
                   //alert("HERE2");
                   //alert("about to plot");
                   map.addOverlay(marker);
                   //};
               });
           })();      
       

   }


function createTabbedMarker(attraction) {

    //create start GIcon
    var attractionIcon = new GIcon();
    if (attraction[1] != "" && attraction[1] != null) {
        attractionIcon.image = "images/Icons/" + attraction[1];
        attractionIcon.iconAnchor = new GPoint(15, 15);
        attractionIcon.infoWindowAnchor = new GPoint(5, 1);

        var marker = new GMarker(new GLatLng(attraction[13][0], attraction[13][1]), { icon: attractionIcon, title: attraction[0] });
    }
    else {
        var marker = new GMarker(new GLatLng(attraction[13][0], attraction[13][1]), { title: attraction[0] } );
        _plainMarkerArr.push(marker);
    }

    var title = attraction[0];

    //description
    var description = jQuery.trim(attraction[4]);
    description = description.replace(/\"/g, '');
    description = description.replace(/\'/g, '');
    description = description.replace(/\r/g, '');
    description = description.replace(/\t/g, ' ');
    description = description.replace(/\n/g, '<br />');
    //var roomTypes = poi[trail][pointOfInterest][4][1]; //"<table><tr><td>Room Type</td><td>Min</td><td>Max</td></tr><tr><td>The Stabels Cottage</td><td>£400</td><td>£710</td></tr></table>";
    //Facilities
    var facilities_icons = attraction[7];
    var awards_icons = attraction[9];
    var ratings_icons = attraction[8];
    //contact
    var proprietor = attraction[10];
    var address = attraction[11];
    var tel = attraction[5];
    var fax = attraction[6];
    var website = jQuery.trim(attraction[12]);
    var webstr = ((website == "") || (website == null)) ? "No Website" : "<a href=" + website + "> " + website + "</a>";
    var titleLink = (attraction[14] != null) ? "<a href=" + attraction[14] + ">" + title + "</a>" : title;

    var cont_desc = "<h2>" + titleLink + "</h2><h3>Description:</h3>" + description + "";
    var cont_fac = "<h2>" + titleLink + "</h2><h3>Facilities:</h3><div id=infoWindow_fac>" + facilities_icons + "</div>";
    var cont_awd = "<h3>Awards</h3><div id=infoWindow_awards>" + awards_icons + "</div>";
    var cont_rat = "<h3>Ratings</h3><div id=infoWindow_awards>" + ratings_icons + "</div>";
    var cont_contact = "<h2>" + titleLink + "</h2><h3>Proprietor / Manager:</h3><p>" + proprietor + "</p><br /><h3>Address</h3><p>" + address + "</p><br /><h3>Contact</h3><p><b>Tel:</b> " + tel + "<br /><b>Fax:</b> " + fax + "<br /><b>Website:</b> " + webstr + "</p>";

       cont_fac = cont_fac.replace(/\"/g,'');
       cont_fac = cont_fac.replace(/\'/g,'');
       cont_awd = cont_awd.replace(/\"/g,'');
       cont_awd = cont_awd.replace(/\'/g,'');
       cont_contact = cont_contact.replace(/\"/g,'');
       cont_contact = cont_contact.replace(/\'/g,'');
       var fac_icons = new Array();
       var this_split = new Array();
       var my_icons = attraction[7];
       my_icons = my_icons.replace(/\|\|/g,'|');
       fac_icons = my_icons.split('|');
       my_icons = "";
       for (faci = 0; faci < fac_icons.length; faci++)
       {
            this_split = fac_icons[faci].split("~");
            if (this_split[0] != "") {
                my_icons += '<img style=\\\'border-width: 0px;\\\' src=\\\'/images/ENet/facilities_icons/' + this_split[0] + '.gif\\\' alt=\\\''+ this_split[1] + '\\\' title=\\\''+ this_split[1] +'\\\' />';
            }
       }
       cont_fac = "<h2>" + titleLink + "</h2><h3>Facilities:</h3><div id=infoWindow_fac><span>" + my_icons + "</span></div>";

       // Redo for Awards
       var awd_icons = new Array();
       my_icons = attraction[9];
       my_icons = my_icons.replace(/\|\|/g, '|');
       my_icons = my_icons.replace(/\"/g, '');
       my_icons = my_icons.replace(/\'/g, '');
       awd_icons = my_icons.split('|');
       my_icons = "";
       for (faci = 0; faci < (awd_icons.length-1); faci++) {
           this_split = awd_icons[faci].split("~");
           if (this_split[1] != "" && this_split[1] != "undefined") {
               my_icons += '<img style=\\\'border-width: 0px;\\\' src=\\\'/images/ENet/support_icons/' + this_split[0] + '.gif\\\' alt=\\\'' + this_split[1] + '\\\' title=\\\'' + this_split[1] + '\\\' />';
           }
       }
       if (my_icons != "")
       {
            cont_awd = "<h3>Awards:</h3><div id=infoWindow_awards><span>" + my_icons + "</span></div>";
       }
       else
       {
            cont_awd = "";
       }


       // Redo for Ratings
       var rat_icons = new Array();
       my_icons = attraction[8];
       my_icons = my_icons.replace(/\|\|/g, '|');
       my_icons = my_icons.replace(/\"/g, '');
       my_icons = my_icons.replace(/\'/g, '');
       rat_icons = my_icons.split('|');
       my_icons = "";
       for (faci = 0; faci < (rat_icons.length-1); faci++) {
           this_split = rat_icons[faci].split("~");
           if (this_split[0] != "" && this_split[0] != "undefined") {
               my_icons += '<img style=\\\'border-width: 0px;\\\' src=\\\'/images/ENet/support_icons/' + this_split[1] + '\\\' alt=\\\'' + this_split[0] + '\\\' title=\\\'' + this_split[0] + '\\\' />';
           }
       }
       if (my_icons != "")
       {
            cont_rat = "<h3>Ratings:</h3><div id=infoWindow_awards><span>" + my_icons + "</span></div>";
       }
       else
       {
            cont_rat = "";
       }


    var test = '<div id=infoWindowHeader >hello</div>';
    var infoHeader = "<div id='infoWindowHeader'><a id='link_desc' class='tab' onclick=\"changeContent('" + cont_desc + "','desc_img')\"><img id=\"desc_img\" src=\"images/googleMapsIcons/Description_sel.png\" /></a><a class=\"tab\" id=\"link_fac\" onclick=\"changeContent('" + cont_fac + cont_rat + cont_awd + "','fac_img')\"><img id=\"fac_img\" src=\"images/googleMapsIcons/Facilities.png\" /></a><a class=\"tab\" id=\"link_cont\" onclick=\"changeContent('" + cont_contact + "','cont_img')\"><img id=\"cont_img\" src=\"images/googleMapsIcons/Contact.png\" /></a><a class=\"tab\"><img id=\"closeBtn\" src=\"images/googleMapsIcons/close.png\" /></a></div>";

    cont_awd = cont_awd.replace(/\\/g, '');

    var infoWindowContent = infoHeader + "<div id='contentDiv' >" + cont_desc + "</div>";

    GEvent.addListener(marker, "click", function() {
        _lastPosBeforeInfoWindow = map.getCenter();



        marker.openInfoWindowHtml(infoWindowContent);
        //hide top of infowindow using jQuery
        $("#map_canvas>div>div>div:eq(9)>div>div:eq(0)").css("display", "none");
        $("#map_canvas>div>div>div:eq(9)>div>div:eq(1)").css("display", "none");
        $("#map_canvas>div>div>div:eq(9)>div>div:eq(5)").css("display", "none");

        $("#closeBtn").click(function() {
            marker.closeInfoWindow();
        });
        $("#link_desc").mouseover(function() {
            this.style.cursor = 'pointer';
        });
        $("#link_desc").mouseout(function() {
            this.style.cursor = 'default';
        });
        $("#link_cont").mouseover(function() {
            this.style.cursor = 'pointer';
        });
        $("#link_cont").mouseout(function() {
            this.style.cursor = 'default';
        });
        $("#link_fac").mouseover(function() {
            this.style.cursor = 'pointer';
        });
        $("#link_fac").mouseout(function() {
            this.style.cursor = 'default';
        });
        $("#closeBtn").mouseover(function() {
            this.style.cursor = 'pointer';
        });
        $("#closeBtn").mouseout(function() {
            this.style.cursor = 'default';
        });
    });
    GEvent.addListener(marker, "visibilitychanged", function() {
        marker.closeInfoWindow();
    });
    GEvent.addListener(marker, "infowindowbeforeclose", function() {
        map.panTo(_lastPosBeforeInfoWindow);
    });

    return marker;
}

/*  end of 14 attractions   */

/////////////////////////////////////////////////////////////////////////////////
//VARS
/////////////////////////////////////////////////////////////////////////////////
var map;
var _trails = new Array();
var _trailMarkers = new Array(); //contains array of managers for each trail
var _icons = new Array();
var _overlayArr = new Array();
var _startZoom = 8;

/////////////////////////////////////////////////////////////////////////////////
//CONSTANTS
/////////////////////////////////////////////////////////////////////////////////
var iconsPath = "/images/googleMapsIcons/";
var iconsImgArr = new Array("icon1.jpg", "icon2.jpg", "icon3.jpg", "icon4.jpg");
var iconWidth = 51;
var iconHeight = 51;

var startZoom = 9;
var poiTypeNum = 4;
/////////////////////////////////////////////////////////////////////////////////
//INIT
/////////////////////////////////////////////////////////////////////////////////
function clearMap() {
    if (map != null) {
        map.clearOverlays();
        map.setCenter(new GLatLng(54.57567251470241, -2.3212280273437447), 13);
        map.setZoom(8);
        PlotAttractions();
    }
}


function addTrails() {
    var trailSelectHtml = "<option value='0'>All Trails</option>";
    for (var i = 0; i < trails.length; i++) {
        var trail = new Array();
        for (var j = 0; j < trails[i].length; j++) {
            var pos = new GLatLng(trails[i][j][0], trails[i][j][1]);
            trail.push(pos);
        }
        var color = trailOptions[i][0];
        var alpha = trailOptions[i][1];
        var weight = trailOptions[i][2];
        var trailPoly = new GPolyline(trail, color, weight, alpha);
        _trails.push(trailPoly);
        map.addOverlay(trailPoly);
        trailPoly.hide();

        //add to select
        var j = i + 1;
        trailSelectHtml += "<option value='" + j + "'>" + trailNames[i] + "</option>";
    }
    document.getElementById("trailSelect").innerHTML = trailSelectHtml
}

function addIcons() {
    for (var i = 0; i < poiTypeNum; i++) {
        var icon;
        if (iconsImgArr[i] != "") {
            icon = new GIcon();
            icon.image = iconsPath + iconsImgArr[i];
            icon.iconAnchor = new GPoint(15, 15);
            icon.infoWindowAnchor = new GPoint(5, 1);

        } else {
            icon = new GIcon();
        }
        _icons.push(icon)
    }
}

function addManagers() {
    for (var i = 0; i < trails.length; i++) {
        var manager = new Array(); //contains arrays of markers of different types

        for (var j = 0; j < poiTypeNum; j++) {
            var markerType = new Array(); //contains marker objects of same type

            for (var k = 0; k < poi[i].length; k++) {
                if (poi[i][k][2] == j) {
                    var latLng = new GLatLng(poi[i][k][0], poi[i][k][1]);
                    var icon = _icons[poi[i][k][2]];

                    var htmls = new Array();
                    var labels = new Array();
                    var numTabs = poi[i][k][4];
                    var startPos = 5

                    for (var l = startPos; l < numTabs + startPos; l++) {
                        var html = poi[i][k][l][1];
                        var label = poi[i][k][l][0];
                        htmls.push(html);
                        labels.push(label);
                    }

                    //var marker = new GMarker(latLng, { icon: icon, title: poi[i][k][3] });

                    var marker = createTabbedMarker(latLng, { icon: icon, title: poi[i][k][3] }, i, k);

                    markerType.push(marker);
                }
            }
            manager.push(markerType);
        }

        _trailMarkers.push(manager);
    }

    addAllPOIs();
}

var attractions = new Array();

function GetAttractions() {

    $.ajax({
        type: "GET",
        url: "js/ajaxhandler.aspx",
        data: "Method=GetAttractions&Date=" + new Date().getTime(),
        dataType: "xml",
        success: function(xml) {
            $(xml).find('Attraction').each(function() {
                attractions.push(new Array($(this).find("Name").text(),
                                        $(this).find("ImageName").text(),
                                        $(this).find("Lat").text(),
                                        $(this).find("Lon").text(),
                                        $(this).find("Description").text(),
                                        $(this).find("ContactTel").text(),
                                        $(this).find("ContactFax").text(),
                                        $(this).find("Facilities").text(),
                                        $(this).find("Ratings").text(),
                                        $(this).find("Awards").text(),
                                        $(this).find("Owner").text(),
                                        $(this).find("Address").text(),
                                        $(this).find("Website").text(),
                                        new Array($(this).find("Lat").text(), $(this).find("Lon").text()),
                                        $(this).find("linkNumber").text() ));

            }); //close each(
            PlotAttractions();
        }
    });
}

function initialize() {
    //set up index of functio for IE
    if (!Array.indexOf) {
        Array.prototype.indexOf = function(obj) {
            for (var i = 0; i < this.length; i++) {
                if (this[i] == obj) {
                    return i;
                }
            }
            return -1;
        }
    }

    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.setMapType(G_PHYSICAL_MAP);
        //map.setMapType(G_SATELLITE_3D_MAP);
        map.setCenter(new GLatLng(54.57567251470241, -2.3212280273437447), 13);
        map.setZoom(8);
        map.addControl(new GLargeMapControl());

        GEvent.addListener(map, "moveend", function() {
            ResetCheckboxes(".show_accommodationType_panel_map");
        });

        GEvent.addListener(map, "zoomend", function(oldzoom, zoom) {
            if(parseInt(zoom)>=10)
                $(".show_accommodationType_panel_error").slideUp("normal");
            else
                $(".show_accommodationType_panel_map").slideUp("normal");
        });
    }
    GetAttractions();
    if(querySt('ObjectID')!="") GetAccommodationFromObjectID(querySt('ObjectID'));
}
    var _lastPosBeforeInfoWindow;

function resetTabs() {
    document.getElementById('desc_img').src = 'images/googleMapsIcons/Description.png'
    document.getElementById('fac_img').src = 'images/googleMapsIcons/Facilities.png'
    document.getElementById('cont_img').src = 'images/googleMapsIcons/Contact.png'
}

function changeContent(content, targ) {
    document.getElementById('contentDiv').innerHTML = content;
    resetTabs();
    switch (targ) {
        case 'desc_img':
            document.getElementById(targ).src = 'images/googleMapsIcons/Description_sel.png'
            break;
        case 'fac_img':
            document.getElementById(targ).src = 'images/googleMapsIcons/Facilities_sel.png'
            break;
        case 'cont_img':
            document.getElementById(targ).src = 'images/googleMapsIcons/Contact_sel.png'
            break;
    }
}

function closeInfoWindow(marker) {

}



/////////////////////////////////////////////////////////////////////////////////
//POI FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////
function addAllPOIs() {
    //used to add to map (only called once during addManagers)
    for (var i = 0; i < _trailMarkers.length; i++) {
        for (var j = 0; j < _trailMarkers[i].length; j++) {
            for (var k = 0; k < _trailMarkers[i][j].length; k++) {
                map.addOverlay(_trailMarkers[i][j][k]);
                _trailMarkers[i][j][k].hide();
            }
        }
    }
}
function showAllPOIs() {
    //shows all pois for all trails
    for (var i = 0; i < _trailMarkers.length; i++) {
        for (var j = 0; j < _trailMarkers[i].length; j++) {
            for (var k = 0; k < _trailMarkers[i][j].length; k++) {
                _trailMarkers[i][j][k].show();
            }
        }
    }
    showAllTrails(); //displays all polylines

}

function hideAllPOIs() {
    //hides all pois for all trails
    for (var i = 0; i < _trailMarkers.length; i++) {
        for (var j = 0; j < _trailMarkers[i].length; j++) {
            for (var k = 0; k < _trailMarkers[i][j].length; k++) {
                _trailMarkers[i][j][k].hide();
            }
        }
    }
    //hideAllTrails(); //hides all polylines
}

function filterTrail(trailNum, types) {
    //displays filtered types of pois(types:Array of types) for certain trail(trailNum)
    for (var i = 0; i < _trailMarkers[trailNum].length; i++) {
        if (types.indexOf(i) >= 0) {
            for (var j = 0; j < _trailMarkers[trailNum][i].length; j++) {
                _trailMarkers[trailNum][i][j].show();
            }
        } else {
            for (var k = 0; k < _trailMarkers[trailNum][i].length; k++) {
                _trailMarkers[trailNum][i][k].hide();
            }
        }
    }

    showTrail(trailNum);
}

function showTrailPois(trailNum) {
    //shows all POIs on certail trail (trailNum);
    var allTypes = new Array();
    for (var i = 0; i < poiTypeNum; i++) {
        allTypes.push(i);
    }
    filterTrail(trailNum, allTypes);
}

function hideTrailPois(trailNum) {
    var allTypes = new Array();
    filterTrail(trailNum, allTypes);
}


/////////////////////////////////////////////////////////////////////////////////
//TRAILS FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////
function showAllTrails() {
    for (var i = 0; i < _trails.length; i++) {
        _trails[i].show();
    }
    setZoom();
}

function hideAllTrails() {
    hideAllPOIs();
    for (var i = 0; i < _trails.length; i++) {
        _trails[i].hide();
    }
}

function showTrail(trailNum) {
    _trails[trailNum].show();
    setZoom();
}

function hideTrail(trailNum) {
    hideTrailPois(trailNum);
    _trails[trailNum].hide();
}
/////////////////////////////////////////////////////////////////////////////////
//ZOOM / POSITION FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////
function setZoom() {
    var visiblePoints = new Array();
    //loop through all trails and find those visible, adding points to array
    for (var i = 0; i < _trails.length; i++) {
        if (_trails[i].isHidden() == false) {
            for (var j = 0; j < _trails[i].getVertexCount(); j++) {
                visiblePoints.push(_trails[i].getVertex(j));
            }
        }
    }
    //create one line from all visible points
    var tmpLine = new GPolyline(visiblePoints);
    //get bounds
    var visibleBounds = tmpLine.getBounds();
    //calculate and compare zoomz
    var newZoom = map.getBoundsZoomLevel(visibleBounds);

    var currentZoom = map.getZoom();
    if (newZoom < currentZoom) {
        map.setZoom(newZoom);
    }
    //set center of map to accomodate all trails
    var newCenter = visibleBounds.getCenter();
    if (map.getCenter() != newCenter) {
        map.panTo(newCenter);
    }
}

function zoomToStart() {
    map.setZoom(startZoom);
}
/////////////////////////////////////////////////////////////////////////////////
//GUI FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////

function checkSelected() {
    if (document.getElementById("ctl00_content_page_id").value == 0) {
        alert('You must select an exisitng page to edit.');
        return false;
    }
    else {
        return true;
    }
}



var current_templates = 1;
$(document).ready(function() {

    $("#page_editor_tree li a").click(function(e) {

        $("#page_editor_tree li a").removeClass("tree_selected");

        var page_id = $(this).attr('rel');

        $(this).addClass("tree_selected");

        $("#ctl00_content_page_id").val(page_id);

    });

    $("#add_page").click(function(e) {

        if ($("#ctl00_content_page_id").val() == "0") {
            alert("You must select a page from the list below before adding a page.");
        }
        else {
            $("#slide_out_panel_large").slideDown("normal");
        }

    });



    $("#close_page").click(function(e) {
        $("#slide_out_panel_large").slideUp("normal");
    });

    $(".template_image").click(function(e) {
        $(".template_image").css("border-color", "#bbb");
        $("#ctl00_content_template").val($(this).attr("rel"));
        $(this).css("border-color", "#777");
    });



    $("#next").click(function(e) {
        if (_scrollerDisplay == "trails") {
            var new_template = 1;

            for (var i = 0; i < _trailsGroupCount; i++) {
                var k = i + 1;
                var l = 0;
                if (current_templates == k) {
                    if (k == _trailsGroupCount) {
                        l = 1;
                    } else {
                        l = k + 1;
                    }
                    $('.template_selection_container').scrollTo($('#template_section_' + l + ''), 600, { axis: 'x' });
                    new_template = l;
                }
            }
            current_templates = new_template;
        } else if (_scrollerDisplay == "poi") {
            var new_template = 1;

            for (var i = 0; i < _POIGroupCount; i++) {
                var k = i + 1;
                var l = 0;
                if (current_templates == k) {
                    if (k == _POIGroupCount) {
                        l = 1;
                    } else {
                        l = k + 1;
                    }
                    $('.template_selection_container').scrollTo($('#template_section_' + l + ''), 600, { axis: 'x' });
                    new_template = l;
                }
            }
            current_templates = new_template;
        }
    });



    $("#prev").click(function(e) {
        if (_scrollerDisplay == "trails") {
            var new_template = 1;

            for (var i = 0; i < _trailsGroupCount; i++) {
                var k = i + 1;
                var l = 0;
                if (current_templates == k) {
                    if (k == 1) {
                        l = _trailsGroupCount;
                    } else {
                        l = k - 1;
                    }
                    $('.template_selection_container').scrollTo($('#template_section_' + l + ''), 600, { axis: 'x' });
                    new_template = l;
                }
            }
            current_templates = new_template;
        } else if (_scrollerDisplay = "poi") {
            var new_template = 1;

            for (var i = 0; i < _POIGroupCount; i++) {
                var k = i + 1;
                var l = 0;
                if (current_templates == k) {
                    if (k == 1) {
                        l = _POIGroupCount;
                    } else {
                        l = k - 1;
                    }
                    $('.template_selection_container').scrollTo($('#template_section_' + l + ''), 600, { axis: 'x' });
                    new_template = l;
                }
            }
            current_templates = new_template;
        }

    });


});

function hideShowTrail(trailNum) {
    if (_trailsVis[trailNum]) {
        hideTrail(trailNum);
        _trailsVis[trailNum] = false;
    } else {
        showTrail(trailNum);
        _trailsVis[trailNum] = true;
    }
}


var allTrailsFilter = new Array();
function hideShowPOI(poiType) {
    //alert("hideShowPOI");
    if (document.getElementById("trailSelect").selectedIndex == 0) {
        //for all trails
        if (allTrailsFilter.indexOf(poiType) == -1) {
            allTrailsFilter.push(poiType);
        } else {
            var poiPos = allTrailsFilter.indexOf(poiType);
            allTrailsFilter.splice(poiPos, 1);
        }
        //alert("hello");
        hideAllPOIs();
        //alert("filter =" + allTrailsFilter);
        for (var i = 0; i < _trails.length; i++) {
            if (_trails[i].isHidden() == false) {
                //alert("filter trail "+i);
                filterTrail(i, allTrailsFilter);
            }
        }
    } else {
        //alert("not specific type");
        allTrailsFilter = new Array();
        //for specific trail...
        //find out which types are currently showing
        var trailNum = document.getElementById("trailSelect").selectedIndex - 1;
        var currentlyShowing = new Array();
        //alert(_trailMarkers[trailNum].length +" mkarkers associated wit this trail");
        for (var i = 0; i < _trailMarkers[trailNum].length; i++) {
            //alert("markers of " + i + " type = " + _trailMarkers[trailNum][i].length);
            if (_trailMarkers[trailNum][i].length > 0 && _trailMarkers[trailNum][i][0].isHidden() == false) {
                currentlyShowing.push(i);
            }

        }
        // alert("hello");
        //alert("here " + currentlyShowing.indexOf(poiType))
        if (currentlyShowing.indexOf(poiType) == -1) {
            currentlyShowing.push(poiType);
        } else {
            var poiPos = currentlyShowing.indexOf(poiType);
            currentlyShowing.splice(poiPos, 1);
        }

        //alert("about to filer trail: "+trailNum+" to show "+currentlyShowing+" types of POI");
        filterTrail(trailNum, currentlyShowing);
    }
}
/////////////////////////////////////////////////////////////////////////////////
var _scrollerDisplay = "trails";
var _trailsPerPage = 3;
var _trailsGroupCount = 1;

var _trailsVis = new Array();
var _poiVis = new Array();

function createPOIVis() {

}

function createTrailsVis() {
    for (var i = 0; i < trails.length; i++) {
        _trailsVis.push(false);
    }
}

function createTrailsGUI() {
    //alert(document.getElementById("template_selection_row_container").css("left"));
    _scrollerDisplay = "trails";
    current_templates = 1;
    _trailsGroupCount = 1
    var trailsNum = 0;

    var containerHtml = "";
    var pageHtml = "";
    for (var i = 0; i < trails.length; i++) {

        //create trail div in scroller
        var html = "";
        if (trailsNum == 0) {
            trailsNum++;
            pageHtml += "<div class=\"template_selection_row\" id=\"template_section_" + _trailsGroupCount + "\">"
        }
        pageHtml += "<div class='trailBlock' onClick='hideShowTrail(" + i + ")'>" + trailNames[i] + "</div>"
        if (i == _trailsPerPage - 1) {
            trailsNum = 0;
            _trailsGroupCount++;
            pageHtml += "</div>";
        } else if (i == trails.length - 1) {
            pageHtml += "</div>";
        }
    }
    document.getElementById("template_selection_row_container").innerHTML = pageHtml;
    $('.template_selection_container').scrollTo($('#template_section_1'), 600, { axis: 'x' });
}



var _poiPerPage = 3;
var _POIGroupCount = 1;
function createPOIGUI() {
    _scrollerDisplay = "poi";
    current_templates = 1;
    // alert("starting creating POI GUI");
    var poisNum = 0;
    _POIGroupCount = 1;
    var containerHtml = "";
    var pageHtml = "";
    for (var i = 0; i < poiTypeNum; i++) {

        //create trail div in scroller
        var html = "";
        if (poisNum == 0) {
            poisNum++;
            pageHtml += "<div class=\"template_selection_row\" id=\"template_section_" + _POIGroupCount + "\">"
        }
        pageHtml += "<div class='poiBlock' onClick='hideShowPOI(" + i + ")'><img src='" + iconsPath + iconsImgArr[i] + "' /></div>"
        if (i == _poiPerPage - 1) {
            poisNum = 0;
            _POIGroupCount++;
            pageHtml += "</div>";
        } else if (i == poi.length - 1) {
            pageHtml += "</div>";
        }
    }
    document.getElementById("template_selection_row_container").innerHTML = pageHtml;
    $('.template_selection_container').scrollTo($('#template_section_1'), 600, { axis: 'x' });
    //alert("finished creating POI GUI");
}

function GetAccommodationFromObjectID(ObjectID) {
    $.ajax({
        url: "js/ajaxhandler.aspx",
        data: "Method=GetAccommodationFromObjectID&ObjectID=" + ObjectID + "&Date=" + new Date().getSeconds(),
        success: function(xml) {
            plotSearchAttractions(xml);
        }
    });
}
function GetTrailInfo(trailID) {
    $('.bottom_map_toolbar #text').html('<span class="loading">Loading...</span>');

    var removeLoading = function() {
        $('.bottom_map_toolbar .loading').remove();
    };
    $.ajax({
        url: "js/ajaxhandler.aspx",
        data: "Method=GetTrailInfo&ID=" + trailID + "&Date=" + new Date().getSeconds(),
        success: function(xml) {
            displayContent(xml);
            removeLoading();
        },
        error: function() {
            removeLoading();
        }
    });
}

function attachShowHide() {
    $("input[type*='checkbox']").change(function() {
        clearMap();
        $("input[type*='checkbox']").each(function() {
            if (this.checked) {
                switch (getSelectedRef()) {
                    case "acc":
                        GetAccommodationFromObjectID($(this).attr("value"));
                        break;
                    case "trails":
                        GetTrailInfo($(this).attr("value"));
                        break;
                }
            }
        });
    });
}

function getSelectedRef() {
    return $('.left_container').find(".selected").attr("id");
}

function querySt(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}

function plotSearchAttractions(xml) {
    $(xml).find("Item").each(function() {
        var latlng = new GLatLng($(this).attr("Lat"), $(this).attr("Lon"));
        //create start GIcon
        var attractionIcon = new GIcon();
        //attractionIcon.image = "images/Icons/" + attractions[i][1];
        attractionIcon.iconSize = new GSize(24, 38);
        attractionIcon.iconAnchor = new GPoint(15, 15);
        attractionIcon.infoWindowAnchor = new GPoint(5, 1);
        //create array
        var attractions = new Array();
        attractions.push($(this).attr("Name"));
        attractions.push("");
        attractions.push($(this).attr("Lat"));
        attractions.push($(this).attr("Lon"));
        attractions.push($(this).attr("Description"));
        attractions.push($(this).attr("ContactTel"));
        attractions.push($(this).attr("ContactFax"));
        attractions.push($(this).attr("Facilities"));
        attractions.push($(this).attr("Ratings"));
        attractions.push($(this).attr("Awards"));
        attractions.push($(this).attr("Owner"));
        attractions.push($(this).attr("Address"));
        attractions.push($(this).attr("Website"));
        attractions.push(new Array($(this).attr("Lat"), $(this).attr("Lon")));
        attractions.push($(this).attr("ObjectID"));
        var marker = createTabbedMarker(attractions);
        map.addOverlay(marker);
    });
}

function findLocation(callbackFunction) {
    var postCode = $("#location_search_input").val();
    localSearch.setSearchCompleteCallback(null,
        function() {
        if (localSearch.results[0]) {
            var bounds = new GLatLngBounds;
            clearMap();
            var resultLat = localSearch.results[0].lat;
            var resultLng = localSearch.results[0].lng;
            var latlng = new GLatLng(resultLat, resultLng);
            bounds.extend(latlng);
            var marker = new GMarker(latlng);
            map.addOverlay(marker);
            map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        } else {
            alert("Location not found!");
        }
    });
    localSearch.execute(postCode + ", UK");
}

function ZoomIntoAttraction(attraction) {
    var bounds = new GLatLngBounds;
    var latlng = new GLatLng(attractions[attraction][13][0], attractions[attraction][13][1]);
    bounds.extend(latlng);
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}
function ResetCheckboxes(div) {
    $(div + " input[type='checkbox']").each(function() {
        this.checked = false;
    });
}
function beginLocationSearch() {
    for (var i = 0; i < _plainMarkerArr.length; i++) {
        _plainMarkerArr[i].hide();
    }
    _plainMarkerArr = new Array();
    var txt = $("#location_search_input").val();
    //query feeds
    var attractionFound = false;
    for (var a = 0; a < attractions.length; a++) {
        if (attractions[a][0].toLowerCase().indexOf(txt.toLowerCase()) > -1) {
            attractionFound = true;
            ZoomIntoAttraction(a);
            break;
        }
    }
    if (!attractionFound) {   // if attraction not found
        findLocation('');   // no feed information matches.
    }
}

$(window).unload(function() {
    GUnload();
});