// JavaScript Document

function GBG() {
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* PRIVATE PROPERTIES
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	var self 								= GBG;					// Holds a pointer to the class.
	var pageType						= $('body').attr('class').split(' ')[0];
	var search_timeout 			= undefined;
	var mgGmv3 							= null;
	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* PUBLIC PROPERTIES
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	
	
	
	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* CONSTRUCTOR (DOM READY)
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	function constructor()
	{

	    $(window).load(documentLoad());


	    /*
	    * jQuery Cycle Lite Plugin
	    * http://malsup.com/jquery/cycle/lite/
	    * Copyright (c) 2008 M. Alsup
	    * Version: 1.0 (06/08/2008)
	    * Dual licensed under the MIT and GPL licenses:
	    * http://www.opensource.org/licenses/mit-license.php
	    * http://www.gnu.org/licenses/gpl.html
	    * Requires: jQuery v1.2.3 or later
	    */
	    (function (d) { var a = "Lite-1.0"; d.fn.cycle = function (e) { return this.each(function () { e = e || {}; if (this.cycleTimeout) { clearTimeout(this.cycleTimeout); } this.cycleTimeout = 0; this.cyclePause = 0; var i = d(this); var j = e.slideExpr ? d(e.slideExpr, this) : i.children(); var g = j.get(); if (g.length < 2) { if (window.console && window.console.log) { window.console.log("terminating; too few slides: " + g.length); } return; } var h = d.extend({}, d.fn.cycle.defaults, e || {}, d.metadata ? i.metadata() : d.meta ? i.data() : {}); h.before = h.before ? [h.before] : []; h.after = h.after ? [h.after] : []; h.after.unshift(function () { h.busy = 0; }); var f = this.className; h.width = parseInt((f.match(/w:(\d+)/) || [])[1]) || h.width; h.height = parseInt((f.match(/h:(\d+)/) || [])[1]) || h.height; h.timeout = parseInt((f.match(/t:(\d+)/) || [])[1]) || h.timeout; if (i.css("position") == "static") { i.css("position", "relative"); } if (h.width) { i.width(h.width); } if (h.height && h.height != "auto") { i.height(h.height); } var k = 0; j.css({ position: "absolute", top: 0, left: 0 }).hide().each(function (m) { d(this).css("z-index", g.length - m); }); d(g[k]).css("opacity", 1).show(); if (d.browser.msie) { g[k].style.removeAttribute("filter"); } if (h.fit && h.width) { j.width(h.width); } if (h.fit && h.height && h.height != "auto") { j.height(h.height); } if (h.pause) { i.hover(function () { this.cyclePause = 1; }, function () { this.cyclePause = 0; }); } d.fn.cycle.transitions.fade(i, j, h); j.each(function () { var m = d(this); this.cycleH = (h.fit && h.height) ? h.height : m.height(); this.cycleW = (h.fit && h.width) ? h.width : m.width(); }); j.not(":eq(" + k + ")").css({ opacity: 0 }); if (h.cssFirst) { d(j[k]).css(h.cssFirst); } if (h.timeout) { if (h.speed.constructor == String) { h.speed = { slow: 600, fast: 200}[h.speed] || 400; } if (!h.sync) { h.speed = h.speed / 2; } while ((h.timeout - h.speed) < 250) { h.timeout += h.speed; } } h.speedIn = h.speed; h.speedOut = h.speed; h.slideCount = g.length; h.currSlide = k; h.nextSlide = 1; var l = j[k]; if (h.before.length) { h.before[0].apply(l, [l, l, h, true]); } if (h.after.length > 1) { h.after[1].apply(l, [l, l, h, true]); } if (h.click && !h.next) { h.next = h.click; } if (h.next) { d(h.next).bind("click", function () { return c(g, h, h.rev ? -1 : 1); }); } if (h.prev) { d(h.prev).bind("click", function () { return c(g, h, h.rev ? 1 : -1); }); } if (h.timeout) { this.cycleTimeout = setTimeout(function () { b(g, h, 0, !h.rev); }, h.timeout + (h.delay || 0)); } }); }; function b(j, e, i, k) { if (e.busy) { return; } var h = j[0].parentNode, m = j[e.currSlide], l = j[e.nextSlide]; if (h.cycleTimeout === 0 && !i) { return; } if (i || !h.cyclePause) { if (e.before.length) { d.each(e.before, function (n, p) { p.apply(l, [m, l, e, k]); }); } var f = function () { if (d.browser.msie) { this.style.removeAttribute("filter"); } d.each(e.after, function (n, p) { p.apply(l, [m, l, e, k]); }); }; if (e.nextSlide != e.currSlide) { e.busy = 1; d.fn.cycle.custom(m, l, e, f); } var g = (e.nextSlide + 1) == j.length; e.nextSlide = g ? 0 : e.nextSlide + 1; e.currSlide = g ? j.length - 1 : e.nextSlide - 1; } if (e.timeout) { h.cycleTimeout = setTimeout(function () { b(j, e, 0, !e.rev); }, e.timeout); } } function c(e, f, i) { var h = e[0].parentNode, g = h.cycleTimeout; if (g) { clearTimeout(g); h.cycleTimeout = 0; } f.nextSlide = f.currSlide + i; if (f.nextSlide < 0) { f.nextSlide = e.length - 1; } else { if (f.nextSlide >= e.length) { f.nextSlide = 0; } } b(e, f, 1, i >= 0); return false; } d.fn.cycle.custom = function (k, h, i, e) { var j = d(k), g = d(h); g.css({ opacity: 0 }); var f = function () { g.animate({ opacity: 1 }, i.speedIn, i.easeIn, e); }; j.animate({ opacity: 0 }, i.speedOut, i.easeOut, function () { j.css({ display: "none" }); if (!i.sync) { f(); } }); if (i.sync) { f(); } }; d.fn.cycle.transitions = { fade: function (f, g, e) { g.not(":eq(0)").css("opacity", 0); e.before.push(function () { d(this).show(); }); } }; d.fn.cycle.ver = function () { return a; }; d.fn.cycle.defaults = { timeout: 4000, speed: 1000, next: null, prev: null, before: null, after: null, height: "auto", sync: 1, fit: 0, pause: 0, delay: 0, slideExpr: null }; })(jQuery);

		
		$('input[type=image].submit').click(
			function (e)
			{
				var s = $('.fld_search');
				if(s.attr('alt') != s.val() && s.val().length > 0)
					return true;
				else
					return false;
			}
		);
		
		$('body').bind('done.customizeForm',function(){
			
			bookingPageSocialToolsInputElementCorrection();
			//mgEditItemAccordion.init();
			$('.numRooms').bind(
				'change', 
				function (e)
				{
					var num = (e.target.value == 1) ? 0 : (e.target.value * 2) - 2;
					
					var parent = $(e.target).parents('fieldset');
					if(e.target.value == 1)
					{
						$('.additionalSelects label', parent).hide().css('visibility', 'visible');
					}
					else
					{
						var num = (e.target.value * 2) - 3;
						$('.additionalSelects label', parent).css('visibility', 'visible');
						$('.additionalSelects label:lt('+num+')', parent).show();
						$('.additionalSelects label:eq('+num+')', parent).show();
						$('.additionalSelects label:gt('+num+')', parent).hide();
					}
				}
			);
			
			$('.numRooms').trigger('change');
			
		});
        
		switch (pageType)
		{
			//// MAP PAGE CONFIG
			case 'mapPage' :			
				
				map();
				
				
			break;
			
			//// SMULTRON PAGE CONFIG
			case 'smultronPage' :			
				
				smap();
				
			break;
			
			//// START PAGE CONFIG

            case 'startPage':

                if (window.startPageFlashLoad) {
					startPageFlashLoad();
				}
				
                if ($.daddy.browser({ browser: 'IE6' })) {

                    $('.calendarItems .item').hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); });

                }

                $('.calendarItems .item .fallback').remove();

                if ($.daddy.browser({ browser: 'IE6' })) {

                    $('.calendarItems .item')
					            .hover(
						            function() {
						                $(this).addClass('hover');
						            },
						            function() {
						                $(this).removeClass('hover');
						            }
					            );

                }

                break;
				
			//// START PAGE REDESIGN (SUMMER 2010) CONFIG
			
			case 'startPageRedesign':
			
				spRedesign();
				
			break;
			
			//// PRODUCT PAGE CONFIG

            case 'productPage':

                toolTabs();
                $('#facilities .tab').bind('click', facilities);

                $('.productListAdv :input').live('change', generateProductListReslt);

                imageGallery();

                $('.rating').each(rating);

                var xmas09_bookingForm = $('#xmas09_bookingForm');

                productPageMap();

                if (xmas09_bookingForm.length > 0) {
                    $('body').append(xmas09_bookingForm);
                    xmas09bf.events_init();
                }

                var nearByModule = $('.rc_box.nearby');
                if (nearByModule.length > 0) {
                    var nearBySelect = nearByModule.find('.header select');
                    var categoryId = nearBySelect.val();
                    GetNearbyItems(categoryId);

                    nearBySelect.change(function() {
                        GetNearbyItems(nearBySelect.val());
                    });

                }


                break;
			
			//// LANDING PAGE CONFIG
			case 'landingPage' :
			break;
			
			//// LANDING PRODUCT CONFIG
			case 'landingProductPage' :
			break;
			
			//// LIST PAGE CONFIG
			case 'listPage' :
			$('.mgMicroGuidesExpand .tabIcon').bind('click', mgMicroGuidesExpandTogglePane)
			break;
			
			//// MICROGUIDES PAGE CONFIG
			case 'microguidesPage' :
				$('.mgMicroGuidesSection .tabIcon').toggle(mgMicroGuidesSectionHide, mgMicroGuidesSectionShow);
			break;
			
			//// MG SAVE PUBLISH
			case 'mgSavePublish' :
				$('.description input:checkbox').
				bind('click', function (e)
				{
					if(e.target.checked)
					{
						//$('.registerPane').css({height: 'auto'});
						//$('.loginPane').css({height: '0px', overflow: 'hidden'});
						$('.loginPane').addClass('hiddenPane');
						$('.registerPane').removeClass('hiddenPane').css({height: '1%', overflow: 'visible'});
					}
					else
					{
						//$('.registerPane').css({height: '0px'});
						//$('.loginPane').css({height: 'auto'});
						$('.registerPane').addClass('hiddenPane');
						$('.loginPane').removeClass('hiddenPane');
					}
				});
				
				$('form').append($('#mgImgTerms'));
				$('form').append($('#mgWhyRegister'));
				
				modal.layer.init();
					
				$('#mgImgTerms .modal_ctrl button').click(function(){
					modal.layer.hide('#mgImgTerms');
					return false;
				});
				
				$('.show_mgImgTerms').click(function(){
					modal.layer.show('#mgImgTerms');
					return false;
				});
				
				$('#mgWhyRegister .modal_ctrl button').click(function(){
					modal.layer.hide('#mgWhyRegister');
					return false;
				});
				
				$('.show_mgWhyRegister').click(function(){
					modal.layer.show('#mgWhyRegister');
					return false;
				});
				
				
				
				instantErrorCheck.init();
											
			break;
			
			//// MG DETAIL PAGE CONFIG

            case 'mgDetailPage':
                toolTabs();
				$('.rating').each(rating);
				
				var mapSettings = 
				{
					mapNode: 'mgMap',
					centerLat: $('.item_lat:first input').val(),
					centerLng: $('.item_lng:first input').val(),
					initZoom: 10,
					
					// MARKER SETTINGS
					markerIconUrl: 		'/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.png',
					markerIconSize: 	{width: 25, height: 35},
					markerIconOrigin: 	{x: 0, y: 0},
					markerIconAnchor: 	{x: 12, y: 25},
					
					markerShadowSize: 	{width: 35, height: 25},
					markerShadowOrigin: {x: 0, y: 0},
					markerShadowAnchor: {x: 0, y: 10},
					markerShadowUrl: 	'/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.shadow.png',
					
					// MAP TYPE
					mapType: google.maps.MapTypeId.ROADMAP
				}
				
				//// GET INSTANCE OF MAP	
				var mgDGmv3 = new GMV3(mapSettings);
				
				var mgDetailMap = {};
				
				mgDetailMap.init = function ()
				{
					var items = $('.mgDetailItems li');
					$.each(items,
					function (index)
					{
						var lat = $('.item_lat input', this).val();
						var lng = $('.item_lng input', this).val();
						
						var m = mgDGmv3.addMarker({lat: lat, lng: lng, draggable: false, visible: true});
						
						
						$(this).bind('removeSelectMark',function(){
							mgDGmv3.setMarkerIcon(m, '/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.png');									 
						});
						
						$(this).hover(
							function ()
							{
								if ($('.mgDetailItems li.mapViewSelected').length == 0) {
									mgDGmv3.setMarkerIcon(m, '/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v2.png');
									var latLng = mgDGmv3.getLatLng(m);
									mgDGmv3.panTo(latLng);
									mgDGmv3.bringToFront(m);
								}
							},
							function ()
							{
								if ($('.mgDetailItems li.mapViewSelected').length == 0) {
									mgDGmv3.setMarkerIcon(m, '/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.png');
								}
							}
						).click(function(){
							$('.mgDetailItems li.mapViewSelected')
								.trigger('removeSelectMark')
								.removeClass('mapViewSelected');
								
							$(this).addClass('mapViewSelected');
							
							mgDGmv3.setMarkerIcon(m, '/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v2.png');
							var latLng = mgDGmv3.getLatLng(m);
							mgDGmv3.panTo(latLng);
							mgDGmv3.bringToFront(m);
						});
						
						/* $(this).find('a').click(function(){
							$(this).parent().click();						 
							return false;
						}); */
					});
					
					mgDGmv3.makeMarkerFit();
					
				}
				
				mapLoaded = function ()
				{
					mgDetailMap.init();	
				}
				
				mg_stalkerMap.init();
				
			break;
			
			
			////
			case 'searchResult' :
				$('.searchResultSection .tabIcon').click(function(){
				   var currentBox = $(this).parent().parent();
				   if ($('.sRS_item',currentBox).length > 0) {
					   $(currentBox).toggleClass('sRS_closed');
				   }
				});
			break;
			
			//// MG INFO PAGE CONFIG
			case 'mgInfoPage' :
			break;
			
			//// MG PAGE CONFIG
			case 'mgPage' :
				//$("#create_new").click(createNewAccount);
				$('.rating').each(rating);
				
				var mapSettings = 
				{
					mapNode: 'mapSmall',
					centerLat: 57.7073868,
					centerLng: 11.9666177,
					initZoom: 10,
					
					// MARKER SETTINGS
					markerIconUrl: 		'/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.png',
					markerIconSize: 	{width: 25, height: 35},
					markerIconOrigin: 	{x: 0, y: 0},
					markerIconAnchor: 	{x: 12, y: 25},
					
					markerShadowSize: 	{width: 35, height: 25},
					markerShadowOrigin: {x: 0, y: 0},
					markerShadowAnchor: {x: 0, y: 10},
					markerShadowUrl: 	'/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.shadow.png',
					
					// MAP TYPE
					mapType: google.maps.MapTypeId.ROADMAP
				}
				
				//// GET INSTANCE OF MAP	
				mgGmv3 = new GMV3(mapSettings);
				
				
				
				//mgEditItemAccordion.init();
			break;
			
			//// MG PAGE CONFIG
			case 'MicroGuide_Edit' :
			
				var mapSettings = 
				{
					mapNode: 'mapSmall',
					centerLat: 57.7073868,
					centerLng: 11.9666177,
					initZoom: 10,
					
					// MARKER SETTINGS
					markerIconUrl: 		'/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.png',
					markerIconSize: 	{width: 25, height: 35},
					markerIconOrigin: 	{x: 0, y: 0},
					markerIconAnchor: 	{x: 12, y: 25},
					
					markerShadowSize: 	{width: 35, height: 25},
					markerShadowOrigin: {x: 0, y: 0},
					markerShadowAnchor: {x: 0, y: 10},
					markerShadowUrl: 	'/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.shadow.png',
					
					// MAP TYPE
					mapType: google.maps.MapTypeId.ROADMAP
				}
				
				//// HIDE TOLLTIP
				if($('.mgItemWrap').size() == 1) {
					if ($('.mgItemWrap').eq(0).find('.namePlaceField_item input').eq(0).val() == '') {
						$('.mgItemWrap:first .mgTooltip').show();
					}
				}
				
				$('.namePlaceField').bind('focus', function () {$(this).parents('.mgItemWrap').children('.mgTooltip').hide();})
				
				//// GET INSTANCE OF MAP	
				mgGmv3 = new GMV3(mapSettings);
				mgMapInit();
				
				$('form').append($('#mgImgTerms'));
				modal.layer.init();
				$('#mgImgTerms .modal_ctrl button').click(function(){
					modal.layer.hide('#mgImgTerms');
					return false;
				});
				
				$('.show_mgImgTerms').click(function(){
					modal.layer.show('#mgImgTerms');
					return false;
				});
			break;
			
			//// SECTION PAGE CONFIG
			case 'sectionPage' :
			break;
			
			//// GUIDE PAGE CONFIG

			case 'guidePage':


		    $('.guidePage .datePicker').each(function(i) {
		
		        var current = this;
		
		        $(this).DatePicker(
								{
								    color: 'yell',
								    date: $(this).val(),
								    current: $(this).val(),
								    onChange: function(formated, dates) {
								        $(current).val(formated);
								        $(current).DatePickerHide();
								        Visit.CorrectDates(current);
		
								    },
								    onRender: Visit.OnRenderDisableDates
		
								}
							);
		
		    });
		
		
		
		    $('.fI_multiChoice :checked').each(function() {
		
		        $(this).parent().addClass('selected');
		
		    });
		
		
		    $('.fI_multiChoice label').click(function() {
		
		        if ($(this).hasClass('selected')) {
		
		            $(this).removeClass('selected');
		
		            $('input', this).attr('checked', false);
		
		        } else {
		
		            $(this).addClass('selected');
		
		            $('input', this).attr('checked', true);
		
		        }
		
		        return false;
		
		    });
		
		
		    /*$('.gRP_item tt, .gRP_itemHeadLink').click(function(){
		
		    var scope = $(this).parents('.gRP_item').eq(0);
							
		
		    if ($('.guideSubItem',scope).length > 0) {
		
		    $(this).parents('.gRP_item').eq(0).toggleClass('gRP_selected');
		
		    }
		
							return false;
		
		    });*/
		
		
		    $('.gCP_tipsCtrl .heading').click(function() {
		
		        $(this).parent().toggleClass('gCP_tips_selected');
		
		        return false;
		
		    });
		
		
		
		    if (!$.daddy.browser({ browser: 'IE6' })) {
		        /*var selection = [];
		        selection.push('#uc_guideConfigPanel');
		        selection.push('#uc_guideResultPanel');
		        selection.push('#uc_pageHeader');
		        selection.push('#uc_languageSelector');
		        selection.push('#uc_login');
				selection.push('.transport_noBorder');
		        $(selection.join(', ')).customizeForm(); */
				
				$('#uc_guideResultPanel .gRP_sort').customizeForm();
		
		    }
		
		    function guideInputDate(e) {
		        if (e.type == 'focus') {
		            $(e.target).parents('.inputDate').addClass('active');
		        }
		        else {
		            $(e.target).parents('.inputDate').removeClass('active');
		        }
		    }
		
		    $('#uc_guideConfigPanel input.datePicker')
				    .focus(guideInputDate)
				    .blur(guideInputDate);
		
		
		    break;
			
			case 'businessGuidePage' :
				
				$('.businessGuidePage .datePicker').each(function(i){
					var current = this;
					$(this).DatePicker(
						{
							color: 'yell',
							date: $(this).val(),
							current: $(this).val(),
							onChange: function(formated, dates) {
								$(current).val(formated);
								$(current).DatePickerHide();
								Visit.CorrectDates(current);

							},
							onRender: Visit.OnRenderDisableDates
					
						}
					);
				});
			
			
				$('.fI_multiChoice :checked').each(function(){
					$(this).parent().addClass('selected');
				});
			
				$('.fI_multiChoice label').click(function(){
					if ($(this).hasClass('selected')) {
						$(this).removeClass('selected');
						$('input',this).attr('checked',false);
					} else {
						$(this).addClass('selected');
						$('input',this).attr('checked',true);
					}
					return false;
				});
				
				/*$('.gRP_item tt, .gRP_itemHeadLink').click(function(){
					$(this).parents('.gRP_item').eq(0).toggleClass('gRP_selected');
					return false;
				});*/
				
				$('.gCP_tipsCtrl .heading').click(function(){
					$(this).parent().toggleClass('gCP_tips_selected');
					return false;
				});
				
				if (!$.daddy.browser({browser: 'IE6'})) {
					/*var selection = [];
		        	selection.push('#uc_guideConfigPanel');
		        	selection.push('#uc_guideResultPanel');
		        	selection.push('#uc_pageHeader');
		        	selection.push('#uc_languageSelector');
		        	selection.push('#uc_login');
					selection.push('.transport_noBorder');
		        	$(selection.join(', ')).customizeForm(); */
					
					$('#uc_guideResultPanel .gRP_sort').customizeForm();
				}
			
			break;

			
			//// BOOKING PROCESS PAGE CONFIG
			case 'bookingProcess' :
				bookingPage.addToolClickEvents();
				if (window.bookingProcess_showInputBlock == true) {
					bookingPage.activatePanes(); // for locking the process;
				}
				
				
				if ($.daddy.browser({browser: 'IE6'})) {
					$('.bSL_box').hover(function(){
						$(this).addClass('hover');			 
					},function(){
						$(this).removeClass('hover');
					});
				}
			break;
			
		}
		
		//// DEFAULT METHODS TRIGGERED ON EACH PAGE LOAD
		
		$('.languageSelector .head a').bind('click', closeLanguageSelector);
		$('.registerUser .head a').bind('click', closeRegisterUser);
		$('a.loginLayer_show').bind('click', openLogin);
		$('a.registerLayer_show').bind('click', openRegisterUser);
		$('.login .head a').bind('click', closeLogin);
		$('.login .newPassword').bind('click', viewPasswordReminder);
		
		if (!$.daddy.browser({browser: 'IE6'}) && (pageType != 'businessGuidePage' && pageType != 'guidePage')) {
			$(document).customizeForm();
		}
		$('input:text[alt]').bind('focus blur', inputDefault);
		
		toolTips.big.addEvents();
		
		travelPlanner.addEvents();
		
		modal.layer.init();
		
		$('.guidePush_form .datePicker').each(function(i){
			var current = this;
			var indexCheck = i;

			$(this).DatePicker(
				{
					color: 'yell',
					date: $(this).val(),
					current: $(this).val(),
					onChange: function(formated, dates) 
					{
						$(current).val(formated);
						$(current).DatePickerHide();
						Visit.CorrectDates(current);

					},
					onRender: Visit.OnRenderDisableDates
				}
			);
		});
		
		
		$('.productListAdv .datePicker').each(function(i){
			var current = this;
			$(this).DatePicker(
				{
					color: 'yell',
					date: $(this).val(),
					current: $(this).val(),
					onChange: function(formated, dates) {
						$(current).val(formated);
						$(current).DatePickerHide();
						Visit.CorrectDates(current);

					},
					onRender: Visit.OnRenderDisableDates
				}
			);
		});


		$('.guide_roomItemGroup .guide_roomSelect').change(function(e) {
			var width = $(this).parent().find(".inputSelect input").eq(0).width();
			var nr = parseInt($(this).val());
			var scope = $(this).parents('.guide_roomItemGroup').eq(0);
			
			$('.guide_roomItem',scope)
				.removeClass('guide_roomItem_selected')
				.slice(0,nr)
					.addClass('guide_roomItem_selected');

			$('.guide_roomItem_selected label .inputSelect input', scope).width(width);
		});
		
		$('.guide_roomItemGroup .guide_childrenSelect').change(function(e){
			var nr = parseInt($(this).val());
			var scope = $(this).parents('.guide_roomItem').eq(0);
			
			var guide_room_childrenAge = $('.guide_room_childrenAge',scope);
			guide_room_childrenAge.removeClass('guide_room_childrenAge_selected');
			
			var guide_room_childrenAge_labels = guide_room_childrenAge.find('label');
			guide_room_childrenAge_labels.removeClass('selected');
			
			if (nr > 0) {
				guide_room_childrenAge.addClass('guide_room_childrenAge_selected');
				guide_room_childrenAge_labels.slice(0,nr)
					.addClass('selected');
			}
		});
		
		$('.guide_roomItemGroup .guide_roomSelect:first').change();
		
		$('.guide_childrenSelect').each(function(){
			var currentVal = parseInt($(this).val());
			var currentScope = $(this).parents('.guide_roomItem').eq(0);
			if (currentVal > 0) {
				$('.guide_room_childrenAge',currentScope)
					.addClass('guide_room_childrenAge_selected');
				$('.guide_room_childrenAge label:lt('+currentVal+')',currentScope)
					.addClass('selected');
			}
		});
		
		if ($('.dummy____').length > 0) {
			instantErrorCheck.init();
			instantErrorCheck.test();
		}
		
		showLanguageSelector();
		
		bindNavigation('.imageLinkPush');
		if (document.all && !window.opera) {
			$('.imageLinkPush span, .imageLinkPush img').click(function(){
				$(this).parents('a').eq(0).trigger('navigate');
				return false;
			})
		}


	}
	
	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* CONSTRUCTOR (DOCUMENT LOAD)
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	function documentLoad ()
	{
		setSearchAreaWidth();
		$(document.body).removeClass('sys_pageLoad');
	}
	
	
	
	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* PRIVATE METHODS
	* * * * * * * 
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	//// GUIDE PAGE TEXT SHORTERNER ////////////////////////////////////////////////////////////////
	
	var guidePageTextShorterner = function() {
			
	}
	
	//// BIND NAVIGATION (for external triggering of links, or span-in-link-fix in IE) ////////////////////////////////////////////////////////////////
	
	var bindNavigation = function(jQSel_a_tag) {
		$(jQSel_a_tag).bind('navigate',function(){
			var href = $(this).attr('href');
			var target = $(this).attr('target');
			var clickEv = $(this).attr('onclick');
								
			if (clickEv != undefined) {
				clickEv();
				return false;
			} else if (target == '_blank') {
				window.open(href);
				return false;
			} else {
				window.location.href = href;
				return false;
			}
		});
	}
	
	//// STALKER MAP (FOLLOWS ITEMS ON MICROGUIDE DETAIL PAGE) ////////////////////////////////////////////////////////////////
	
	var mg_stalkerMap = {};
	
	mg_stalkerMap.init = function() {
		var theCol = $('.columnName4 .padding').eq(0);
		var colPos = theCol.offset();
		colPos = colPos.top;
		
		var mgPos = $('.mgDetailList:last').offset();
		mgPos = mgPos.top;
		
		if (document.all || $.browser.safari) {
			$(window).scroll(function(){
				var sc = scrolledXY();
				if (sc[1] > colPos) {
					theCol.addClass('stalkerMapIE');
					if (mgPos > sc[1]) {
						theCol.css({marginTop: (sc[1] - colPos)+'px'});
					}
				} else {
					theCol
						.removeClass('stalkerMapIE')
						.css({marginTop: '0'});
				}
			});
		} else {
			$(window).scroll(function(){
				var sc = scrolledXY();
				if (sc[1] > colPos) {
					theCol.addClass('stalkerMap');
				} else {
					theCol.removeClass('stalkerMap');
				}
			});
		} 
	}
	
	
	//// INSTANT ERROR CHECK ////////////////////////////////////////////////////////////////
	
	var instantErrorCheck = {};
	
	instantErrorCheck.interval = false;
	
	instantErrorCheck.init = function() {
		instantErrorCheck.interval = setInterval(function(){
			$('span.error').each(function(){
				if ($(this).parents('label').eq(0).find('.InstantErrorCheck').length == 0) {
					$(this).removeClass('error');
				}
			});
			
			$('span.InstantErrorCheck').each(function(){
				$(this).parents('label').eq(0).find('span:has(span input, span textarea)').addClass('error');
			});
		},300);	
		
		//instantErrorCheck.test();
	}
	
	instantErrorCheck.test = function() {
		$('#errorTest0000002').click(function(){
			$('#errorTest0000001').append('ACH! <span style="display: none;" class="InstantErrorCheck">errorTest0000001</span>');
			return false;
		});	
		
		$('#errorTest0000003').click(function(){
			$('#errorTest0000001 .InstantErrorCheck').remove();
			return false;
		});	
	}
	
	
	//// BOOKING PAGE SOCIAL TOOLS INPUT ELEMENT CORRECTION ////////////////////////////////////////////////////////////////
	
	var bookingPageSocialToolsInputElementCorrection = function() {
		$('div.bT_ctrl_email').css({
			display: 'none',
			position: 'static',
			top: 'auto'
		});	
	};
	
	
	//// TRAVELPLANNER BOX ////////////////////////////////////////////////////////////////
	
	var travelPlanner = {};
	
	travelPlanner.addEvents = function() {
		$('.travelPlanner ul li a').not('ul ul a').click(function(){
			var outer = $(this).parent();
			var amount = $(this).find('.amount').text();
			
			amount = amount.replace('(','').replace(')','');
			
			if (!outer.hasClass('selected') && amount != '0') {
				outer.addClass('selected');
			} else {
				outer.removeClass('selected');
			}
			
			return false;
		});
		
		$('.travelPlanner ul ul a').live('click',function(e){
			if (e.target.nodeName  == 'TT') {
				return false;	
			}
		});
	};
	
	
	
	
	
	
	//// FACILITIES ////////////////////////////////////////////////////////////////
	function facilities (e)
	{
		var module = $(e.currentTarget).parents('#facilities');
		var index = $(e.currentTarget).parents('.head').children('.tab').index(e.currentTarget);
		$('.tab.selected', module).removeClass('selected');
		$(e.currentTarget).addClass('selected');
		
		$('ul.selected', module).removeClass('selected');
		$('ul:eq('+index+')', module).addClass('selected');
	}
	
	//// MG MICROGUIDES EXPAND TOGGLE PANE /////////////////////////////////////////
	function mgMicroGuidesExpandTogglePane (e)
	{
		var parentObj = $(e.target).parents('.mgMicroGuidesExpand');
		
		
		if($('.items:visible', parentObj).size() == 1)
			$('.items', parentObj).hide(300);
		else
			$('.items', parentObj).show(300);
	}
	
	//// SHOW PAGE SHADE ///////////////////////////////////////////////////
	function showPageShade()
	{
		$('#pageShade').addClass('showShade');
	}
	
	//// SHOW LANGUAGE SELECTOR ///////////////////////////////////////////////////
	function showLanguageSelector(){
		var langSel = $('.rc_box.languageSelector');
		
		//alert("$('.rc_box.languageSelector').length = "+langSel.length);
		//alert("gup('googleTranslate') == "+gup('googleTranslate'));
		
		if (langSel.length > 0) {
			
			if (gup('googleTranslate') == 'true') {
				langSel.addClass('languageSelectorShow');
				showPageShade();
            } else if (langSel.hasClass('showMe') && navigator.cookieEnabled) {
                langSel.addClass('languageSelectorShow');
				showPageShade();
				$('#pageShade').click(function(){
					$('.rc_box.languageSelector').removeClass('languageSelectorShow');
					$('#pageShade').removeClass('showShade');
				});
			}
		} 
		
		return false;

	}
	
	//// CLOSE LANGUAGE SELECTOR ///////////////////////////////////////////////////
	function closeLanguageSelector (e)
	{
		$(e.target).parents('.languageSelector').remove();
		$('#pageShade').removeClass('showShade');
		return false;
	}
	
	//// CLOSE REGISTER USER ///////////////////////////////////////////////////
	function closeRegisterUser (e)
	{
		$(e.target).parents('.registerUser').css({top: '-999em'});
		$('#pageShade').removeClass('showShade');
		return false;
	}
	
	//// OPEN REGISTER USER ///////////////////////////////////////////////////////////////
	function openRegisterUser (e)
	{
		$('.registerUser')
			.css({top: '300px'});
		$('#pageShade').addClass('showShade');
		return false;
	}
	
	
	//// OPEN LOGIN ///////////////////////////////////////////////////////////////
	function openLogin (e)
	{
		$('.rc_box.login')
			.css({top: '300px'})
			.addClass('loginMode_login');
		$('#pageShade').addClass('showShade');
		return false;
	}
	
	//// CLOSE LOGIN ///////////////////////////////////////////////////////////////
	function closeLogin (e)
	{
		$(e.target).parents('.login').css({top: '-999em'});
		$('.rc_box.login').removeClass('loginMode_login loginMode_sendPassword');
		$('#pageShade').removeClass('showShade');
		return false;
	}
	
	//// VIEW PASSWORD REMINDER ///////////////////////////////////////////////////////////////
	function viewPasswordReminder (e)
	{
		//$('.login .passwordText, .login .login_email').css({display: 'block'});
		//$('.login .login_userName, .login .login_password, .login .newPassword').hide();
		$('.rc_box.login').addClass('loginMode_sendPassword').removeClass('loginMode_login');
		return false;
	}
	

	
	//// GENERATE PRODUCT LIST RESULT //////////////////////////////////////////////
	function generateProductListReslt (e)
	{
		var ser = $('form').find('.productListAdv :input').serialize();
		/*
		$.ajax
		(
			{
			   type: "POST",
			   url: "/Templates/Public/_json/productList.json",
			   data: ser,
			   dataType: "json",
			   success: processResult
			 }
		 );
		*/
		
		function processResult (data)
		{
			//console.log(data);
		}
		
	}
	
	
	
	//// MG LOGIN - CREATE NEW ACCOUNT /////////////////////////////////////////////
	function createNewAccount ()
	{
		
		var ison = $('#create_new:checked').val() == 'on';
		if(ison)
		{
			$(".name").show();
			$(".passwordAgain").show();
			$("#Register").css("visibility","visible");
			$("#loginButton").parent().hide();
		}
		else
		{
			$(".name").hide();
			$(".passwordAgain").hide();
			$("#Register").css("visibility","hidden");
			$("#loginButton").parent().show();
		}
	}
	
	//// MICRO GUIDE SECTION SHOW/HIDE /////////////////////////////////////////////
	function mgMicroGuidesSectionShow (e)
	{
		$(e.target).css({backgroundPosition: '0px 0px'});
		var obj = $(e.target).parents('.mgMicroGuidesSection');
		$('.items', obj).slideDown(300);
	}
	
	function mgMicroGuidesSectionHide (e)
	{
		$(e.target).css({backgroundPosition: '0px -24px'});
		var obj = $(e.target).parents('.mgMicroGuidesSection');
		$('.items', obj).slideUp(300);
	}
	
	//// TOOL TABS /////////////////////////////////////////////////////////////////
	function toolTabs()
	{	
		this.show = function (e)
		{
			/*var parent = $(e.target).parent();
			var index = parent.parent().children().index(parent);
			$('.tabs li').removeClass('selected').eq(index).addClass('selected');
			$('.tabContent li').hide().eq(index).show();
			$('.tabContent li:visible').customizeForm();
			*/
			
			var scope = $(e.target).parents('.tools').eq(0);
			var currentTab = $(e.target).parent();
			var currentTarget = currentTab.attr('class');
			
			if(currentTab.hasClass('selected'))
			{
				currentTab.removeClass('selected');
				$('.tabContent .'+currentTarget.split(' ')[0]+'Content').hide();
				return false;
			}
			else
			{
			
				$('.tabs li',scope).removeClass('selected');
				
				currentTab.addClass('selected');
				
				$('.tabContent li').hide();
				$('.tabContent .'+currentTarget+'Content').show();
				
				$('.tabContent li:visible').customizeForm();
				
				return false;
			}
		}


		$('.shareButton').bind('click', sendTipsData);
		
		$('.tools .tabs li a').not('[href*=window.print]').bind('click', this.show);

		function sendTipsData ()
		{
		    var ser = $('form').find('.shareContent :input').serialize();
		    ser += "&share_url=" + window.location.href;

			$.ajax({
			 type: "POST",
			 url: "/Templates/Public/Handlers/TipsHandler.ashx",
			 dataType: 'json',
			 data: ser,
			 success: function(data)
			 {
					if(!data.name)
						$('.share_name').parents('.inputText').addClass('error');
					else
						$('.share_name').parents('.inputText').removeClass('error');
						
					if(!data.email)
						$('.share_email').parents('.inputText').addClass('error');
					else
						$('.share_email').parents('.inputText').removeClass('error');
						
					if(data.valid)
					{
						var h = $('.shareContent').height();
						$('.shareContent div:first').fadeOut(300, function () {$('.share_message').height(h).fadeIn(300, function () {var interval = window.setTimeout(function () { window.clearTimeout(interval); $('.share_message').fadeOut(300, function () {$('.shareContent div:first').fadeIn(300);});}, 2000);});});
					}
					
			 }
		    });
			
			return false;
			
		}
		
	}
	
	//// RATING /////////////////////////////////////////////////////////////////////
	function rating (e) {
		var input = $('input:radio', this);
		var rating = $(this);
		var current = ($('.current', rating).size() == 1) ? $('.current', rating).val() : null;
		
		function over (e)
		{
			var index = (e.target.value);
			$('.star:lt('+index+')', rating).addClass('active').removeClass('set');
			$('.star:gt('+(index-1)+')', rating).removeClass('active set');
		}
		
		function set (e)
		{
			var index 		= (e.target.value);
			var parent 		= $(e.target).parents('.rating');
			var productType = $('input.productType', parent).val();
			var productId 	= $('input.productId', parent).val();
			
			e.target.checked = true;
			$('.active', rating).addClass('set').removeClass('active');
			input.unbind('mouseover click').attr('disabled', true);
			rating.unbind('mouseout');
			
			$.ajax(
			{
			   type: "POST",
			   url: '/templates/public/handlers/SetRating.ashx',
			   data: 'productType='+productType+'&rating='+index+'&productId='+productId,
			   dataType: 'json',
			   success: function(msg)
			   {
				   $('.votes', parent).html('('+msg.count+')');
				 
			   },
			   error: function ()
			   {
				  // ERROR HANDLER
			   }
			 });
		}
		
		
		function out (e)
		{
			(current == null) ? $('.star', rating).removeClass('active') : setCurrent();
		}
		
		function setCurrent ()
		{
			$('.star:lt('+current+')', rating).addClass('set');
			$('.star:gt('+(current-1)+')', rating).removeClass('set active');
		}
		
		this.prepare = function (e)
		{
			var obj = $(this);
			obj.siblings('.value').hide();
			obj.css({opacity: 0}).wrap('<span class="star"></span>');
			obj.bind('mouseover', over);
			obj.bind('click', set);
			rating.bind('mouseout', out);
			$('input:button, button', rating).hide();
		}
		
		$.each(input, this.prepare);
		
		
		
		if ($.browser.msie && parseInt($.browser.version) < 8) { // fix for jumping content in IE
			var gradeArea = $(rating).parents('.gradeArea').eq(0);
			//alert('hide');
			gradeArea.hide();
			setTimeout(function(){
				//alert('show');
				gradeArea.show();
			},100);
		}
		
		setCurrent();
		 
	}
	
	//// SET SEARCH AREA WIDTH /////////////////////////////////////////////////////
	function setSearchAreaWidth()
	{
		var topNav = $('#topNav .content');
		
		var param = {};
		param.topNavWidth = topNav.width();
		param.navigationWidth = $('ul:first', topNav).outerWidth();
		param.searchModuleWidth = $('.searchModule', topNav).width();
		
		var width = (param.topNavWidth - param.navigationWidth - 170);
		
		$('.fld_search', topNav).width(width);
		
		
		if($.daddy.browser({browser: 'IE6'}) || $.daddy.browser({browser: 'IE7'}))
		{
			
			$('div.searchModule input')
			.hover(
				function ()
				{
					$(this).addClass('hover');
				},
				function ()
				{
					$(this).removeClass('hover');
				}
			);
			$('div.searchModule input').bind('focus', function () {$(this).addClass('focus');});
			$('div.searchModule input').bind('blur', function () {$(this).removeClass('focus');});
		}
	}
	
	
	
	
	//// INPUT DEFAULT /////////////////////////////////////////////////////////////
	function inputDefault (e)
	{
		var obj = $(this);
		var alt = obj.attr('alt');
		var val = obj.val();
		
		switch (e.type)
		{
			case 'focus' :
				(val == alt) ? obj.val('') : null;
			break;
			
			case 'blur' :
				(val.length == 0) ? obj.val(alt) : null;
			break;
		}
	}
	
	//// TOOLS TAB /////////////////////////////////////////////////////////////
	
	
	//// BOOKING PAGE FUNCTIONS /////////////////////////////////////////////////////////////////////
	
	var bookingPage = {};
	
	bookingPage.addToolClickEvents = function() {
		$('.bT_ctrl_').click(function(){
			var myClass = $(this).attr('class');
			myClass = myClass.split(' ');
			myClass = myClass[1];
			$('.bT_ctrl_field').hide();
			$('div.'+myClass).show();
			return false;
		});
	}
	
	bookingPage.activatePanes = function() {
		var col_left = $('.columnName1').eq(0);
		
		var col_right = $('.columnName2').eq(0);
		var col_right_topEl_offset = col_right.find('.bPR_sum').eq(0).position();
		
		$('#bookingShade01')
			.css({
				 width: col_left.find('.rc_box').eq(0).innerWidth() + 'px',
				 height: col_left.height() + 'px',
				 left: '8px',
				 top: '0px'
			});
												
		$('#bookingShade02')
			.css({
				 width: col_right.find('.rc_box').eq(0).innerWidth() + 'px',
				 height: col_right_topEl_offset.top + 6 + 'px',
				 left: '8px',
				 top: '0px'
			});
			
		$('.infoBadge').show();	
		
		$('.columnName1:eq(0) a, .columnName1:eq(0) input, .columnName1:eq(0) select, .bPR_box a').not('.infoBadge a')
			.click(function(){
				return false;
			}).focus(function(){
				return false;
			});
	}
	
	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* MG MAP
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	function mgMapInit()
	{
		var mgMap = {};
		
		
		mgMap.addCustomMarker = function(e) 
		{
			//// Remove all existing markers.
			mgGmv3.removeAllMarkers();
			
			//// Get the position of the click
			var obj = {};
			
			obj.lat = e.latLng.Tf;
			obj.lng = e.latLng.Wf;
			
			//// Add an new marker
			var m = mgGmv3.addMarker({lat: obj.lat, lng: obj.lng, draggable: true, visible: true, keysArray: {}});
			
			//// Get the geocode info from the marker.
			mgMap.geocode(e.latLng);
			
			//// Pan the map
			mgGmv3.panTo(e.latLng);
			
			//// Bind dragged event to retrive the updated geocode info.
			mgGmv3.addEventHandler(
			m, 
			'dragend', 
			function (e)
			{
				var latLng = mgGmv3.getLatLng(this);
				mgMap.geocode(latLng);
				mgGmv3.panTo(latLng);
			}
			);
		}
		
		mgMap.geocode = function (latLng)
		{
			mgGmv3.geocoder.geocode(
			{'latLng': latLng}, 
			function (res, status) 
			{
				//// Update the field in HTML for address data.
				var current = $('.mgItemWrap.active');
				$('.aCR_hid_lat input', current).val(res[0].geometry.location.Lf);
				$('.aCR_hid_lng input', current).val(res[0].geometry.location.Nf);
				$('.addressField', current).val(res[0].formatted_address);
			});
		}
		
		//// Add an marker based on the selected product.
		mgMap.addMarker = function (obj)
		{
			
		
			
			//// Remove all existing markers.
			mgGmv3.removeAllMarkers();
			
			/// Add the new marker.
			var m = mgGmv3.addMarker({lat: obj.lat, lng: obj.lng, draggable: false, visible: true, keysArray: {}});

		}
		
		//// METHOD TRIGGERD WHEN THE MAP IS READY
		mapLoaded = function ()
		{
			mgGmv3.addEventHandler(mgGmv3.map, 'click', mgMap.addCustomMarker);
			
			var last = $('.mgItemWrap:last');
			var lat = $('.aCR_hid_lat input', last).val();
			var lng = $('.aCR_hid_lng input', last).val();
			
			mgMap.addMarker({lat: lat, lng: lng});
		}
	
	
		//// MICROGUIDE ACCORDION /////////////////////////////////////////////////////////////////////
	
		var mgEditItemAccordion = {};
		
		mgEditItemAccordion.init = function ()
		{	
			$('.mgItemWrap:last').addClass('active').children('.mgFormItemExpand').show();
			
			$('.mgItemWrap').not('.active').children('.mgFormItemExpand').css({height: '0px'});
			
			
			$('.mgFormItem').live(
			'click',
			function (e)
			{	
				$('.mgItemWrap.active').removeClass('active').children('.mgFormItemExpand').css({height: '0px'});
				$(this).parents('.mgItemWrap').addClass('active').children('.mgFormItemExpand').css({height: 'auto'});
				
				var active = $('.mgItemWrap.active');
				var lat = $('.aCR_hid_lat input', active).val();
				var lng = $('.aCR_hid_lng input', active).val();
				mgMap.addMarker({lat: lat, lng: lng});
			});
		}
		
		mgEditItemAccordion.init();
		mgFindName_aC_init();
		mgFindAddress_aC_init();
	
	}
	
	
	
	
	
	
	
	
	//// TOOLTIPS /////////////////////////////////////////////////////////////////////
	
	var toolTips = {};
	
	toolTips.big = function(e) {
		toolTips.big.state = 1;
		if ($('#tooltip_big_single').length == 0) {
			$('form').eq(0)
				.append('<div id="tooltip_big_single" class="toolTipBig">\
					<div class="rc_box yellow1">\
						<div class="t"><div class="n"></div><div class="ne"></div><div class="nw"></div></div><div class="m"><div class="w"></div>\
						<div class="boxContent">\
							<div class="innerS" id="">\
								<div id="tooltip_big_single_content">I AM ZE TOOLTIP, YE!</div>\
							</div>\
						</div>\
						<div class="e"></div></div><div class="b"><div class="s"></div><div class="se"></div><div class="sw"></div></div>\
					</div>\
					<div class="tTArrow_down"></div>\
				</div>\
				');
				
			//$('#tooltip_big_single').hover(function(){},function(e){
				//toolTips.big.hide(e);								 
			//});
			$('#tooltip_big_single').hover(function(){
				toolTips.big.isHovering = true;
			}
			,function(){
				toolTips.big.isHovering = false;
				toolTips.big.hide(e);
			});
		}
		
		$('#tooltip_big_single').removeClass('tt_small');	
		
		var contentContainer = $('.toolTipContent',e.currentTarget)
		
		var content = contentContainer.html();
		
		if (contentContainer.hasClass('small')) {
			var tt_small = true;	
		} else {
			var tt_small = false;	
		}
		
		if (content != '') {
			$('#tooltip_big_single_content').html(content);
			
			if (e.type === 'click' && !e.relatedTarget ) {
				// clicked by keyboard, so don't track the mouse!
			} else {
				
				// tooltip dimensions
				var ttWidth = $('#tooltip_big_single').outerWidth();
				var ttHeight = $('#tooltip_big_single').outerHeight();
			
				// mouse position (viewport, not document)
				//var posX = scrolledXY();
				//var posY = parseInt(e.pageY) - posX[1];
				//posX = parseInt(e.pageX) - posX[0];		
				var posOff = $(e.currentTarget).offset();
				var posX = posOff.left + ($(e.currentTarget).outerWidth() / 2);
				var posY = posOff.top + ($(e.currentTarget).outerHeight() / 2);
				
				
				// screen dimension
				var bleedX = $(window).width();
				var bleedY = $(window).height();
				
				var posXAdjust = parseInt($('#tooltip_big_single').css('margin-left')); // adjust for tootip arrow position
				posXAdjust = posXAdjust * -1; // turn into positive value (negative is assumed)
				ttWidth = ttWidth - posXAdjust;
				
				var setLeft = parseInt(posX);
				var setTop = (parseInt(posY) - ttHeight);
				
				if (tt_small == true) {
					$('#tooltip_big_single').addClass('tt_small');	
				} else {
					if ((posX + ttWidth) > bleedX) { // if tooltip is outside right window border
						$('#tooltip_big_single').addClass('shiftLeft');
						setLeft = (parseInt(posX) -(ttWidth - posXAdjust));
					}
					
					if (ttHeight > posY) {  // if tooltip is higher than window top
						var ttArrHeight = $('#tooltip_big_single .tTArrow_down').height();
						
						$('#tooltip_big_single')
							.addClass('shiftDown')
							.find('.tTArrow_down')
								.css('top','-'+(ttHeight-ttArrHeight-1)+'px');
			
						setTop = parseInt(posY);
						//console.log($('#tooltip_big_single .tTArrow_down').css('top'))
					}
				}
				

				$('#tooltip_big_single').css({
					left: setLeft + 'px',
					top: setTop + 'px'
				});
				
			}
		}
	};
	
	toolTips.big.hide = function(e) {
		var tt = $('#tooltip_big_single');
		//alert(toolTips.big.isHovering);
		
		if ($(e.relatedTarget).parents('#tooltip_big_single').length == 0 && toolTips.big.isHovering == false) {
			toolTips.big.state = 0;
			$('#tooltip_big_single')
				.css({
					left: '0px',
					top: '-9999px'
				})
				.removeClass('shiftDown shiftLeft')
				.find('.tTArrow_down')
					.css('top','-1px')
				.end()
				.find('#tooltip_big_single_content')
					.html('');
		}
	}
	
	toolTips.big.state = 0;
	toolTips.big.timerOn = null;
	toolTips.big.timerOff = null;
	toolTips.big.isHovering = false;
	
	toolTips.big.addEvents = function() {
		$('.toolTipContent').parent().hover(function(e){
			clearTimeout(toolTips.big.timerOff);
			toolTips.big.timerOn = setTimeout(function(){
				toolTips.big(e);										 
			},250);
		}
		,function(e){
			clearTimeout(toolTips.big.timerOn);
			toolTips.big.timerOff = setTimeout(function(){
				toolTips.big.hide(e);										 
			},700);
		});
	};
	
	//// GET SCROLLED DISTANCE /////////////////////////////////////////////////////////////////////
	
	scrolledXY = function() {
		var scrX = 0, scrY = 0;
		if( typeof( window.pageYOffset ) == 'number' ) {
			scrY = window.pageYOffset;
			scrX = window.pageXOffset;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			scrY = document.body.scrollTop;
			scrX = document.body.scrollLeft;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			scrY = document.documentElement.scrollTop;
			scrX = document.documentElement.scrollLeft;
		}
		return [scrX,scrY];
	}
	
	
	
	//// MODAL LAYER /////////////////////////////////////////////////////////////////////
	
	var modal = {};
	modal.layer = {};

	modal.layer.init = function() {

	    $('a.showTips').click(function() {
	        modal.layer.show('#tipsa'); // TEMP!
	        return false;
	    });

	    $('a.showImage').click(function() {
	        modal.layer.show('#image'); // TEMP!
	        return false;
	    });
	    
		$('.modal a.close').click(function(){
			modal.layer.hide('.modal.active');
			return false;
		});
		
		$(window).resize(function(){
			modal.layer.place('.modal.active');
		});
		
	    
	}
	
	modal.layer.show = function(jQSel) {
		$(jQSel)
			.addClass('active');

		modal.shade.show();
		modal.layer.place(jQSel);
	}
	
	modal.layer.place = function(me) {
		var myHeight = $(me).outerHeight();
		var winPosY = scrolledXY(); // find out how much the window is scrolled
		winPosY = parseInt(winPosY[1]) + ($(window).height() / 2); // find center of viewport
		winPosY = winPosY - (myHeight / 2); // detuct half the height of the modal layer
		$(me).css('top',winPosY+'px');
	}
	
	modal.layer.hide = function(jQSel) {
		$(jQSel)
			.removeClass('active')
			.css('top','-9999px');
		modal.shade.hide();
	}
	
	//// MODAL SHADE /////////////////////////////////////////////////////////////////////
	
	modal.shade = {};
	
	modal.shade.show = function() {
		if ($('#modalShade').length == 0) {
			$('form:last')
				.after('<div id="modalShade"></div>');
			$('#modalShade').click(function(){
				modal.shade.hide();
				modal.layer.hide('.modal.active');
			});
		}
		
		$('#modalShade').show();
	}
	
	modal.shade.hide = function() {
		$('#modalShade').hide();	
	}
	
	//// IMAGE GALLERY /////////////////////////////////////////////////////////////
	var imgGallFunctions = {};

	imgGallFunctions.imgCheckLoop = false;
	imgGallFunctions.imgCheckThis = false;

	function imageGallery()
	{
		//// GET ALL INSTANCES
		var galleries = $('.imageGallery');
		
		//// BIND EVENTS
		$('.imageGallery').each(function(){
										 
			$('.items a', this).click(function(e){
				var gallery = $(this).parents('.imageGallery');
				$('.imageViewPort img', gallery).attr('src', e.currentTarget.href);
				$('.items li.selected', gallery).removeClass('selected');
				$(this).parents('li').addClass('selected');		
				
				return false;
			});
			
			$('a.expand', this).click(function(e){
				imgGallFunctions.loadImage(this);
				$(this).parents('.imageGallery').eq(0).addClass('activeGallery');
				return false;
			});
			
			$('a.prev', this).click(function(e){
				var gallery = $(this).parents('.imageGallery');
				var size = $('ul.items li').size()-1;
				var index = $('li.selected', gallery).parent().children().index($('li.selected', gallery));
				
				var setIndex = ((index-1) < 0) ? size : index-1;
				
				$('.items li.selected', gallery).removeClass('selected');
				$('.items li', gallery).eq(setIndex).addClass('selected');
				$('.imageViewPort img', gallery).attr('src', $('.items li.selected a', gallery).attr('href'));	
				
				return false;
			});
			
			$('a.next', this).click(function(e){
				var gallery = $(this).parents('.imageGallery');
				var size = $('ul.items li').size()-1;
				var index = $('li.selected', gallery).parent().children().index($('li.selected', gallery));
				
				var setIndex = ((index+1) > size) ? 0 : index+1;
				
				$('.items li.selected', gallery).removeClass('selected');
				$('.items li', gallery).eq(setIndex).addClass('selected');
				$('.imageViewPort img', gallery).attr('src', $('.items li.selected a', gallery).attr('href'));	
				
				return false;
			});
			
			$('.imageViewPort img', this).click(function(){
				$('a.expand', $(this).parents('.imageGallery').eq(0)).click();
			});
		});
	}
	
	
	//// LOAD IMAGE
	imgGallFunctions.loadImage = function(me) {
			var gallery = $(me).parents('.imageGallery');
			var imgGallUrl = $('.items li.selected a', gallery).attr('rel');
			var imgLayer = $('#imageGalleryOverlayView');
			
			if (!$('#pageShade').hasClass('closeable_imgGall')) {
				$('#pageShade').show().fadeTo(0,0);
				$('#pageShade').addClass('closeable_imgGall');
				$('#pageShade').click(function(){
					imgGallFunctions.hidePageShade();
				});
			}
			
			$('#pageShade').show().fadeTo('normal',0.6);
			
			
			imgLayer.html('<img src="'+imgGallUrl+'" alt="" />');
			
			var currentImage = $('#imageGalleryOverlayView img');
			
			currentImage
				.data("gallery", gallery)
				.click(function(){
					imgGallFunctions.nextImage();
				});
			
			imgGallFunctions.imgCheckThis = currentImage
			imgGallFunctions.imgCheckLoop = setInterval(function() {
				if ($(imgGallFunctions.imgCheckThis).width() > 32) {
					imgGallFunctions.displayImage();
					clearTimeout(imgGallFunctions.imgCheckLoop);
					imgGallFunctions.imgCheckThis = false;
				}													
			},200);
			
	}
	
	imgGallFunctions.displayImage = function(e) {
		var imgLayer = $('#imageGalleryOverlayView');
		var currentImage = $('#imageGalleryOverlayView img');
		
		if (currentImage.width() > ($(window).width() * 0.85)) {
			currentImage.width($(window).width() * 0.85);
		} else if (currentImage.height() > ($(window).height() * 0.85)) {
			currentImage.height($(window).height() * 0.85);
		}
		
		var scrolledFromTop = scrolledXY();
		scrolledFromTop = scrolledFromTop[1];
		
		imgLayer.css({
			marginLeft: '-' + (imgLayer.width() / 2) + 'px',
			marginTop: '-' + (imgLayer.height() / 2) + 'px',
			top: (scrolledFromTop + ($(window).height() / 2)) + 'px'
		});
	}
	
	//// NEXT IMAGE
	imgGallFunctions.nextImage = function(e)
	{
		$('#imageGalleryOverlayView')
			.fadeOut(500,function(){
				$(this)
					.css({
						top: '0px',
						left: '50%',
						marginTop: '-9999px',
						display: 'block'
					}).html('');
					
				$('a.next',$('.activeGallery').eq(0)).click();
				$('a.expand',$('.activeGallery').eq(0)).click();
			});
	}
	
	//// HIDE THE LIGHTBOX & PAGE SHADE
	imgGallFunctions.hidePageShade = function() {
		$('.activeGallery').removeClass('activeGallery');
		
		$('#pageShade').fadeTo('normal',0).hide();
		$('#imageGalleryOverlayView')
			.fadeOut('normal',function(){
				$(this)
					.css({
						top: '0px',
						left: '50%',
						marginTop: '-9999px',
						display: 'block'
					}).html('');
			});
	}
	
	
	
	
	
	//// XMAS 09 BOOKING FORM /////////////////////////////////////////////////////////////////////
	
	xmas09bf = {}
	
	xmas09bf.events_init = function() {
		$('#xmas09_bookingForm .close')
			.click(function(){
				xmas09bf.layer_hide();
				return false;
			})
		$('#xmas09_bookingForm .sendForm')
			.click(function(){
				//alert('eventet');
				xmas09bf.send();
				return false;
			});
				
		$('#pageShade').click(function(){
			xmas09bf.layer_hide();				   
		});
		
		$('a[href*=xmas09bf]').click(function(){
			xmas09bf.layer_show();
			return false;				   
		});
		
		$('#xmas09_bookingForm .header').text('Boka tid under misteln');
		
		$('#xmas09_bookingForm .innerS')
			.append('\
			<div class="kthnxbye">Vi ses i Bältesspännarparken <span class="wutDate"></span> <span class="wutTime"></span>.\
				<fieldset>\
					<div style="width: 95px;" class="inputButton right"><div><button class="large green right styled"><span><span><i class="~"><i></i></i>Stäng</span></span></button></div></div>\
				</fieldset>\
			</div>');
			
		$('#xmas09_bookingForm .kthnxbye button').click(function(){
			xmas09bf.layer_hide();
		});
	}
	
	xmas09bf.layer_show = function() {
		$('#pageShade').show();
		$('#xmas09_bookingForm').addClass('active');
	}
	
	xmas09bf.layer_hide = function() {
		$('#pageShade').hide();
		$('#xmas09_bookingForm').removeClass('active');
		$('.xmas09bf_form, #xmas09_bookingForm .close').show();
		$('#xmas09_bookingForm .kthnxbye').hide();
		$('#xmas09_bookingForm .header').text('Boka tid under misteln');
	}
	
	xmas09bf.send = function() {
		//alert('sending...');
		//var xmasUrl = 'http://goteborg/Templates/Public/Handlers/Mistel.ashx?name=fredrikteeest&email=thrthr@gmail.com&date=2009-12-31&time=21:00';
		var xmasUrl = '/Templates/Public/Handlers/Mistel.ashx';	
		
		$.ajax({
			type: "GET",
			dataType: 'json',
			url: xmasUrl,
			data: "name=" + $('#xmas_name').val() + "&email=" + $('#xmas_email').val() + "&time=" + $('#xmas_time').val() + "&date=" + $('#xmas_date').val(),
			success: function(data) {
				//alert(data.name + ' ' + data.email);
				if (data.name) {
					$('#xmas_name').parents('.inputText').eq(0).removeClass('error');
				} else {
					$('#xmas_name').parents('.inputText').eq(0).addClass('error');
				}
				
				if (data.email) {
					$('#xmas_email').parents('.inputText').eq(0).removeClass('error');
				} else {
					$('#xmas_email').parents('.inputText').eq(0).addClass('error');
				}
				
				if (data.name && data.email) {
					$('#xmas09_bookingForm .header').text('Tack för din bokning');
							
					$('.xmas09bf_form, #xmas09_bookingForm .close').hide();
					
					$('#xmas09_bookingForm .kthnxbye .wutTime').text($('#xmas_time').val());
					var wutDate = $('#xmas_date').val();
					wutDate = wutDate.replace('_',' ');
					$('#xmas09_bookingForm .kthnxbye .wutDate').text(wutDate);
					$('#xmas09_bookingForm .kthnxbye').show();	
				}
			},
			error: function(err, bla, blabla) {
				//alert('post error - ' + bla);
			},
			complete: function() {
				//alert('klares');
			}
		});
	}

	
	//// GUIDEPUSH DATE SPAN /////////////////////////////////////////////////////////////////////

	var guidePush_setSpan = function(me, indexCheck) {
		var scope = $(me).parent().parent().parent().parent();
		var spans = $('input', scope);
		var fromInput = spans[2];
		var toInput = spans[3];

		var fdate = $(fromInput).DatePickerGetDate();
		var tdate = $(toInput).DatePickerGetDate();
		var dateConv = function(date) {
			return date.getFullYear() + "-" + (date.getMonth() < 9 ? "0" : "") + (date.getMonth() + 1) + "-" + (date.getDate() < 10 ? "0" : "") + date.getDate();
		};

		if (me == fromInput) {
			fdate.addDays(1);
			$(toInput).val(dateConv(fdate));
		} else if (me == toInput && tdate < fdate) {
			tdate.addDays(-1);
			$(fromInput).val(dateConv(tdate));
		}

		/*
		if (spans.length > 0 && indexCheck % 2 == 0) {
		alert("oh");
		var dateSpan = parseInt(spans.val());
		var nowString = '';

			var currentVal = $('input.datePicker', scope).eq(0).val();
		currentVal = currentVal.split('-');

			var now = new Date(currentVal[0], currentVal[1], currentVal[2]);

			now.setDate(now.getDate() + dateSpan);


		var then = [];
		then[0] = now.getFullYear();
		then[1] = now.getMonth();
		if (then[1] < 10) {
		then[1] = '0' + then[1];
		}
		then[2] = now.getDate();
		if (then[2] < 10) {
		then[2] = '0' + then[2];
		}

			then = then.join('-');

			$('input.datePicker', scope).eq(1).val(then);

			// $('input.datePicker',scope).eq(1)
		//.val(then) 
		//.DatePicker({current: then});
		//
			
		}*/
	}
	
	//alert($('.guidePush_form input.datePicker').eq(0).val());
		
		/*
		$('.guidePush_form input.datePicker').eq(0).change(function(){
			alert('chäng');										 	
			var scope = $(this).parents('fieldset').eq(0);
			$('input.datePicker',scope).eq(1).val('2020-01-01');
		});
		*/
	
	//// AUTOCOMPLETE /////////////////////////////////////////////////////////////////////
	
	var aCR_scrollpaneSettings = {
		scrollbarWidth:17,
		dragMinHeight: 12,
		dragMaxHeight: 12,
		scrollbarMargin:0,
		showArrows:true
	}
	
	
	var inputAutoComplete = function(){
		this.holdForNKeys = 3;
		this.throttleDelay = 300; // in ms
		this.blockedKeyCodes = [9,13,16,17,18,20,27,36,37,38,39,45,91,93,112,113,114,115,116,117,118,119,120,121,123,123,224];
		this.recievedData = '';
		this.xhrAction = false;
		this.state_busy = false;
		this.busyTimeout = null;
		
		var scope = this;
		
		this.init = function(jQSel,ac_allBack) {
			if (ac_allBack == '') {
				ac_allBack = false;
			}
			var me = $(jQSel);
			var context = this;
			
			me
				.keyup(function(e){
					for (var i=0, il=scope.blockedKeyCodes.length; i<il; i++) {
						if (e.keyCode == scope.blockedKeyCodes[i]) {
							return false;
						}
					}
					context.trig(me,e.keyCode);
				})
				.bind('transmit',function(){
					context.transmit(me,ac_allBack,context);
				})
				.bind('recieve', function() {
				    context.recieve(me, context);
				});

	        $('.aCR_content').jScrollPane(aCR_scrollpaneSettings);

	        $('body').click(function(e) {
	            if ($(e.target).parents('.autoCompleteResult_wrap').length == 0) {
	                $('.autoCompleteResult').removeClass('aCR_visible');
	            }
	        });
	    }

	    this.setState_busy = function() {
	        this.state_busy = true;
	        var context = this;
	        this.busyTimeout = setTimeout(function() {
	            context.state_busy = false;
	        }, this.throttleDelay);
	    }

	    this.trig = function(me, keycode) {
	        var searchStr = $(me).val();

	        if ((this.state_busy == false && searchStr.length > scope.holdForNKeys) || keycode == 8) { // 8 = backspace
	            this.setState_busy();
	            $(me).trigger('transmit');
	        }
	    }

	    this.transmit = function(me, ac_allBack, context) {
	        if ($(me).val().length > context.holdForNKeys) {
	            data = eval(context.xhrAction);
	        }
	    }

	    this.recieve = function() { }
	};
	
	
	
	//// AUTOCOMPLETE - find name, microguide /////////////////////////////////////////////////////////////////////
    var mgFindNameFields = [];

	var mgFindName_aC_init = function() {

	    $('.namePlaceField').each(function(inputIndex) {
	        $('.namePlaceField_item:eq(' + inputIndex + ') .aCR_content li a')
                .live('click', function() {
                    var currScope = $(this).parents('.innerS').eq(0);
					
					mgGmv3.removeAllMarkers();
					var m = mgGmv3.addMarker({lat: $('.aC_Lat', this).html(), lng: $('.aC_Lng', this).html()});
					var latLng = mgGmv3.getLatLng(m);
					mgGmv3.panTo(latLng);
					
                    PageMethods.GetImage($(this).attr('rel'), $('.aC_TemplateId', this).html(), function(result, userContext, methodName) {
                        result = result.replace('~', '');
                        $('.imageThumb img', currScope).attr('src', result);
						$('.aCR_hid_Image input', currScope).val(result);
                    });
					
					$('.aCR_hid_visitId input', currScope).val($(this).attr('rel'));
					$('.aCR_hid_templateId input', currScope).val($('.aC_TemplateId', this).html());
					
					$('.namePlaceField', currScope).val($('.aC_Name', this).text());
                    $('.aCR_hid_lat input', currScope).val($('.aC_Lat', this).text());
                    $('.aCR_hid_lng input', currScope).val($('.aC_Lng', this).text());
                    $('.addressField', currScope).val($('.aC_Address', this).text());
                    $('.descriptionBox', currScope).html($('.aC_Description', this).text());
                    $('.linkUrlBox', currScope).val($('.aC_LinkUrl', this).text());

                    $('.aCR_visible', currScope).removeClass('aCR_visible');
                    
                    return false;
                });

	        mgFindNameFields[inputIndex] = new inputAutoComplete;

	        mgFindNameFields[inputIndex].init('.namePlaceField:eq('+inputIndex+')');
	        mgFindNameFields[inputIndex].holdForNKeys = 3;
	        mgFindNameFields[inputIndex].xhrAction = 'PageMethods.SearchVisitProducts($(".namePlaceField").eq('+inputIndex+').val(), lang, function(result, userContext, methodName) { mgFindNameFields['+inputIndex+'].recievedData = result; $(".namePlaceField").eq('+inputIndex+').trigger("recieve"); });';


	        mgFindNameFields[inputIndex].recieve = function(me, context) {
	            if (context.recievedData != '') {
	                var currVal = $(me).val();
	                var aCR = $(me).parents('.autoComplete_item').eq(0).find('.autoCompleteResult').eq(0);

	                if ((currVal == '') || (currVal.length <= context.holdForNKeys)) {
	                    aCR.removeClass('aCR_visible');
	                    aCR_list.html(''); // empty list
	                    return true;
	                }

	
	                mgFindNameFields[inputIndex].aCR_result = eval("(" + context.recievedData + ")");
					
					if (mgFindNameFields[inputIndex].aCR_result.length > 0) {
	
						var aCR_tmpl = aCR.find('.tmpl').html();
						var aCR_list = aCR.find('ul').eq(0);
	
						aCR_list.html(''); // empty list
						
						aCR.addClass('aCR_visible'); // show list element
	
						for (var i = 0, il = mgFindNameFields[inputIndex].aCR_result.length; i < il; i++) {
							var currentItem = '<li>' + aCR_tmpl + '</li>';
							currentItem = currentItem
								.replace('__Name__', mgFindNameFields[inputIndex].aCR_result[i].Name)
								.replace('__Name__', mgFindNameFields[inputIndex].aCR_result[i].Name)
								.replace('__VisitId__', mgFindNameFields[inputIndex].aCR_result[i].VisitId)
								.replace('__TemplateId__', mgFindNameFields[inputIndex].aCR_result[i].TemplateId)
								.replace('__LanguageId__', mgFindNameFields[inputIndex].aCR_result[i].LanguageId)
								.replace('__Lat__', mgFindNameFields[inputIndex].aCR_result[i].Latitude)
								.replace('__Lng__', mgFindNameFields[inputIndex].aCR_result[i].Longitude)
								.replace('__Address__', mgFindNameFields[inputIndex].aCR_result[i].Address)
								.replace('__Description__', mgFindNameFields[inputIndex].aCR_result[i].Description)
								.replace('__LinkUrl__', mgFindNameFields[inputIndex].aCR_result[i].LinkUrl);
							aCR_list.append(currentItem);
						}
	
						$('.aCR_content').jScrollPane(aCR_scrollpaneSettings);
					}
	            }

	            if ((currVal == '') || (currVal.length <= context.holdForNKeys)) {
	                aCR.removeClass('aCR_visible');
	                aCR_list.html(''); // empty list
	                return true;
	            }
	        }
        });
    }

    //// AUTOCOMPLETE - find address, microguide /////////////////////////////////////////////////////////////////////

    var mgFindAddressFields = [];

    var mgFindAddress_aC_init = function() {

        $('.addressField').each(function(inputIndex) {
            $('.addressField_item:eq(' + inputIndex + ') .aCR_content li a')
                .live('click', function() {
                    var currScope = $(this).parents('.innerS').eq(0);
					
					mgGmv3.removeAllMarkers();
					var m = mgGmv3.addMarker({lat: $('.aC_Lat', this).html(), lng: $('.aC_Lng', this).html()});
					var latLng = mgGmv3.getLatLng(m);
					mgGmv3.panTo(latLng);
					
                    $('.aCR_hid_lat input', currScope).val($('.aC_Lat', this).text());
                    $('.aCR_hid_lng input', currScope).val($('.aC_Lng', this).text());
                    $('.addressField', currScope).val($('.aC_Address', this).text());

                    $('.aCR_visible', currScope).removeClass('aCR_visible');
	
                    return false;
                });

            mgFindAddressFields[inputIndex] = new inputAutoComplete;

            mgFindAddressFields[inputIndex].init('.addressField:eq(' + inputIndex + ')');
            //mgFindAddressFields[inputIndex].throttleDelay = 1500;
            mgFindAddressFields[inputIndex].holdForNKeys = 3;
            mgFindAddressFields[inputIndex].xhrAction = 'PageMethods.SearchAdress($(".addressField").eq(' + inputIndex + ').val(), function(result, userContext, methodName) { mgFindAddressFields[' + inputIndex + '].recievedData = result; $(".addressField").eq(' + inputIndex + ').trigger("recieve"); });';


            mgFindAddressFields[inputIndex].recieve = function(me, context) {
                if (context.recievedData != '') {
                    var currVal = $(me).val();
                    var aCR = $(me).parents('.autoComplete_item').eq(0).find('.autoCompleteResult').eq(0);

                    if ((currVal == '') || (currVal.length <= context.holdForNKeys)) {
                        aCR.removeClass('aCR_visible');
                        aCR_list.html(''); // empty list
                        return true;
                    }

                    mgFindAddressFields[inputIndex].aCR_result = eval("(" + context.recievedData + ")");
					
					if (mgFindAddressFields[inputIndex].aCR_result.length > 0) {
						
						var aCR_tmpl = aCR.find('.tmpl').html();
						var aCR_list = aCR.find('ul').eq(0);
	
						aCR_list.html(''); // empty list
						
						aCR.addClass('aCR_visible'); // show list element
	
						for (var i = 0, il = mgFindAddressFields[inputIndex].aCR_result.length; i < il; i++) {
							var currentItem = '<li>' + aCR_tmpl + '</li>';
							currentItem = currentItem
								.replace('__Address__', mgFindAddressFields[inputIndex].aCR_result[i].Address)
								.replace('__Address__', mgFindAddressFields[inputIndex].aCR_result[i].Address)
								.replace('__Lat__', mgFindAddressFields[inputIndex].aCR_result[i].Lat)
								.replace('__Lng__', mgFindAddressFields[inputIndex].aCR_result[i].Long);
							aCR_list.append(currentItem);
						}
	
						$('.aCR_content').jScrollPane(aCR_scrollpaneSettings);
					}
						
                }

                if ((currVal == '') || (currVal.length <= context.holdForNKeys)) {
                    aCR.removeClass('aCR_visible');
                    aCR_list.html(''); // empty list
                    return true;
                }
            }
        });
    }
	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* BIG MAP
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	function map ()
	{
			
		var mapSettings =
		{
			mapNode: 'map',
			centerLat: 57.7232446,
			centerLng: 11.7671044,
			initZoom: 10,
			mapTypeControl: true,
			
			// MARKER SETTINGS
			markerIconUrl: 		'/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.png',
			markerIconSize: 	{width: 25, height: 35},
			markerIconOrigin: 	{x: 0, y: 0},
			markerIconAnchor: 	{x: 0, y: 35},
			
			markerShadowSize: 	{width: 35, height: 25},
			markerShadowOrigin: {x: 0, y: 0},
			markerShadowAnchor: {x: -10, y: 20},
			markerShadowUrl: 	'/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.shadow.png',
			
			// MAP TYPE
			mapType: google.maps.MapTypeId.ROADMAP
		}
		
		//// GET INSTANCE OF MAP	
		var gmv3 = new GMV3(mapSettings);
		
		
		//// METHOD TRIGGERD WHEN THE MAP IS READY
		mapLoaded = function ()
		{	
			$('#filter :input').bind('click', setVisibility);
			$('#map_search').bind('keyup', loadMarkers);
			
			//// MAKE FILTER LIST DRAGGABLE
			$('#filter').draggable({opacity: .5, containment: $('#map')});
			
			$('#filter #toggle')
			.toggle(
				function (e)
				{
					$(e.target).removeClass('-').addClass('+');
					var obj = $(e.target).parents('#filter');
					$('#controls', obj).hide();
				},
				function (e)
				{
					$(e.target).removeClass('+').addClass('-');
					var obj = $(e.target).parents('#filter');
					$('#controls', obj).show();
				}
			);
			
			if(gup('pid').length > 0)
			{
				$.ajax({
				type: "GET",
				url: "/templates/public/handlers/GetProducts.ashx",
				//url : "/Templates/Public/_json/museum.json",
				dataType: "json",
				data: "pid=" + gup('pid') + "&lang=" + lang,
				queue: "search",
				cancelExisting: true,
				beforeSend: function () {$('#loader').show();},
				success: addMarkers,
				error: function () {$('#loader').hide();},
				complete: function () {$('#loader').hide();}
				});
			}
			
		}
		
		
		function loadMarkers(e)
		{	
		
			if(search_timeout != undefined)
				window.clearInterval(search_timeout);
				
			search_timeout = window.setTimeout(
			function ()
			{
				search_timeout = undefined;
				
				gmv3.removeAllMarkers();
				
				$.ajax({
				type: "GET",
				url: "/templates/public/handlers/GetProducts.ashx",
				//url : "/Templates/Public/_json/museum.json",
				dataType: "json",
				data: "query="+e.target.value+"&lang="+lang,
				queue: "search",
				cancelExisting: true,
				beforeSend: function () {$('#loader').show();},
				success: addMarkers,
				error: function () {$('#loader').hide();},
				complete: function () {$('#loader').hide();}
				});
			},
		500);
		}
		
		function addMarkers (data)
		{
			var dataLen = data.length-1;

			$.each(
				data,
				function(index) {

				    var data = this;

				    if (!data.Longitude || !data.Latitude) {
				        //alert('no lat/long!');
				        return;
				    }

				    //// CONTENT OF INFO BOX
				    var content = '<div class="label">' + data.Name + '</div><div class="score value' + data.RatingLevel + '"></div>';

				    var keys = '';

				    //// LIST THE KEYS DEFINED FOR THE SPECIFIC MARKER
				    if (this.Keys.length > 0) {
				        var keyLen = this.Keys.length;

				        $.each(
						this.Keys,
						function(index) {
						    if (index == 0 || index == 3) {
						        keys += '<div class="key">';
						    }

						    if (index < 4) {
						        keys += '<a href="' + this.url + '">' + this.label + '</a>, ';
						    }

						    if (index == 4) {
						        keys += '<a href="' + this.url + '">' + this.label + '</a>';
						    }

						    if (index == 2 || index == 4) {
						        keys += '</div>';
						    }

						});
				    }


				    content += keys;

				    content += '<div class="actions">' +
						//'<a class="green" href="' + data.OrderLink.url + '">' + data.OrderLink.label + '</a>' +
						'<a class="blue" href="' + data.PageLink.url + '">' + data.PageLink.label + ' ' + this.Name + '</a>' +
					'</div>';


				    /// CHECK IF THE MARKER SHOULD BE VISIBLE
				    var state = false;

				    //console.log(data.Keys);

				    if (data.Keys.length < 1) {
				        state = true;
				    } else {
				        $.each(data.Keys,
					        function() {
					            var id = 'filter_' + this['id'];
					            if (document.getElementById(id).checked) {
					                state = true;
					            }
					        });
				    }

				    


				    //// STORE MIN/MAX BOUNDARY
				    if (data.Latitude > 0 || data.Longitude > 0) {
				        //// ADD THE MARKER TO THE MAP
				        //alert('all nice and big: ' + data.Latitude);
				        var m = gmv3.addMarker({ lat: data.Latitude, lng: data.Longitude, draggable: false, clickable: true, visible: state, keysArray: data.Keys });
				        //alert(state);
				        gmv3.enableInfoBox(m, 'click', content);
				    } else {
				        //alert('too smal vals (lat long)');
				    }
				}
			);

            
			if(dataLen > 0)
			    gmv3.makeMarkerFit();
		}
		
		function setVisibility()
		{
			$('.infoBox').fadeOut(300);
			var markers = gmv3.getMarkersArray();
			
			$.each(
			markers, 
			function () 
			{
				var state = false;
				
				$.each(this.keysArray,
				function ()
				{
					var id = 'filter_'+this['id'];
					if(document.getElementById(id).checked)
					{
						state = true;
					}
				});
				
				gmv3.setMarkerVisibility(this, state);
			});
		}
	}
	

	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* ProductPageMap
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	function productPageMap ()
	{

		var latEl = document.getElementById('productMapLat');
		var lngEl = document.getElementById('productMapLng');
		var zoom  = (document.getElementById('productMapZoom') && (document.getElementById('productMapZoom').value.length > 0)) ? document.getElementById('productMapZoom').value : 10;
		if (latEl && latEl.value > 0 && lngEl && lngEl.value > 0) {

			var lat = latEl.value;
			var lng = lngEl.value;
			
			var mapSettings =
			{
				mapNode: 'mapViewPort',
				centerLat: lat,
				centerLng: lng,
				initZoom: parseInt(zoom),
				mapTypeControl: true,
				
				// MARKER SETTINGS
				markerIconUrl: 		'/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.png',
				markerIconSize: 	{width: 25, height: 35},
				markerIconOrigin: 	{x: 0, y: 0},
				markerIconAnchor: 	{x: 0, y: 35},
				
				markerShadowSize: 	{width: 35, height: 25},
				markerShadowOrigin: {x: 0, y: 0},
				markerShadowAnchor: {x: -10, y: 20},
				markerShadowUrl: 	'/Templates/Public/Images/UI/Core/googleMaps/googleMaps.marker.v1.shadow.png',
				
				// MAP TYPE
				mapType: google.maps.MapTypeId.ROADMAP
			}
			
			//// GET INSTANCE OF MAP	
			var ppgmv3 = new GMV3(mapSettings);
			
			mapLoaded = function ()
			{
				var phoneContent = document.getElementById('productMapEmail');
				if (!phoneContent) {
					phoneContent = {};
					phoneContent.value = '';
				} else  {
					phoneContent = phoneContent.value
				}
				
				//alert(phoneContent);
				
				var m = ppgmv3.addMarker({lat: lat, lng: lng, draggable: false, clickable: true, visible: true});
				
				var title 	= (document.getElementById('productMapTitle').value.length > 0) ? document.getElementById('productMapTitle').value : '';
				var address = (document.getElementById('productMapAddress').value.length > 0) ? document.getElementById('productMapAddress').value : '';
				var city 		= (document.getElementById('productMapCity').value.length.length > 0) ? document.getElementById('productMapCity').value : '';
				var phone 	= (document.getElementById('productMaPhone').value.length > 0) ? document.getElementById('productMaPhone').value : '';
				var email 	= (document.getElementById('productMapEmail').value.length > 0) ? document.getElementById('productMapEmail').value : '';
				//var email 	= (phoneContent.value.length > 0) ? phoneContent.value : '';
				
				
				if(
					 title.length > 0
					 || address.length > 0
					 || city.length > 0
					 || email.length > 0
				)
				{
					var content = '\
					<div class="label">'+title+'</div>\
					<div class="adress">'+address+'</div>\
					<div class="city">'+city+'</div>\
					<div class="phone">'+phone+'</div>\
					<div class="phone">'+email+'</div>\
					';
					
					ppgmv3.enableInfoBox(m, 'click', content);
				}
				
			}
		}
	}
	
	
	function gup( name )
	{
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
			return "";
		else
			return results[1];
	}


	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* SMULTRONSTÄLLEN PAGE MAP FUNCTIONS
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	function smap() {

/*jquery cookie plugin*/
jQuery.cookie=function(b,j,m){if(typeof j!="undefined"){m=m||{};if(j===null){j="";m.expires=-1;}var e="";if(m.expires&&(typeof m.expires=="number"||m.expires.toUTCString)){var f;if(typeof m.expires=="number"){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000));}else{f=m.expires;}e="; expires="+f.toUTCString();}var l=m.path?"; path="+(m.path):"";var g=m.domain?"; domain="+(m.domain):"";var a=m.secure?"; secure":"";document.cookie=[b,"=",encodeURIComponent(j),e,l,g,a].join("");}else{var d=null;if(document.cookie&&document.cookie!=""){var k=document.cookie.split(";");for(var h=0;h<k.length;h++){var c=jQuery.trim(k[h]);if(c.substring(0,b.length+1)==(b+"=")){d=decodeURIComponent(c.substring(b.length+1));break;}}}return d;}};

		
/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */
(function(d){d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(f,e){d.fx.step[e]=function(g){if(g.state==0){g.start=c(g.elem,e);g.end=b(g.end);}g.elem.style[e]="rgb("+[Math.max(Math.min(parseInt((g.pos*(g.end[0]-g.start[0]))+g.start[0]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[1]-g.start[1]))+g.start[1]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[2]-g.start[2]))+g.start[2]),255),0)].join(",")+")";};});function b(f){var e;if(f&&f.constructor==Array&&f.length==3){return f;}if(e=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)){return[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])];}if(e=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)){return[parseFloat(e[1])*2.55,parseFloat(e[2])*2.55,parseFloat(e[3])*2.55];}if(e=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)];}if(e=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)];}return a[d.trim(f).toLowerCase()];}function c(g,e){var f;do{f=d.curCSS(g,e);if(f!=""&&f!="transparent"||d.nodeName(g,"body")){break;}e="backgroundColor";}while(g=g.parentNode);return b(f);}var a={};})(jQuery);


/**
 * jQuery background-position animation plugin
 * @author Alexander Farkas
 * v. 1.21
 */
(function(b){if(!document.defaultView||!document.defaultView.getComputedStyle){var d=jQuery.curCSS;jQuery.curCSS=function(g,e,h){if(e==="background-position"){e="backgroundPosition";}if(e!=="backgroundPosition"||!g.currentStyle||g.currentStyle[e]){return d.apply(this,arguments);}var f=g.style;if(!h&&f&&f[e]){return f[e];}return d(g,"backgroundPositionX",h)+" "+d(g,"backgroundPositionY",h);};}var c=b.fn.animate;b.fn.animate=function(e){if("background-position" in e){e.backgroundPosition=e["background-position"];delete e["background-position"];}if("backgroundPosition" in e){e.backgroundPosition="("+e.backgroundPosition;}return c.apply(this,arguments);};function a(f){f=f.replace(/left|top/g,"0px");f=f.replace(/right|bottom/g,"100%");f=f.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");var e=f.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);return[parseFloat(e[1],10),e[2],parseFloat(e[3],10),e[4]];}b.fx.step.backgroundPosition=function(f){if(!f.bgPosReady){var h=b.curCSS(f.elem,"backgroundPosition");if(!h){h="0px 0px";}h=a(h);f.start=[h[0],h[2]];var e=a(f.options.curAnim.backgroundPosition);f.end=[e[0],e[2]];f.unit=[e[1],e[3]];f.bgPosReady=true;}var g=[];g[0]=((f.end[0]-f.start[0])*f.pos)+f.start[0]+f.unit[0];g[1]=((f.end[1]-f.start[1])*f.pos)+f.start[1]+f.unit[1];f.elem.style.backgroundPosition=g[0]+" "+g[1];};})(jQuery);

/**
 * @author Marco Alionso Ramirez, marco@onemarco.com
 * @url http://onemarco.com
 * @version 1.0
 * This code is public domain
 */

/**
 * The Tooltip class is an addon designed for the Google Maps GMarker class. 
 * @constructor
 * @param {GMarker} marker
 * @param {String} text
 * @param {Number} padding
 */

function Tooltip(marker,text,padding){this.marker_=marker;this.text_=text;this.padding_=padding;}
Tooltip.prototype=new GOverlay();Tooltip.prototype.initialize=function(map){var div=document.createElement("div");div.innerHTML=this.text_;div.className='smultTip';div.style.position='absolute';div.style.visibility='hidden';map.getPane(G_MAP_FLOAT_PANE).appendChild(div);this.map_=map;this.div_=div;}
Tooltip.prototype.remove=function(){this.div_.parentNode.removeChild(this.div_);}
Tooltip.prototype.copy=function(){return new Tooltip(this.marker_,this.text_,this.padding_);}
Tooltip.prototype.redraw=function(force){if(!force)return;var markerPos=this.map_.fromLatLngToDivPixel(this.marker_.getPoint());var iconAnchor=this.marker_.getIcon().iconAnchor;var xPos=Math.round(markerPos.x-this.div_.clientWidth/2);var yPos=markerPos.y-iconAnchor.y-this.div_.clientHeight-this.padding_;this.div_.style.top=yPos+'px';this.div_.style.left=xPos+'px';}
Tooltip.prototype.show=function(){this.div_.style.visibility='visible';}
Tooltip.prototype.hide=function(){this.div_.style.visibility='hidden';}
		
		// set global constants
		var centerLat 		= 57.6930;	//starting location centered on Göteborg, Sweden
		var centerLong 		= 11.9707;
		var mapData 		= smultronXml.alla; //location of initially-loaded map data
		var pointsArray 	= new Array();	//initializing Array to store point data
		var tempArray		= new Array();  //array to store votes made on current page load
		var map;
				
		init = function() {
			
			$('<div id="modalShade" style="display: none"></div>').appendTo("body");
			
			//Beyond this place, there be dragons.
			
			$('#tipsa').remove();
			
			var modalMail = '<div style="width: 300px; height: 300px; margin-left: -165px; top: 68px; display: none" class="modal modal_generic active" id="tipsa"> <div class="rc_box yellow1 modal_box"> <div class="t"><div class="n"></div><div class="ne"></div><div class="nw"></div></div><div class="m"><div class="w"></div> <div class="boxContent"> <div class="innerS"> <div class="modal_header"> <a href="#" class="close"><i class="~"><i></i></i>Stäng</a> <tt></tt> <strong>E-kort / mail</strong> </div> <div class="modal_txt"> <ul> <li id="shareTab" class=""> <div class="shareFirst"> <label style="float: left; width: 250px;" class="clearfix" for="share_email"> <strong></strong> <span class="inputText yellow"><span><input type="text" value="someone@domain.se" alt="someone@domain.se" name="share_email" class="emailFormTo_smult yellow styled" id="share_email" style="width: 218px; float: none;"></span></span> </label> <label style="float: left; width: 250px; margin-top: 3px;" class="clearfix" for="share_name"> <strong></strong> <span class="inputText yellow"><span><input type="text" value="Ditt namn" alt="Ditt namn" name="share_name" class="emailFormName_smult yellow styled" id="share_name" style="width: 218px; float: none;"></span></span> </label> <div style="clear: both; float: none;" class="sendArea clearfix"> <div class="cf_center"><div class="inputButton center" style="width: 94px;"><div><button type="button" class="emailFormButton large green center styled"><span><span><i class="~"><i></i></i>Skicka</span></span></button></div></div></div> </div> </div> <div style="display: none;" class="shareMessage"> <p style="text-align: center; padding-top: 25px;">Ditt tips har nu skickats.</p> </div> </li> </ul> </div> </div> </div> <div class="e"></div></div><div class="b"><div class="s"></div><div class="se"></div><div class="sw"></div></div> </div> </div>';

			
			
			$(modalMail).appendTo('body');
			
			if (!($.cookie("votes"))) {
				$.cookie("votes","",{expires:730})
			} else {
				pointsArray = ($.cookie("votes")).split(",")
			};
			//transparent url(/Templates/Public/Images/UI/Core/googleMaps/map_bg.gif) left top no-repeat;
			$('#smultronmap_bg').css({
				"background-image": 'url('+smultronXml.mapFrame+')', 
				"background-position": 'left top',
				"background-repeat": "no-repeat"
			});
			
			$('#votes').data("newvotes","");
						
			$.ajax({
				url: smultronXml.alla,
				type: 'GET',
				dataType: 'xml',
				success: function(xml) {
					
					$(xml).find("marker").each(function() {
						if (window.location.hash === "#"+$(this).attr("locid") || getQs("xid") === $(this).attr("locid")) {
							postcardd(
								$(this).attr("locid"),
								$(this).attr("label"),	
								$(this).attr("img"),	
								$(this).attr("desc"),	
								$(this).attr("attr"),	
								$(this).attr("url"),	
								$(this).attr("votes"),
								$(this).attr("userid")
							);
						}
					});
				}
			});
			
			populateMap(mapData);

			$('#closePostcard').click(function() {
				$(this).parent().fadeOut('400',function(){$('#votes').removeClass('voted');});
				window.location.hash = "#map";
				GEvent.clearListeners(map,"click");
				$('.clip').remove();
				return false;
			});

			$('#topplistan').click(function() {
				if(window.pageTracker) {pageTracker._trackPageview("topplistan")};
				pointSwap(smultronXml.toplist);
				$('#kontrollpanel li a').removeClass('active');
				$(this).children('a').addClass('active');
				$('#postcard').fadeOut(400, function() {
					GEvent.clearListeners(map,"click");
				});
				$('.clip').remove();
				window.location.hash = "#map";
				return false;
			});
			
			$('#rekommenderar').click(function() {
				if(window.pageTracker) {pageTracker._trackPageview("rekommenderar")};
				pointSwap(smultronXml.rekommenderar);
				$('#kontrollpanel li a').removeClass('active');
				$(this).children('a').addClass('active');
				$('#postcard').fadeOut(400, function() {
					GEvent.clearListeners(map,"click");
				});
				$('.clip').remove();
				window.location.hash = "#map";
				return false;
			});
			
			$('#alla').click(function() {
				if(window.pageTracker) {pageTracker._trackPageview("alla")};
				pointSwap(smultronXml.alla);
				$('#kontrollpanel li a').removeClass('active');
				$(this).children('a').addClass('active');
				$('#postcard').fadeOut(400, function() {
					GEvent.clearListeners(map,"click");
				});
				$('.clip').remove();
				window.location.hash = "#map";
				return false;
			});

			$('#votes').click(function() {
				if ($(this).hasClass('voted')) {
					return false;
				} else {
					$.post(smultronXml.vote+$(this).attr("rel"),{});
					 
					var gilla = parseInt($('#gilla').val(),10);
					gilla = gilla+1;
					$('#gilla').val(gilla);
					$('#votes').text(gilla);
										
					pointsArray.push($(this).attr("rel"));
					tempArray.push($(this).attr("rel"));
					$.cookie("votes",pointsArray.join(),{expires:730})
					
					$(this).animate({"color": "#ffc345","background-position": "right 50px;"}, 300, function() {
						$(this).animate({"color": "#777777","background-position": "right bottom;"}, 300,function() {
							$(this).addClass('voted');
						});
					});
					
					return false;
				};
			});

			$('.addNewPoint').click(function() {
				$('#addForm').show('default', function() {
					if ($.browser.msie) {
						this.style.removeAttribute('filter');
					};
					$.scrollTo("#addForm",600);
					if (GBrowserIsCompatible()) {

						smmap = new GMap2(document.getElementById("smallMap"));
						smmap.setMapType(G_NORMAL_MAP);

						var location = new GLatLng(centerLat, centerLong);

						smmap.setCenter(location, 12);
						smmap.setUIToDefault();
						smmap.disableScrollWheelZoom();
						
						var addPoint = GEvent.addListener(smmap, "click", function(overlay, location) {
							var added = new GMarker(location,{clickable:false, draggable: true, icon:myIcons['pin']});
							smmap.addOverlay(added);
							$('.lat_smult').val(location.lat()); $('.long_smult').val(location.lng()); 
							GEvent.removeListener(addPoint);
							GEvent.addListener(added, "dragend", function(point) {
								$('.lat_smult').val(point.lat()); $('.long_smult').val(point.lng()); 
							});
						});
					}
				});
				
				return false;
			});
			
			$('.rubrik_smult').bind('keydown keyup', function(event) {
				inputCount(".rubrik_smult",".rubrikCount_smult",20,5);
			});
			
			$('.beskrivning_smult').bind('keydown keyup', function(event) {
				inputCount(".beskrivning_smult",".beskrivningCount_smult",140,25);
			});
			
			$('.showDisclaimer').click(function() {
				$('.disclaimerText').slideDown('slow');
				return false;
			});
			
			$('.submit_smult').click(function() {
				$('span.smultronError, span.checkboxError').hide();
				var complete;
				$('#addForm input[type=checkbox]:not(:checked)').siblings("span.checkboxError").show();
				
				$('#addForm input, #addForm textarea').each(function() {
					if(($(this).val() == "")==true) {
						complete="NO";
						
						
						$("#addForm input, #addForm textarea").each(function() {
							if(($(this).val() == "")==true) {
								$(this).parents('label').children('span.smultronError').show();
								$(this).parents('label').siblings('span.smultronError').show();
								$(this).parents('span.inputText').siblings('.identLabel').children('span.smultronError').show();
								$(this).parents(".inputTextarea").siblings("p.textarea").children("span.smultronError").show();
							}
						});
						
						
						if ($('.lat_smult').val() == "") {$('span.smallMapError').show();};
						
						
						return false;
					} else {
						complete="YES";
					};
				});
				if (complete==="YES" && $(".d1_smult").attr("checked")==true && $(".d2_smult").attr("checked")==true) {
					if(window.pageTracker) {pageTracker._trackPageview("addPoint");};
				} else {
					$('#submitFail').slideDown('slow');
					return false;
				};
				
			});
			
		};
		
		inputCount = function(field,cntfield,maxlimit,warning) {
			if ($(field).val().length > maxlimit) {
				$(field).val($(field).val().substring(0, maxlimit));
			} else {
				$(cntfield).val(maxlimit - $(field).val().length);
				if (parseInt($(cntfield).val()) <= warning) {
					$(cntfield).addClass('warning');
				} else {
					$(cntfield).removeClass('warning');
				};
			};
		};

		populateMap = function(mapData) {
			if (GBrowserIsCompatible()) {

				var hash = window.location.hash;

				map = new GMap2(document.getElementById("mapBox"));
				map.setMapType(G_NORMAL_MAP);
				
				centerPoint = new GLatLng(centerLat, centerLong);
				
				if ($("body").data("mapStart")) {
					zoomLevel = ($('body').data("mapStart").mapZoom)-1;
				} else {
					zoomLevel = 10;
				};

				
				map.setCenter(centerPoint, zoomLevel);
				var bounds = new GLatLngBounds();
				map.setUIToDefault();
				map.disableScrollWheelZoom();
				
				GDownloadUrl(mapData, function(doc) {
					var xmlDoc = GXml.parse(doc);
					var markers = xmlDoc.documentElement.getElementsByTagName("marker");

					for (var i = 0; i < markers.length; i++) {

						var lat = parseFloat(markers[i].getAttribute("lat"));
						var lng = parseFloat(markers[i].getAttribute("lng"));
						var point = new GLatLng(lat,lng);
						bounds.extend(point);

						var locid = markers[i].getAttribute("locid");
						var label = markers[i].getAttribute("label").toString();
						var img = markers[i].getAttribute("img");
						var desc = markers[i].getAttribute("desc");
						var attr = markers[i].getAttribute("attr");
						var url = markers[i].getAttribute("url");
						var votes = markers[i].getAttribute("votes");
						var userid = markers[i].getAttribute("userid");
						
						var imgTag = "<div class='tipContainer'><img height='48' src='"+img+"' alt='' /></div>";
						var marker = createMarker(locid,point,label,img,desc,attr,url,votes,userid);
						var tooltip = new Tooltip(marker, imgTag, 8);
						marker.tooltip=tooltip;
						map.addOverlay(marker);	
						map.addOverlay(tooltip);	 
						
						GEvent.addListener(marker,"mouseover", function() {
							this.tooltip.show();
						});
						
						GEvent.addListener(marker,"mouseout", function() {
							this.tooltip.hide();
						});
					};
					
					if(map.getBoundsZoomLevel(bounds)<=9){
						map.setCenter(centerPoint, 10);
					} else {
						map.setZoom(map.getBoundsZoomLevel(bounds)-1);
						map.setCenter(bounds.getCenter());
					};
					
					
					
					$('body').data("mapStart",{mapZoom:map.getBoundsZoomLevel(bounds),mapCenter:bounds.getCenter()});
				});
			}
		};

		createMarker = function(locid,point,label,img,desc,attr,url,votes,userid) {
			var marker = new GMarker(point, {icon:myIcons['pin']});
			GEvent.addListener(marker, "click", function() {
				if(window.pageTracker) {pageTracker._trackPageview("postcard-"+locid)};
				postcardd(locid,label,img,desc,attr,url,votes,userid);
			});
			return marker;
		};

		pointSwap = function(mapData) {
			map.clearOverlays;
			populateMap(mapData);
		};
		
		getQs = function(name) {
			name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
			var regexS = "[\\?&]"+name+"=([^&#]*)";
			var regex = new RegExp(regexS);
			var results = regex.exec(window.location.href);
			if(results == null) {
				return "";
			} else {
				return results[1];
			};
		};

		postcardd = function(locid,label,img,desc,attr,url,votes,userid) {
			window.location.hash = "#"+locid;
			$('#votes').removeAttr('style');
			var pc = $('#postcard');
			var pccontent = $('#postcard .dyntext');
			pccontent.empty();

			var pchtml = "<h2>"+label+"</h2>";
			pchtml += "<img src='"+img+"' alt='stuff' />";
			pchtml += "<p class='desc'>"+desc+"</p>";
			pchtml += "<p class='attr'>" + smultronXml.searchText + " <br /><a href='#' id='seeAllBy'>" + attr + "</a></p>";
			pccontent.append(pchtml);
			$("<img src='/Templates/Public/Images/UI/Core/googleMaps/clip.png' class='clip' alt='' />").insertAfter('#closePostcard');
			
			$('#seeAllBy').click(function() {
				pointSwap(smultronXml.search + userid);
				$('#postcard').fadeOut(400, function() {
					GEvent.clearListeners(map,"click");
				});
				window.location.hash = "#map";
				$('.clip').remove();
				return false;
			});
			
			$('#anmal').text('Anmäl vykortet!').css('cursor', 'pointer');
			
			if (jQuery.inArray(locid,pointsArray)!= -1) {
				$('#votes').addClass('voted');
			}
			
			if (jQuery.inArray(locid,tempArray)!= -1) {
				$('#votes').attr('rel', locid).text(parseInt(votes)+1);
			} else {
				$('#votes').attr('rel', locid).text(votes);				
			}

			$('#fb a').attr('href', 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent("http://" + document.location.hostname + url) + '&t=' + encodeURIComponent(label) + '');
			$('link#fbLink').attr('href', 'http://' + document.location.hostname + img);
			$('#twitter a').attr({'href': 'http://twitter.com/home?status=' + smultronXml.tweet.replace("#url#", "http://" + document.location.hostname + url),"target":"_blank"});
			
			$('#mail a').click(function() {
				//$('#sendBox').show();
				$('#tipsa').show().addClass('sendMail');
				return false;
			});
			
			$('#direct a').attr('href', 'http://'+document.location.hostname+url).text("goteborg.com"+url);
			
			$('.emailFormButton').click(function() {
				var emailTo = encodeURIComponent($('.emailFormTo_smult').val());
				var emailName = encodeURIComponent($('.emailFormName_smult').val());
				var emailPost = smultronXml.mail.replace("{0}",emailName).replace("{1}",emailTo).replace("{2}",locid);
				
				$.get(emailPost,
				 function(){
			   		$('#tipsa, #modalShade').fadeOut();
				});

			});
			
			$('.modal_header .close').click(function() {
				$('#tipsa, #modalShade').hide();
				return false;
			});
			
			$('#gilla').val($('#votes').text());
			
			$('#anmal').one('click',function() {
				var abusePost = smultronXml.abuse.replace("{0}",locid);
				$.post(abusePost);
				$(this).text("Din anmälan är skickad").animate({"color": "#ffc345"}, 300, function() {
				  $(this).animate({"color": "#C1C0B7"},600);
				}).css('cursor', 'default');
			}).bind('click', function() {
				return false;
			});;

			pc.fadeIn(400, function() {
				if ($.browser.msie) {
					this.style.removeAttribute('filter');
				};
				GEvent.addListener(map,"click",function() {
					$('#postcard').fadeOut(400, function() {
						$('#votes').removeClass('voted');
						GEvent.clearListeners(map,"click");
						window.location.hash = "#map";
						$('.clip').remove();
					});
				});
			});
		};		
		
		$(document).ready(function(){
			init();
			var ext;
			if ($.browser.msie) {
			    ext = ".gif";
			 } else {
				ext = ".png";
			};

			$('.smultronPage #postcard').css('background', 'transparent url(/Templates/Public/Images/UI/Core/googleMaps/postcard_bg'+ext+') left top no-repeat'); 


		});

		$(window).unload(function(){
			GUnload();
		});
		
	}
	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* START PAGE REDESIGN SUMMER 2O1O
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

	function spRedesign() {


/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */;(function($){var helper={},current,title,tID,IE=$.browser.msie&&/MSIE\s(5\.5|6\.)/.test(navigator.userAgent),track=false;$.tooltip={blocked:false,defaults:{delay:200,fade:false,showURL:true,extraClass:"",top:15,left:15,id:"tooltip"},block:function(){$.tooltip.blocked=!$.tooltip.blocked;}};$.fn.extend({tooltip:function(settings){settings=$.extend({},$.tooltip.defaults,settings);createHelper(settings);return this.each(function(){$.data(this,"tooltip",settings);this.tOpacity=helper.parent.css("opacity");this.tooltipText=this.title;$(this).removeAttr("title");this.alt="";}).mouseover(save).mouseout(hide).click(hide);},fixPNG:IE?function(){return this.each(function(){var image=$(this).css('backgroundImage');if(image.match(/^url\(["']?(.*\.png)["']?\)$/i)){image=RegExp.$1;$(this).css({'backgroundImage':'none','filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+image+"')"}).each(function(){var position=$(this).css('position');if(position!='absolute'&&position!='relative')$(this).css('position','relative');});}});}:function(){return this;},unfixPNG:IE?function(){return this.each(function(){$(this).css({'filter':'',backgroundImage:''});});}:function(){return this;},hideWhenEmpty:function(){return this.each(function(){$(this)[$(this).html()?"show":"hide"]();});},url:function(){return this.attr('href')||this.attr('src');}});function createHelper(settings){if(helper.parent)return;helper.parent=$('<div id="'+settings.id+'"><h3></h3><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();if($.fn.bgiframe)helper.parent.bgiframe();helper.title=$('h3',helper.parent);helper.body=$('div.body',helper.parent);helper.url=$('div.url',helper.parent);}function settings(element){return $.data(element,"tooltip");}function handle(event){if(settings(this).delay)tID=setTimeout(show,settings(this).delay);else
show();track=!!settings(this).track;$(document.body).bind('mousemove',update);update(event);}function save(){if($.tooltip.blocked||this==current||(!this.tooltipText&&!settings(this).bodyHandler))return;current=this;title=this.tooltipText;if(settings(this).bodyHandler){helper.title.hide();var bodyContent=settings(this).bodyHandler.call(this);if(bodyContent.nodeType||bodyContent.jquery){helper.body.empty().append(bodyContent)}else{helper.body.html(bodyContent);}helper.body.show();}else if(settings(this).showBody){var parts=title.split(settings(this).showBody);helper.title.html(parts.shift()).show();helper.body.empty();for(var i=0,part;(part=parts[i]);i++){if(i>0)helper.body.append("<br/>");helper.body.append(part);}helper.body.hideWhenEmpty();}else{helper.title.html(title).show();helper.body.hide();}if(settings(this).showURL&&$(this).url())helper.url.html($(this).url().replace('http://','')).show();else
helper.url.hide();helper.parent.addClass(settings(this).extraClass);if(settings(this).fixPNG)helper.parent.fixPNG();handle.apply(this,arguments);}function show(){tID=null;if((!IE||!$.fn.bgiframe)&&settings(current).fade){if(helper.parent.is(":animated"))helper.parent.stop().show().fadeTo(settings(current).fade,current.tOpacity);else
helper.parent.is(':visible')?helper.parent.fadeTo(settings(current).fade,current.tOpacity):helper.parent.fadeIn(settings(current).fade);}else{helper.parent.show();}update();}function update(event){if($.tooltip.blocked)return;if(event&&event.target.tagName=="OPTION"){return;}if(!track&&helper.parent.is(":visible")){$(document.body).unbind('mousemove',update)}if(current==null){$(document.body).unbind('mousemove',update);return;}helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");var left=helper.parent[0].offsetLeft;var top=helper.parent[0].offsetTop;if(event){left=event.pageX+settings(current).left;top=event.pageY+settings(current).top;var right='auto';if(settings(current).positionLeft){right=$(window).width()-left;left='auto';}helper.parent.css({left:left,right:right,top:top});}var v=viewport(),h=helper.parent[0];if(v.x+v.cx<h.offsetLeft+h.offsetWidth){left-=h.offsetWidth+20+settings(current).left;helper.parent.css({left:left+'px'}).addClass("viewport-right");}if(v.y+v.cy<h.offsetTop+h.offsetHeight){top-=h.offsetHeight+20+settings(current).top;helper.parent.css({top:top+'px'}).addClass("viewport-bottom");}}function viewport(){return{x:$(window).scrollLeft(),y:$(window).scrollTop(),cx:$(window).width(),cy:$(window).height()};}function hide(event){if($.tooltip.blocked)return;if(tID)clearTimeout(tID);current=null;var tsettings=settings(this);function complete(){helper.parent.removeClass(tsettings.extraClass).hide().css("opacity","");}if((!IE||!$.fn.bgiframe)&&tsettings.fade){if(helper.parent.is(':animated'))helper.parent.stop().fadeTo(tsettings.fade,0,complete);else
helper.parent.stop().fadeOut(tsettings.fade,complete);}else
complete();if(settings(this).fixPNG)helper.parent.unfixPNG();}})(jQuery);
	
/* function to set all selected items to the same height, rewritten as jQuery plugin */
(function(a){a.fn.equalHeights=function(c,b){tallest=(c)?c:0;this.each(function(){if(a(this).height()>tallest){tallest=a(this).height();}});if((b)&&tallest>b){tallest=b;}return this.each(function(){a(this).height(tallest).css("overflow","visible");});};})(jQuery);

/* infinite carousel function, rewritten as jQuery plugin */
(function($) {
	$.fn.carousel = function(previous, next, options){
		$(this).show().wrap('<div class="carouselWrapper"></div>');

		var listItems = $(this).children().children();
		
		//joolss = (window.console) ? console.log('10005 listItems.length: '+ listItems.length) : null;
		
		
		if(listItems.length>5) {
			
			var thisId = $(this).attr("id"),
			prevB = "<a href='#' class='carouselPrev'></a>",
			nextB = "<a href='#' class='carouselNext'></a>";
	
			$(this).before(prevB).after(nextB);
			$('.carouselPrev, .carouselNext').hover(function() {
				$(this).css('opacity', 1); 
			}, function() {
				$(this).css('opacity', .3);
			});
	
			var sliderList = $(this).children()[0];
				
			if (sliderList) {
				
				var increment = $(sliderList).children().outerWidth("true"),
				elmnts = $(sliderList).children(),
				numElmts = elmnts.length,
				sizeFirstElmnt = increment,
				shownInViewport = Math.round($(this).width() / sizeFirstElmnt),
				firstElementOnViewPort = 1,
				isAnimating = false;
		
				for (i = 0; i < shownInViewport; i++) {
					$(sliderList).css('width',(numElmts+shownInViewport)*increment + "px");
					//joolss = (window.console) ? console.log(sliderList) : null;
					//joolss = (window.console) ? console.log(elmnts[i]) : null;
					//return true // BREAKPOINT!
					$(elmnts[i]).clone().appendTo($(sliderList));
					//$(sliderList).append($(elmnts[i]).clone());
				}
				
		
				$(this).prev("a.carouselPrev").click(function(event){
					if (!isAnimating) {
						if (firstElementOnViewPort == 1) {
							$(sliderList).css('left', "-" + numElmts * sizeFirstElmnt + "px");
							firstElementOnViewPort = numElmts;
						}
						else {
							firstElementOnViewPort--;
						}
				
						$(sliderList).animate({
							left: "+=" + increment,
							y: 0,
							queue: true
						}, "swing", function(){isAnimating = false;});
						isAnimating = true;
					}
					return false;
				});
		
				$(this).next("a.carouselNext").click(function(event){
					if (!isAnimating) {
						if (firstElementOnViewPort > numElmts) {
							firstElementOnViewPort = 2;
							$(sliderList).css('left', "0px");
						}
						else {
							firstElementOnViewPort++;
						}
						$(sliderList).animate({
							left: "-=" + increment,
							y: 0,
							queue: true
						}, "swing", function(){isAnimating = false;});
						isAnimating = true;
					}
					return false;
				});
			}
		} else {
			$(this).addClass('carouselStatic');
			
			switch(listItems.length) {
				case 1:
					$(this).children('ul').children('li').css('padding','0 295px');
					break;
				case 2:
					$(this).children('ul').children('li').css('padding','0 122px');
					break;
				case 3:
					$(this).children('ul').children('li').css('padding','0 65px');
					break;
				case 4:
					$(this).children('ul').children('li').css('padding','0 36px');
					break;
				case 5: 
					$(this).children('ul').children('li').css('padding','0 19px');
					break;
			}
			
		};
		
		
		
		// add "Boka" badge to items with "book" class
		var ext = typeof document.body.style.maxHeight === "undefined" ? "gif" : "png",
			boka = $('<div class="boka"><img src="/Templates/Public/Images/UI/Units/startPageRedesign/carousel/framework/boka.'+ext+'" /></div>');
		$(this).children('ul').children('li.book').append(boka);
		
		$('.carousel li.book').hover(function() {
			$(this).find(".boka").show();
			var relUrl = $(this).children('a').attr("href");
			if (relUrl != undefined) {
				$('.boka').hover(function() {
					$(this).css('cursor', 'pointer');
				}, function() {
					$(this).css('cursor', 'default');
				}).click(function() {
					document.location.href = $(this).prev('a').attr("href");
				});
				return false;
			}
			
		}, function() {
			$(this).find(".boka").hide();
		});
		
		$('.carousel li img').hover(function(e){
			$(this).attr('alt','');
		},function(){});
	};
})(jQuery);



// function to set up the grid structure, written as a jQuery plugin
(function($) {
	$.fn.gridLove = function() {
		$.each($(this).children('li'), function(index, val) {			
			
			var url = $(val).children('a').attr('href');
			var title = $(val).children('img').attr("title");
			var currentImg = $(this).children('img');
			
			if (title != "") {
				currentImg.before('<div class="imgTitleWrap"><div class="imgTitle"><a href="'+url+'">'+title+'</a></div></div>');
				var imgTitle = $(this).find('.imgTitle');

				if ($(this).hasClass('full') || $(this).hasClass('threequarter')) {
					imgTitle.width(currentImg.width());
				}
				
				imgTitle.height(currentImg.height());
				
				currentImg.attr('title', '');
			}
			
			
			
			if ($(this).hasClass('gridElemFreeStyle') === false) {
				$(this).hover(function() {
					$(this).addClass('hover').find('.imgTitle').show();
				}, function() {
					$(".imgTitle").hide();
					$(this).removeClass('hover');
				}).click(function() {
					if (url !== undefined) {
						document.location.href=url;
					} else {
						return false;
					}
				});
			}
		});
		$.each($(".pageGrid"),function(i,v) {
			//$(v).children('li').equalHeights();
		});
	};
})(jQuery);
		
		
		
		init = function() {
			// CROSSFADE GALLERY DISPLAY
			$('.gallery *').show();
			$.each($(".gallery"),function(){
				$(this).children("li").equalHeights();
				$(this).height($(this).children(":first").height());
				if (!($(this).attr("rel"))) {
					var speed = 4000;
				} else {
					var speed = $(this).attr("rel")*1000;
				};
				$(this).cycle({timeout:speed});
			});
			
			$.each($(".carousel"), function(index, val) {
				//joolss = (window.console) ? console.log('removed the carousel script. temp for debug //jolsson') : null;
				$(this).carousel('.carouselPrev', '.carouselNext');
			});  
			
			$('.carousel li[title]').each(function(){
				$(this).tooltip({
					track: true,
					delay: 0,
					showURL: false,
					showBody: " - ",
					extraClass: "pretty",
					fixPNG: true,
					opacity: 1,
					left: -26,
					top: -50,
					fade: 0
				});
				
				$(this).attr('title','');
			});
			
			$('.carousel li a[title]').attr('title','');
			
			
			// This is entirely to fix a stupid display bug in IE 7. Bah. 
			$('.carouselNext').hover();
			
			$(window).load(function() {
				$('.pageGrid').gridLove();		
			});
			
		}
		
		$(document).ready(function() {
			init();			
		});
		
	}

	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* PUBLIC METHODS
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	
	
	
	
	
	
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	* ENSURE SINGLETON PATTERN
	* DO NOT MODIFY!!!
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	if (!self.instance) {constructor(); self.instance = this; self.instance.numInstances = 1;} else	{self.instance.numInstances++;	delete this; }
	return self.instance;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*	FRAMEWORK EVENT HANDLERS
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function frameworkEventHandlers ()
{
	
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*	JQUERY CONSTRUCTOR
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*	$.daddy.browser();
*
*	@browser	IE8 | IE7 | IE6 (Default) | FF | S
*	
*	Retuns true or false if the specified browser is present.
*
*	Example:
*
*	($.daddy.browser({browser: 'IE7'}) ? ... : ... ;
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
jQuery.daddy =
{
	browser : function (options)
	{
		var settings = $.extend({
			browser: 'IE6'
		},options||{});

		switch (settings.browser)
			{
				case 'IE8' 	: return ($.browser.msie && $.browser.version >= 8) ? true : false; break;
				case 'IE7' 	: return ($.browser.msie && $.browser.version >= 7 && $.browser.version < 8) ? true : false; break;
				case 'IE6' 	: return ($.browser.msie && $.browser.version >= 6 && $.browser.version < 7) ? true : false; break;
				case 'IE5' 	: return ($.browser.msie && $.browser.version >= 5 && $.browser.version < 6) ? false : false; break;
				case 'IE7-' 	: return ($.browser.msie && $.browser.version <= 7 && $.browser.version < 8) ? true : false; break;
				case 'FF' 	: return ($.browser.mozilla) ? true : false; break;
				case 'S' 	: return ($.browser.safari) ? true : false; break;
				default 	: alert("$.daddy.browser error"); break;
			}
	}
};



$(function ()
	{
		gbg = new GBG();
	}
);




	var travelbox = {};
	
	travelbox.SetDiscountCard = function(hasdiscountcard) {
        $.ajax({
            url: '~/Templates/Public/Handlers/TravelCartAdd.ashx',
            type: 'POST',
            data: { hasdiscountcard: hasdiscountcard },
            contextType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
                if (data.success == '1') {
                    //alert(data.productname +' '+ '<%= Translate("/travelcart/addedproduct") %>');
                    if (document.getElementById('discountCardChk').checked) {
                        //alert('<%= Translate("/travelcart/discountcardadded") %>');
					} else {
                        //alert('<%= Translate("/travelcart/discountcardremoved") %>');
                    //Refresh travelcart
                    travelbox.RenderTravelCart();
					}
                } else {
                    //alert('<%= Translate("/travelcart/addproducterror") %>');
				}
            }
        });
    }

	// onclick="travelbox.DeleteRow(this)"

    travelbox.DeleteRow = function(me) {
		var productType = $('input.productType',me).val();
		var productId = $('input.productId',me).val();
		var templateId = $('input.templateId',me).val();
		
		//alert(productType + ' / ' + productId);
		
        $.ajax({
            url: '~/Templates/Public/Handlers/TravelCartDelete.ashx',
            type: 'POST',
           	data: 'productType='+productType+'&productId='+productId+'&templateId='+templateId,
            contextType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
				//alert('data.success='+data.success);
                if (data.success == '1') {
					//alert('success');
					window.location.reload();
					
                    //uppdatera travelcart NY FUNKTION
                   // travelbox.RenderTravelCart();
                } else {
                    //alert('<%= Translate("/travelcart/addproducterror") %>');
				}
			}
        });
    }
    
    travelbox.ToggleTravelRows = function(rowType, rowListDivId, liRowId) {
    
        var rowDiv = document.getElementById(rowListDivId);

        if ($("." + liRowId).hasClass("selected")) {

            $("." + liRowId).removeClass("selected");

        }

        if (rowDiv.style.display == 'none') {
        
            $.ajax({
                url: '~/Templates/Public/Handlers/TravelCartGet.ashx',
                type: 'POST',
                data: { rowtypeid: rowType },
                contextType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(data) {

                    $("." + liRowId).addClass("selected");

                    if (data.travelrows.length > 0) {
                        rowDiv.innerHTML = '';
                        rowDiv.style.display = 'block';
                        for (var i = 0; i < data.travelrows.length; i++) {
                            rowDiv.innerHTML += "<li><a href=\"#\"><tt></tt>" + data.travelrows[i].name + "</a></li>";
                            //$('ul', rowDiv).append("<li><a href=\"#\"><tt></tt>" + data.travelrows[i].name + "</a></li>");
                        }
                    }
                }
            });
        }
        else
            rowDiv.style.display = 'none';
    }

    travelbox.RenderTravelCart = function() {
    
        var travelCartDiv = document.getElementById('TravelCart');

        $.ajax({
            url: '~/Templates/Public/Handlers/TravelCartGet.ashx',
            type: 'POST',
            data: {},
            contextType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
          
                    //travelCartDiv.innerHTML += "<div class='header'>Mitt besök</div>";
                    var rowType = '';
                    var rowHTMLbuffer = '<ul>'
                    for (var i = 0; i < data.rowtypes.length; i++) {
                        var rowDivId = "rowDiv_" + i;
                        var liRowId = "liRowDiv_" + i;
                        rowHTMLbuffer += "<li class=" + liRowId + " onclick=\"travelbox.ToggleTravelRows('" + data.rowtypes[i].rowtypeid + "','" + rowDivId + "','" + liRowId + "');\"><a href=\"#\">" + data.rowtypes[i].typename + "<span class=\"amount\">(" + data.rowtypes[i].sum + ")</span><span class=\"toolTipContent\">asdsd</span></a><ul style=\"display:none\" id=\"" + rowDivId + "\"><li></li></ul> ";
                    }
                    document.getElementById('discountCardChk').checked = data.discountcard;
                    rowHTMLbuffer += "</ul>";
                    travelCartDiv.innerHTML += rowHTMLbuffer;
             
            }
        });
    }
		
		
	
		function GetNearbyItems(categoryId){
			var nearbyItemsDiv = document.getElementById("nearbyItems");
			var innerHtml = '';
			
			$("#loading-items").show();
			
			if (window.PageId != undefined) {
				$.ajax({
					url: '/Templates/Public/Handlers/NearbyGet.ashx',
					type: 'POST',
					data: {
						pageid: PageId,
						productid: ProductId,
						templateid: TemplateId,
						categoryid: categoryId,
						lang: lang
					},
					contextType: 'application/json; charset=utf-8',
					dataType: 'json',
					success: function(data){
					
						for (var i = 0; i < data.length; i++) {
							var cssClass;
							if ((i + 1) % 2 == 0) 
								cssClass = 'rc_box grayOutlineShade item right';
							else 
								cssClass = 'rc_box grayOutlineShade item left';
							var categories = "";
							
							for (var j = 0; j < data[i].Categories.length; j++) {
								if (j > 0) 
									categories += ", ";
								categories += data[i].Categories[j].Name;
							}
							innerHtml += "<div class='" + cssClass + "'>";
							innerHtml += "<span class='t'><span class='n'></span><span class='ne'></span><span class='nw'></span></span><span class='m'><span class='w'></span>";
							innerHtml += "<span class='boxContent'><span class='innerS'>";
							innerHtml += "<span class='itemHeader'>" + data[i].Name + "</span>";
							innerHtml += "<span class='staticRating value" + data[i].Props.Rating + "'></span>";
							innerHtml += "<span class='itemCategory'>" + categories + "</span>";
							innerHtml += "<a class='itemReadMore' href='" + data[i].Props.Url + "'>Läs mer</a>";
							//		innerHtml += "<a class='itemAddToGuide' href='#' onClick=\"AddProductToTravelCart('"+ data[i].Id +"','"+ data[i].TemplateId +"')\">Lägg till i reseplaneraren</a>";
							innerHtml += "<span class='clear'></span>";
							innerHtml += "</span></span>";
							innerHtml += "<span class='e'></span></span><span class='b'><span class='s'></span><span class='se'></span><span class='sw'></span></span></div>";
							
							if ((i + 1) % 2 == 0) 
								innerHtml += "<div class='clear'></div>";
						}
						nearbyItemsDiv.innerHTML = innerHtml;
					},
					complete: function(){
						$("#loading-items").fadeOut("fast");
					}
				});
			}
		}



$('.shareMistelButton').bind('click', sendMistelMail);

function sendMistelMail() {

    var ser = $('form').find('.shareMistelContent :input').serialize();
    ser += "&share_url=" + window.location.href;

    $.ajax({

        type: "POST",
        url: "/Templates/Public/Campaigns/Mistel2009/Handlers/MistelTipsHandler.ashx",
        dataType: 'json',
        data: ser,
        success: function(data) {
            if (!data.name)
                $('.shareMistelContent .shareMistel_name').parents('.inputText').addClass('error');
            else
                $('.shareMistelContent .shareMistel_name').parents('.inputText').removeClass('error');

            if (!data.email)
                $('.shareMistelContent .shareMistel_email').parents('.inputText').addClass('error');
            else
                $('.shareMistelContent .shareMistel_email').parents('.inputText').removeClass('error');


            if (data.valid) {
                $('.shareMistelContent .shareMistel_email').parents('.inputText').removeClass('error');
                $('.shareMistelContent .shareMistel_name').parents('.inputText').removeClass('error');

                var h = $('.shareMistelContent').height();
                $('.shareMistelContent div:first').fadeOut(300, function() { $('.shareMistel_message').height(h).fadeIn(300, function() { var interval = window.setTimeout(function() { window.clearTimeout(interval); $('.shareMistel_message').fadeOut(300, function() { $('.shareMistelContent div:first').fadeIn(300); }); }, 5000); }); });
           
            
             //   $('.shareMistel_message').height(h).fadeIn(300);
             //   $('.shareMistelContent div:first').fadeOut(300);
 
               // $('.shareMistel_message').height(h).fadeIn(300);
               // $('.shareMistelContent div:first').fadeOut(300);
            }

        }
    });

    return false;

}
