$(document).ready(function() {
	// Main menu buttons
	$("#main-li-1").bind('click', function(e){document.location = '/' + $("#main-menu-1").attr('href');});
	$("#main-li-2").bind('click', function(e){document.location = '/' + $("#main-menu-2").attr('href');});
	$("#main-li-3").bind('click', function(e){document.location = '/' + $("#main-menu-3").attr('href');});
	$("#main-li-4").bind('click', function(e){document.location = '/' + $("#main-menu-4").attr('href');});
	$("#main-li-5").bind('click', function(e){document.location = '/' + $("#main-menu-5").attr('href');});
	
	// Breadcrumb Tooltips
	$("#breadcrumbs li a, #top-left-controls a img[alt]").tipsy({gravity: $.fn.tipsy.autoNS, fade: false, title: 'alt', fallback: "Gå direkt till "});
	
	// Home page Accordion
	if(document.getElementById("accordion")){
		$("#accordion").accordion({fillSpace: true});
		$("#accordion").css({visibility: 'visible'});
	}
	
	// Home page Boden on the Map
	if(document.getElementById("home-page-map")){
		
		// skapa kartan
		var home_page_map = new GMap2(document.getElementById("home-page-map"),{size:new GSize(405,234)});
		
		// setCenter till boden
		bodenPoint = new GLatLng('65.82833099365234', '21.70655059814453');
		home_page_map.setCenter(bodenPoint, 8);
	}
	
	// Product detail Map
	if(document.getElementById("product-detail-map")){
		// skapa kartan
		var productDetailMap = new GMap2(document.getElementById("product-detail-map"),{size:new GSize(268,250)});
		
		
		// lägga till controllers
		productDetailMap.addControl(new GLargeMapControl3D());
		productDetailMap.addControl(new GMapTypeControl()); 
		productDetailMap.enableDoubleClickZoom();
		
		// setCenter till produkten
		productPoint = new GLatLng($('#product-detail-lat').attr('value'), $('#product-detail-long').attr('value'));
		productDetailMap.setCenter(productPoint, 7);
		
		// plotta ut produkten
		productDetailMarker = new GMarker(productPoint);
		productDetailMap.addOverlay(productDetailMarker);
		
		// visa
		$("#product-detail-map").css({visibility: 'visible'});
	}
	
	// Product Detail Image Gallery
	if(document.getElementById("product-detail-gallery-container")){
		$('ul.media_gallery_list').galleria({
			history   : false, // activates the history object for bookmarking, back-button etc.
			clickNext : true, // helper for making the image clickable
			insert    : '#media-gallery-display', // the containing selector for our main image
			onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
				
				// fade in the image & caption
				image.css('display','none').fadeIn(1000);
				caption.css('display','none').fadeIn(1000);
				
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				
				// fade out inactive thumbnail
				_li.siblings().children('img.selected').fadeTo(500,0.5);
				
				// fade in active thumbnail
				thumb.fadeTo('fast',1).addClass('selected');
				
				// add a title for the clickable image
				image.attr('title','Next image >>');
			},
			onThumb : function(thumb) { // thumbnail effects goes here
				
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				
				// if thumbnail is active, fade all the way.
				var _fadeTo = _li.is('.active') ? '1' : '0.5';
				
				// fade in the thumbnail when finnished loading
				thumb.css({display:'none',opacity:_fadeTo}).fadeIn(500);
				
				// hover effects
				thumb.hover(
					function() { thumb.fadeTo('fast',1); },
					function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
				)
			}
		});
		
		// visa
		$("#product-detail-gallery-container").css({visibility: 'visible'});
	}
	
	if(document.getElementById("comment-dialog")){
		$("#comment-dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 420,
			width: 420,
			modal: true,
			buttons: {
				'Kommentera': function() {
					$('#comment-form').submit();
				},
				'Avbryt': function() {
					$(this).dialog('close');
				}
			},
			close: function() {
			}
		});
	}
	
	// Make comment button
	if(document.getElementById("make-comment")){
		$('#make-comment').bind('click', function() {
			$('#comment-dialog').dialog('open');
			return false;
		});
	}
	
	// Facebook share
	if(document.getElementById("facebook-share")){
		url = 'http://www.facebook.com/sharer.php?u=';
		url += window.location;
		url += '&t=';
		url += document.title;
		$('#facebook-share').attr('href', url);
	}
	
	if(document.getElementById("start-date")){
		$.datepicker.setDefaults($.datepicker.regional['sv']);

		var dates = $('#start-date, #stop-date').datepicker({
			dateFormat: "yy-mm-dd",
			showOtherMonths: true,
			onSelect: function(selectedDate) {
				var option = this.id == "start-date" ? "minDate" : "maxDate";
				var instance = $(this).data("datepicker");
				var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
				dates.not(this).datepicker("option", option, date);
			}
		});
	}

	if (document.getElementById('monitor')) {
		$('#monitor ul').show().cycle();
	}

	// Move me to template..?
	$('#breadcrumbs').after('<div id="product-list-gmap" class="container_10" style="width: 960px; height: 375px; display: none;"></div>');
	var gmap = new GM($('#product-list-gmap'), [960, 375]);

	$('#map-control a').click(function(event) {
		event.preventDefault();

		gmap.load();

		if ($(this).hasClass('show')) {
			gmap.show();
		} else {
			gmap.hide();
		}

		$(this).parent().find('.toggle').toggle();
	});
	
	$('a.map').click(function(event) {
		event.preventDefault();

		var productId = event.target.className.match(/product_([0-9]+)/i);
		var parentCategoryId = event.target.className.match(/category_parent_([0-9]+)/i);
		var categoryId = event.target.className.match(/category_([0-9]+)/i);

		if (productId != undefined && productId[1]) {
			productId = productId[1];

			if (categoryId != undefined && categoryId[1]) {
				categoryId = categoryId[1];
			} else if (parentCategoryId != undefined && parentCategoryId[1]) {
				categoryId = parentCategoryId[1];
			} else {
				categoryId = 0;
			}

			gmap.load();
			gmap.openMarker(productId);
			gmap.show();

			$('#map-control a.hide').show();
			$('#map-control a.show').hide();
		}
	});

});

function GM(element, size) {
	if (size == undefined || size.length != 2) {
		return false;
	}

	this.element = element;
	this.size = size;
	this.markers = [];
	this.isVisible = false;
	this.isLoaded = false;
}

GM.prototype.load = function() {
	if (this.isLoaded) {
		return;
	}

	this.defaultPosition = new GLatLng('65.82833099365234', '21.70655059814453');
	this.bounds = new GLatLngBounds();
	this.map = new GMap2(this.element.get()[0], {
		size: new GSize(this.size[0], this.size[1])
	});
	this.map.setCenter(this.defaultPosition, 8);
	this.map.setUIToDefault();

	if (fs_tellus_mapItems) {
		// alert(0);
		this.createMarkers(fs_tellus_mapItems);
	}

	this.isLoaded = true;
}

GM.prototype.show = function() {
	this.element.slideDown();
	this.isVisible = true;
	$('html, body').animate({scrollTop: $("#menu").offset().top}, 'fast');
}

GM.prototype.hide = function() {
	this.element.slideUp();
	this.isVisible = false;
}

GM.prototype.getMarker = function(point) {
	for (var i = 0, l = this.markers.length; i < l; i++) {
		if (this.markers[i]['marker'].equals(point)) {
			return this.markers[i];
		}
	}

	return null;
}

GM.prototype.openMarker = function(id) {
	for (var i = 0, l = this.markers.length; i < l; i++) {
		if (this.markers[i]['data']['id'] == id) {
			GEvent.trigger(this.markers[i]['marker'], 'click');
		}
	}

	return null;
}

GM.prototype.createMarker = function(data) {
	var point = new GLatLng(data['lat'], data['lng']);
	// var marker = this.getMarker(point);

	// if (marker) {
	// 	return null; 
	// }

	marker = new GMarker(point);

	GEvent.addListener(marker, 'click', $.proxy(function() {
		this.map.panTo(point);
		this.map.openInfoWindowHtml(point, data['text']);
	}, this));

	var object = {'marker': marker, 'data': data};

	this.markers.push(object);

	return marker;
}

GM.prototype.createMarkers = function(data) {
	for (var i = 0, l = data.length; i < l; i++) {
		var marker = this.createMarker(data[i]);

		if (marker) {
			this.bounds.extend(marker.getLatLng());
			this.map.addOverlay(marker);
		}
	}
}

// GM.prototype.createMarker = function(point, text) {
// 	var marker = new GMarker(point);

// 	GEvent.addListener(marker, 'click', $.proxy(function() {
// 		this.map.panTo(point);
// 		this.map.openInfoWindowHtml(point, text);
// 	}, this));

// 	return marker;
// }

// // extension
// GM.prototype.createMarkersFromJSON = function(objects) {
// 	for (var i = 0, l = objects.length; i < l; i++) {
// 		var object = objects[i];
// 		var point = new GLatLng(object['lat'], object['lng']);
// 		var marker = this.createMarker(point, object['text']);

// 		if (object['id'] == this.activeObjectId) {
// 			this.map.openInfoWindowHtml(point, object['text']);
// 			this.map.panTo(point, 8);
// 		}

// 		this.bounds.extend(point);
// 		this.map.addOverlay(marker);
// 	}
// }

