var Miljopakken = {
	map: {
		layers: { 'l1': [], 'l2': [], 'l3': [], 'l4': [], 'l5': [] },
		initialize: function() {
			var self = this;

			// Assign change even to checkboxes
			$('.rside INPUT#m_completed, .rside INPUT#m_ongoing, .rside INPUT#m_planned').bind('change', function() {
				self.toggleOverlay();
			});

			// Setup map
			var latlng = new Array();
			latlng[0] = '63.406761185054';
			latlng[1] = '10.488028320312509';
			if (this.mapCenter) latlng = this.mapCenter.split(',');
			
			this.map = new google.maps.Map(document.getElementById("map_canvas"), {
				zoom: parseInt(this.mapZoom) || 10,
				center: new google.maps.LatLng(latlng[0], latlng[1]), 
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				streetViewControl: false
			});

			// Setup info tooltip
			this.infoBubble = new InfoBubble({
				arrowPosition: 50,
				borderRadius: 0,
				borderWidth: 0,
				padding: 15
			});


			if ($.cookie("m_kollektiv") == 'false') $('.l2').addClass('noshow').find('SPAN').css('background-position','0px 0px');
			if ($.cookie("m_veg") == 'false') $('.l1').addClass('noshow').find('SPAN').css('background-position','0px -47px');
			if ($.cookie("m_sykkel") == 'false') $('.l5').addClass('noshow').find('SPAN').css('background-position','0px -94px');
			if ($.cookie("m_sikkerhet") == 'false') $('.l3').addClass('noshow').find('SPAN').css('background-position','0px -141px');
			if ($.cookie("m_miljo") == 'false') $('.l4').addClass('noshow').find('SPAN').css('background-position','0px -188px');
			$('#m_completed').attr('checked', $.cookie("m_completed") != 'false');
			$('#m_ongoing').attr('checked', $.cookie("m_ongoing") != 'false');
			$('#m_planned').attr('checked', $.cookie("m_planned") != 'false');
			self.toggleOverlay();
		},

		addMarker: function(layer,fase,lat,lng, title, url, ptitle) {
			var self = this;
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(lat,lng),
				map: this.map,
				title: title,
				fase: fase,
				icon: new google.maps.MarkerImage('/wp-content/themes/miljo/images/poi_l' + layer + '.png',
					new google.maps.Size(21,32),
					null,
					new google.maps.Point(10,27)
				)
			});

			google.maps.event.addListener(marker, 'click', function() {
				self.infoBubble.close();
				self.infoBubble.setContent('<div class="infobubble"><h1>' + title + '</h1><h2>' + ptitle + '</h2><a href="' + url + '">G&aring; til prosjekt</a></div>');
				self.infoBubble.open(self.map, marker);
			});

			this.layers['l'+layer].push(marker);
		},

		addRoad: function(layer, fase, lat, lng, title, url, ptitle) {
			var self = this;
			lats = lat.split(',');
			lngs = lng.split(',');
		
			var latlngs = new google.maps.MVCArray();
			for (i in lats) {
				var newLocation = new google.maps.LatLng(lats[i], lngs[i]);
				latlngs.push(newLocation);
			}

			var poly = new google.maps.Polyline({
				map: this.map,
				fase: fase,
				strokeColor: "#FF0000",
				strokeOpacity: 1.0,
				strokeWeight: 2,
				path: latlngs 
			});

			google.maps.event.addListener(poly, 'click', function(e) {
				self.infoBubble.close();
				self.infoBubble.setContent('<div class="infobubble"><h1>' + title + '</h1><h2>' + ptitle + '</h2><a href="' + url + '">G&aring; til prosjekt</a></div>');
				self.infoBubble.setPosition(e.latLng);
				self.infoBubble.open(self.map);
			});

			this.layers['l'+layer].push(poly);
		},

		addPath: function(layer, fase, path, title) {
			alert('err. this not suppose to happend');
/*			var self = this;
			var poly = new google.maps.Polyline({
				path: path,
				fase: fase,
				strokeColor: "#FFFFFF",
				strokeOpacity: 1.0,
				strokeWeight: 2,
				map: this.map
			});

			google.maps.event.addListener(poly, 'click', function() {
				self.infoBubble.close();
				self.infoBubble.setContent('<h1>' + title + '</h1><a href="' + url + '">G&aring; til prosjekt</a>');
				self.infoBubble.open(self.map, marker);*/
//				self.infoBubble.setContent('<h1>' + title + '</h1><a href="">G&aring; til prosjekt</a>');
//				self.infobubble.setPosition(path[0]);
//				self.infoBubble.open(self.map);
//			});
			
			
//			this.layers['l'+layer].push(path);
		},

		clearOverlay: function() {
			for (i in this.layers) {
				for (j in this.layers[i]) {
					this.layers[i][j].setMap(null);
				}
			}
		},

		showOverlay: function(e,layer) {
			this.clearOverlay();
			for (i in this.layers[layer]) {
				this.layers[layer][i].setMap(this.map);
			}
			$(e).toggleClass('noshow');
			return false;
		},

		toggleOverlay: function(e) {
			if (e) {
				$(e).toggleClass('noshow');
				var bp = $(e).find('SPAN').css('background-position');
				if (bp) {
					if ($(e).hasClass('noshow')) bp = bp.replace('-41px','0px');
					else bp = bp.replace('0%','-41px');
					$(e).find('SPAN').css('background-position', bp);
				} else {
					var bpX = $(e).find('SPAN').css('backgroundPositionX');
					var bpY = $(e).find('SPAN').css('backgroundPositionY');
					if ($(e).hasClass('noshow')) {
						bpX = bpX.replace('-41px', '0px');
					} else {
						bpX = bpX.replace('0px','-41px');
					}
					$(e).find('SPAN').css('background-position', bpX + ' ' + bpY);
				}
			}

			if ($('#map_canvas').hasClass('details_map')) {
				for (i in this.layers) {
					for (j in this.layers[i]) {
						this.layers[i][j].setMap(this.map);
					}
				}
			} else {
				for (i in this.layers) {
					for (j in this.layers[i]) {
						if ($(".map_header A."+i).hasClass('noshow')) {
							this.layers[i][j].setMap(null);
						} else if (
							(this.layers[i][j].fase == 2 && $('.rside INPUT#m_completed').is(':checked')) ||
							(this.layers[i][j].fase == 3 && $('.rside INPUT#m_ongoing').is(':checked')) ||
							(this.layers[i][j].fase == 4 && $('.rside INPUT#m_planned').is(':checked'))
						) {
							if ( (this.layers[i][j].getMap() == null) || (typeof(this.layers[i][j].getMap()) == 'undefined') ) {
								this.layers[i][j].setMap(this.map);							
							}
						} else {
							this.layers[i][j].setMap(null);
						}
					}
				}
			}
			$.cookie("m_completed", $('#m_completed').attr('checked'));
			$.cookie("m_ongoing", $('#m_ongoing').attr('checked'));
			$.cookie("m_planned", $('#m_planned').attr('checked'));
			$.cookie("m_kollektiv", !$('.l2').hasClass('noshow'));
			$.cookie("m_veg", !$('.l1').hasClass('noshow'));
			$.cookie("m_sykkel", !$('.l5').hasClass('noshow'));
			$.cookie("m_sikkerhet", !$('.l3').hasClass('noshow'));
			$.cookie("m_miljo", !$('.l4').hasClass('noshow'));
		}
	},

	init: function() {
		$('.planlegger INPUT[name="from"]').attr('value', 'Fra').bind({
			focus: function() {
				if (this.value=='Fra') this.value = '';
				else this.select();
			},
			blur: function() {
				if (this.value=='') this.value = 'Fra';
			}
		});
		$('.planlegger INPUT[name="to"]').attr('value', 'Til').bind({
			focus: function() {
				if (this.value=='Til') this.value = '';
				else this.select();
			},
			blur: function() {
				if (this.value=='') this.value = 'Til';
			}
		});
		$('#reiseplanlegger').bind('submit', function(event) {
			if ($('.planlegger INPUT[name="from"]').attr('value') == 'Fra') {
				event.preventDefault();
				$('.planlegger INPUT[name="from"]').focus();

			}
			else if ($('.planlegger INPUT[name="to"]').attr('value') == 'Til') {
				$('.planlegger INPUT[name="to"]').focus();
				event.preventDefault();
			}
			
		});



		$('.search INPUT[type="text"]').attr('value', 'S\u00f8k').bind({
			focus: function() {
				if (this.value=='S\u00f8k') this.value = '';
			},
			blur: function() {
				if (this.value=='') this.value ='S\u00f8k';
			}
		});
		var params = this.getUrlVars();
		if (params['s']) {
			$('.search INPUT[type="text"]').attr('value', decodeURIComponent(params['s']));
		}

		if ($('#map_canvas').length) {
			this.map.initialize();
		}

		$(window).scroll(this.onResize).resize(this.onResize);
		this.onResize();

	},

	onResize: function() {
		var fh = $('.footer').position().top+$('.footer').height()+74;

		if ($(window).height() > fh) {
			$('.footer').css('position', 'absolute');
			this.h = $(window).height();
		}
		if (this.h && $(window).height() < this.h) {
			$('.footer').css('position', 'static');
			this.h = null;
		}
	},

	getUrlVars: function() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
	},

	share: function(t) {
		if (t == 'Facebook') {
			w = window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(location.href)+'&t='+encodeURIComponent(document.title), 'sharer', 'toolbar=0,status=0,width=626,height=436');
		} else if (t == 'Twitter') {
			 w = window.open('http://twitter.com?status='+encodeURIComponent(document.title)+' ' + encodeURIComponent(location.href), 'sharer', 'toolbar=0,status=0,width=626,height=436');
		}
		if (w) {
			w.focus();
			return false;
		}
	}
}

String.prototype.unescapeHtml = function () {
	try {
		var temp = document.createElement("div");
	  temp.innerHTML = this;
	  var result = temp.childNodes[0].nodeValue;
	  temp.removeChild(temp.firstChild);
	  return result;
  } catch (err) {}
}

jQuery.fn.center = function () {
  this.css("position","absolute");
  this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
  this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
  return this;
} 

$(document).ready(function() {
	Miljopakken.init();
});
