/*
 * O utilities
 * By Oktavilla (http://oktavilla.se)
 */
var O = function() {
	return {
		debug: function(str) {
			if (str !== null) {
				str = str + "";
				if ($("#debug").length === 0) {
					$("<div id=\"debug\"></div>").appendTo("body");
					$("#debug").css({
						"position": "absolute",
						"right": "0",
						"top": "50px",
						"font": "11px verdana",
						"background": "white",
						"padding": "10px",
						"background": "white",
						"opacity": ".5",
						"filter": "alpha(opacity = 50)",
						"z-index": "99999999"
					});
				}
				$("<div>" + str.replace(">", "&gt;").replace("<", "&lt;") + "</div>").appendTo("#debug");
			}
		},
		getClassNameValue: function(el, prefix) {
			var ret = new RegExp(".*" + prefix + "-(.*?)(?:\\s|$).*").exec(el.className);
			if (ret) {
				return ret[1];
			}
			return null;
		},
		getHash: function(href) {
 	 		return href.substring(href.indexOf("#") + 1);
		},
		scrollTo: function(elm) {
	   		var position = $(elm).offset();
	    	window.scrollTo(0, Math.max(position.top - 20, 0))
		},
		isVisible: function(el) {
			return !(jQuery(el).is(":hidden") || jQuery(el).parents(":hidden").length);;
		},
		numericStrip: function(str) {
			return str.replace(/ |-|\/|\.|\+/gi, "");
		},
   		init: function() {
			/*@cc_on
			@if (@_jscript_version < 5.7)
				try {
					document.execCommand("BackgroundImageCache", false, true);
				} catch (e) {}
			@end @*/

			$.fn.fadeIn = function(speed, callback) {
				this.animate({opacity: "show"}, speed, function() {
					if (!jQuery.support.opacity) {
						this.style.removeAttribute("filter");
					}
					if (callback != undefined) {
						callback.call(this);
					}
				});
			};
			$.fn.fadeOut = function(speed, callback) {
				this.animate({opacity: "hide"}, speed, function() {
					if (!jQuery.support.opacity) {
						this.style.removeAttribute("filter");
					}
					if (callback != undefined) {
						callback.call(this);
					}
				});
			};
		}
	};
}();


/**
 * Form
 * Validates a form
 */
O.form = function() {
	var validateField = function(elm) {
		var field = elm;
		var form = field.form;
		elm = $(elm);
		if (elm.hasClass("required") && (jQuery.trim(field.value) == "")) {
			form.missing.push(field);
			form.hasErrors = true;
		} else if (elm.hasClass("accept-conditions") && !field.checked) {
			form.unaccepted.push(field);
			form.hasErrors = true;
		} else if (elm.hasClass("email") && jQuery.trim(field.value) != "" && field.value.search(/(\w|\.|\-)+\@(\w|\.|\-)+\.[a-z]{2,6}$/)) {
			form.erronous.push(field);
			form.hasErrors = true;
		} else if (elm.hasClass("numeric") && (/\D/).test(O.numericStrip(field.value))) {
			form.erronous.push(field);
			form.hasErrors = true;
		} else {
			elm.removeClass("has-error");
		}
	};
	
	var alertUser = function(form) {
		var hideDuration = 1;
		var alertBox = $(form).find(".alert-box");
		if (alertBox.length == 0) {
			alertBox = $("<div class=\"alert-box\"></div>");
			$(form.firstChild).before(alertBox);
			alertBox.hide();
		} else {
			hideDuration = 250;
		}
		alertBox.slideUp(hideDuration, function() {
			var alertText = "<span class=\"alert-box-heading\">Oj, n&aring;got gick fel!</span><ul>";
			for (var e = 0, l = form.erronous.length; e < l; e++) {
				$(form.erronous[e]).addClass("has-error");
				alertText += "<li>Kontrollera att " + form.erronous[e].title + " &auml;r korrekt" + "</li>";
			}
			for (e = 0, l = form.missing.length; e < l; e++) {
				$(form.missing[e]).addClass("has-error");
				alertText += "<li>Du har inte fyllt i " + form.missing[e].title + "</li>";
			}
			for (e = 0, l = form.unaccepted.length; e < l; e++) {
				alertText += "<li>Du m&aring;ste godk&auml;nna " + form.unaccepted[e].title; + "</li>"
			}
			alertText += "</ul>";
			alertBox.html(alertText);
			alertBox.slideDown(250);
			if ((window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop) > alertBox.offset().top) {
				O.scrollTo(alertBox);
			}
		});
	};
	
	var DOMReady = function() {
		$("form.validate").submit(function() {
			return O.form.validate(this);
		});
	};

	return {
		init: function() {
			$("form .has-error").live("keyup", function() {
				validateField(this);
				return false;
			});
            $(document).ready(DOMReady);
		},
		
		/**
		 * Validates a submitted form (or this if it's run on an element)
		 */
		validate: function(form) {
			form.erronous = [];
			form.missing = [];
			form.unaccepted = [];
			form.hasErrors = false;
			
			$(form).find("input, textarea").each(function() {
				if (O.isVisible(this)) {
					validateField(this);
				}
			});
			if (form.hasErrors) {
				alertUser(form);
				return false;
			} else {
				return true;
			}
		},
		
		reset: function(form) {
			form.reset();
			var form = $(form);
			form.find("input, textarea").removeClass("has-error");
			form.find(".alert-box").hide();
		},
		
		submitWithAjax: function(form, callback) {
			var data = $("form").serialize();
			data += "&ajax=true";
			$.post(form.getAttribute("action"), data, callback, "json");
		}
	};
}();


/**
 * Adds anchors around an elements inner elements when hovered.
 * Sets a class of "hover" on the parent element when its
 * children are being hovered.
 */
O.addAnchors = function(){
	var stopElements = [];
	
	var getParent = function(el){
		for (var i = 0, ln = stopElements.length; i < ln; i++) {
			var parent = $(el).closest(stopElements[i].selector);
			if (typeof(parent[0]) !== "undefined") {
				if (stopElements[i].linkable) {
					return parent;
				} else {
					return null;
				}
			}
		}
	};
	
	return {
		init: function(settings) {
			if (settings) {
				var selectorArray = [];
				for (var i = 0, ln = settings.length; i < ln; i++) {
					if (settings[i].element) {
						if (settings[i].exclude) {
							for (j = 0, ln2 = settings[i].exclude.length; j < ln2; j++) {
								stopElements.push({
									selector: settings[i].element + " " + settings[i].exclude[j],
									linkable: false
								});
							}
						}
						stopElements.push({
							selector: settings[i].element,
							linkable: true
						});
						if (settings[i].include) {
							for (var j = 0, ln2 = settings[i].include.length; j < ln2; j++) {
								selectorArray.push(settings[i].element + " " + settings[i].include[j]);
							}
						}
					}
				}
				
				var selectors = selectorArray.join(",");

				$(selectors).live("mouseout", function() {
					if (this.linkParent) {
						this.linkParent.removeClass("hover");
					}
				});

				$(selectors).live("mouseover", function() {
					if (!this.linkParent && !this.linked) {
						var el = getParent(this);
						if (el != null) {
							this.linkParent = el;
							var as = el.find("a");
							if (as.length > 0) {
								if (this.innerHTML.length == 0) {
									$(this).wrap($("<a href=\"" + as[0].href + "\" class=\"added-anchor\"></a>"));
								} else if (this.innerHTML.toLowerCase().indexOf("<a") != 0) {
									this.innerHTML = "<a href=\"" + as[0].href + "\" class=\"added-anchor\">" + this.innerHTML + "</a>";
								}
							}
						} else {
							this.linked = true;
						}
					}
					if (this.linkParent) {
						this.linkParent.addClass("hover");
					}
				});
			}
		}
	};
}();


/*
 * TCO
 */
var tco = function() {
	return {	
		init: function() {			
			O.init();
			O.form.init();
			tco.articleTools.init();
			tco.getTickerData.init();
			tco.slideShow.init();
			tco.getTags.init();
			tco.video.init();
			tco.comments.init();
			O.addAnchors.init([
				{
					element: ".item .item-content",
					include: ["p", "img"],
					exclude: [".image p"]
				},
				{
					element: ".teaser",
					include: ["p", "img"]
				}
			]);
			tco.twitter.init();
			tco.twingly.init();
			tco.f100.init();
			tco.tooltips.init();
			tco.fader.init();
			tco.map.init();
		}
	};
}();


tco.slideShow = function() {
	var elms = [];
	var instantiated = false;
	var toggleTo = function(elm) {
		if ($(".slideshow").length == 0) {
			var wrapper = $(".image ul").parent();
			wrapper.html("<div class=\"slideshow\"><img src=\"" + elms[elm].src + "\"/><p>" + elms[elm].caption + "</p></div>");
			$(".slideshow img").load( function() {
				if (instantiated) {
					$(".slideshow").fadeIn("slow");
					wrapper.animate({
						"height": $(".slideshow").outerHeight()
					}, "slow");
				} else {
					wrapper.css("height", $(".slideshow").outerHeight());
					instantiated = true;
				}
			});
		} else {
			$(".slideshow").stop(true, true);
			$(".slideshow").fadeOut("normal", function() {
				$(".slideshow img").attr("src", elms[elm].src);
				$(".slideshow p").html(elms[elm].caption);

			});
			
		}
		$(".slideshow-navigation a").removeClass("current");
		$(".slide-" + elm).addClass("current");
	};
	var DOMReady = function() {
		$(".image li a").each( function() {
			elm = $(this);
			elms.push( {
				"src": elm.attr("href"),
				"caption": elm.text(),
				"thumb": $(elm.children("img")).attr("src")
			} );
		});

		if (elms.length > 0) {
			$(".image").addClass("loader");
			$(".article-additional").prepend("<div class=\"slideshow-navigation\"><ul></ul></div>");
			for (var i = 0, l = elms.length; i < l; i++) {
				$(".slideshow-navigation ul").append("<li><a href=\"" + elms[i].src + "\" class=\"slide-" + i + "\"><img src=\"" + elms[i].thumb + "\"/><span></span></a></li>");
			}
			toggleTo(0);
			$(".slideshow-navigation a").live("click", function() {
				toggleTo(O.getClassNameValue(this, "slide"));
				return false;
			});
		}
	};
	return {
		init: function() {
            $(document).ready(DOMReady);
		}
	};
}();


tco.getTags = function() {
	var getAll = function (data, textStatus) {
		$(".tag-list").html($(data).find("li"));
	};
	
	var DOMReady = function() {
		$(".tag-list .more").click(function(e) {
			e.preventDefault();
			var el = $(this).parents(".tag-list");
			jQuery.getJSON(this.href, { ajax: "true" }, function(data) {
				el.html(data.html);
			});
			return false;
		});
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}();


tco.ticker = function() {
	var easing = "easeInOutQuad";
	var duration = 1500;
	var interval = 4000;
	var step = function(id) {
		var ul = $("#" + id);
		if (!ul.data("over")) {
			var elm = $($(ul).children("li")[0]);
			elm.animate( 
				{ marginLeft: "-=" + elm.outerWidth() },
				ul.data("duration"),
				ul.data("easing"),
				function() {
					this.parentNode.appendChild(this);
					$(this).css("marginLeft", "0px"); 
					setTimer(id);
				}
			);	
		} else {
			setTimer(id);
		}
	};
	var setTimer = function(id) {
		$("#" + id).data("timer", setTimeout( function() { step(id); }, $("#" + id).data("interval")));
	}
	return {
		start: function(args) {
			var tickerList = $("#" + args.id);
			args.easing ? tickerList.data("easing", args.easing) : tickerList.data("easing", easing) ;
			args.duration ? tickerList.data("duration", args.duration) : tickerList.data("duration", duration) ;
			args.interval ? tickerList.data("interval", args.interval) : tickerList.data("interval", interval) ;

			var totalLength = 0;
			tickerList.children("li").each(function() {	totalLength += $(this).outerWidth(); });
			tickerList.width(totalLength + 1);
			
			if (args.onReady) {	args.onReady();	}
			setTimer(args.id);

			$("#" + args.id + " li a").live("mouseover", function() {
				tickerList.data("over", true);
				return false;
			});
			$("#" + args.id + " li a").live("mouseout", function() {
				tickerList.data("over", false);
				return false;
			});
		}
	};
}();


tco.getTickerData = function() {
	var DOMReady = function() {
		var tickers = 0;
		$(".ticker").each(function() {
			var tickerElm = $(this);
			var url = "tickerXmlToJson.cfm?u=" + escape(tickerElm.children("a")[0].href);
			$.getJSON(url,
        		function(data) {
        			if (data.VALUE.ITEMS.length > 0) {
        				var tickerListId = "ticker-list-" + tickers;
						tickerElm.append("<ul id=\"" + tickerListId + "\"></ul>");
						for (var i = 0, l = data.VALUE.ITEMS.length; i < l; i++) {
							$("#" + tickerListId).append("<li><a href=\"" + data.VALUE.ITEMS[i]["LINK"] + "\">" + data.VALUE.ITEMS[i]["TITLE"] + "</a></li>");
						}
						tco.ticker.start({ 
							id: tickerListId
						});
						tickers++;
        			}
				}
			);
		});
	};
	return {
		init: function() {
            $(document).ready(DOMReady);
		}
	};
}();


tco.articleTools = function() {
	var getTools = function(el) {
		return $($(el.parents(".tools")[0]).find(".tools-content")[0]);
	};
	var show = function(el) {
		var tools = getTools(el);
		var wrapper = $("#" + el.attr("id") + "-wrapper");
		if (wrapper.length == 0) {
			el.wrap($("<div id=\"" + el.attr("id") + "-wrapper\"></div>"));
			wrapper = $("#" + el.attr("id") + "-wrapper");
			wrapper.data("original-width", tools.outerWidth(true) + "px");
			wrapper.data("original-height", tools.outerHeight(true) + "px");
			wrapper.width(wrapper.data("original-width"));
			wrapper.height(wrapper.data("original-height"));
		}
		tools.hide();
		wrapper.show();
		wrapper.animate({"width": el.outerWidth(true) + "px", "height": el.outerHeight(true) + "px"}, "fast", null, function() {
			el.fadeIn("slow", function() {
				wrapper.width("auto");
				wrapper.height("auto");
			});
		});
	};
	var hide = function(el, callback) {
		var tools = getTools(el);
		var wrapper = $("#" + el.attr("id") + "-wrapper");
		wrapper.width(wrapper.width() + "px");
		wrapper.height(wrapper.height() + "px");
		el.fadeOut("fast", function() {
			wrapper.animate({"width": wrapper.data("original-width"), "height": wrapper.data("original-height")}, "fast", null, function() {
				wrapper.hide();
				tools.show();
				if (callback) {
					callback.call(el);
				}
			});
		})
	};
	var DOMReady = function() {
		var tools = $(".article .tools");
		if (tools.length > 0) {
			tools.addClass("tools-rounded");
			tools.append("<div class=\"w3\"></div>");
			tools.wrapInner("<div class=\"w2\"></div>");
			tools.wrapInner("<div class=\"w1\"></div>");
		}
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
			$(".tools .tip, .tools .share").live("click", function() {
				show($("#" + O.getHash(this.href)));
				return false;
			});
			$(".tool .cancel").live("click", function() {
				var form = $(this).parents("form");
				hide($(this).parents(".tool"), function() {
					if (form.length > 0) {
						O.form.reset(form[0]);
					}
				});
				return false;
			});
			$("a.print").live("click", function() {
				print();
				return false;
			});
			$("#tip-form .submit").live("click", function() {
				if (O.form.validate(this.form)) {
					var form = $(this.form);
					tco.loader.add(form);
					O.form.submitWithAjax(this.form, function() {
						setTimeout(function() {
							hide(form.parent(), function() {
								O.form.reset(form.context);
								tco.loader.remove(this);
							})
						}, 500);
					});
				}
				return false;
			});
		}
	};
}();


tco.video = function() {
	var videoNo = 0;
	var DOMReady = function() {
		$(".video").each(function() {
			var href = this.href.replace(/\/watch\?|\=/g, "/");
			var id = "video-" + (videoNo++);
			$(this.parentNode).append("<div id=\""  + id + "\"></div>");
			swfobject.embedSWF(href, id, "500", "400", "8", null, null, {"wmode": "transparent"});
			$(this).remove();
		});
	};
	return {
		init: function() {
            $(document).ready(DOMReady);
		}
	};
}();


tco.comments = function() {
	var hide = function(callback) {
		var el = $("#add-comment-form");
		var form = $("#add-comment-form form")[0];
		el.fadeOut("fast", function() {
			O.form.reset(form);
			el.prev().show();
			if (callback) {
				callback.call(el);
			}
		});
	};
	var DOMReady = function() {
		if (window.location.hash == "#comments") {
			show();
		}
	}
	var show = function() {
		var el = $("#add-comment-form");
		var a = el.prev();
		a.hide();
		el.fadeIn(500);
	}
	return {
		init: function() {
            $(document).ready(DOMReady);
			$(".add-comment").live("click", function() {
				show();
				return false;
			});
			$("#add-comment-form .submit").live("click", function() {
				if (O.form.validate(this.form)) {
					var form = $(this.form);
					tco.loader.add(form);
					O.form.submitWithAjax(this.form, function(data) {
						if (data && data.comment && data.comment.text) {
							var comment = $("<div class=\"comment\"></div>");
							comment.append("<q><span>&rdquo;</span>" +  data.comment.text + "&rdquo;</q>");
							var info = $("<p class=\"comment-info\"></p>");
							if (data.comment.name) {
								if (data.comment.url) {
									info.append($("<cite><a href=\"" + data.comment.url + "\">" + data.comment.name + "</a></cite>"));
								} else {
									info.append($("<cite>" + data.comment.name + "</cite>"));
								}
							}
							info.append(", ");
							info.append($("<span class=\"date\">" + data.comment.date + "</span>"));
							comment.append(info);
							comment.hide();
							var previous = $(".comments .add-comment");
							if (previous.prev().hasClass("more")) {
								previous = previous.prev();
							}
							previous.before(comment);
							comment.fadeIn("fast");
						}
						setTimeout(function() {
							hide(function() {
								tco.loader.remove(this);
							});
						}, 500);
					});
				}
				return false;
			});
			$("#add-comment-form .cancel").live("click", function() {
				hide();
				return false;
			});
			$("#comment-text").bind("keyup", function() {
				if (this.value.length > 300) {
					this.value = this.value.substring(0, 300);
				}
			});
		}
	};
}();


tco.loader = function() {
	return {
		add: function(el) {
			el = $(el);
			el.append("<div class=\"loader\"></div>");
			var loader = $(".loader", el);
			el.css("position", "relative");
			loader.css("display", "none");
			loader.css("position", "absolute");
			loader.css("top", "0");
			loader.css("left", "0");
			loader.width(el.width() + "px");
			loader.height(el.height() + "px");
			loader.show();
			loader.fadeTo("slow", 1);
		},
		remove: function(el) {
			$(".loader", $(el)).remove();
		}
	};
}();


tco.twingly = function() {
	var onComplete = function() {
		var twingly = $(".twingly");
		if (twingly.length > 0 && typeof(tw_numberOfPosts) !== "undefined") {
			twingly.addClass("twingly-has-results");
		}
		twingly.css("display", "none");
		twingly.css("display", "none");
		twingly.find(".tw_list").wrapInner("<ul></ul>");
		twingly.find(".tw_item").wrap($("<li></li>"));
		twingly.fadeIn("fast");
	};
	return {
		init: function() {
			window.tw_language = "swedish";
			window.tw_skipDefaultCss = true;
			window.tw_useToolTip = false;
			window.tw_postLimit = 5;
			window.tw_onComplete = onComplete;
		}
	};
}();


tco.twitter = function() {
	var DOMReady = function() {
		$(".message SPAN").each(function() {
			if (this.className) {
				var el = $(this);
				jQuery.getJSON(this.className, { ajax: "true" }, function(data) {
					var el2 = $("<span>" + data.html + "</span>");
					el2.hide();
					el.after(el2);
					el.remove();
					el2.fadeIn("slow");
				});
			}
		});
	};
	return {
		init: function() {
            $(document).ready(DOMReady);
		}
	}
}();


tco.tooltips = function() {
	return {
		init: function() {
			$(".vote-option img, .vote-opinions img").live("mouseover", function() {
				if (!(jQuery.browser.msie && jQuery.browser.version <= 6)) {
					var img = $(this);
					if (!img.data("has-tooltip")) {
						var alt = img.attr("alt");
						if (alt.length > 0) {
							img.after("<span class=\"tooltip\"><span>" + alt + "</span></span>");
							img.attr("alt", "");
						}
						img.data("has-tooltip", true);
					}					
				}
			});
		}
	};
}();


tco.f100 = function() {
	return {
		init: function() {
			$("body.f100 #submit-anonymous").live("click", function() {
				var comment = $("#comment");
				if (!this.checked) {
					comment[0].value = $(this).data("comment");
				} else {
					$(this).data("comment", comment[0].value);
					comment[0].value = "";
				}
				$("#comment").parent().slideToggle(250);
			});
			$("body.f100 #login .help").live("click", function() {
				$("#" + O.getHash(this.href)).fadeIn();
				$(this).hide();
				return false;
			});
		}
	}
}();


tco.fader = function() {
	var DOMReady = function() {
		var els = $("#latest-votes-list li a");
		if (els.length > 1) {
			var opacity = 1 / (els.length);
			for (var i = 1, ln = els.length; i < ln; i++) {
				$(els[i]).css("opacity", Math.max(0.2, opacity * (ln - i)));
			}
		};
	};	
	return {
		init: function() {
			$(document).ready(DOMReady);
		}	
	}
}();


tco.map = function() {
	var map = null;
	var infoWin = function(latlng, html) {
		this.latlng_ = latlng;
		this.html_ = html;
		this.initialized = false;
		this.visible = false;
		
		this.setup = function() {
			this.initialized = true;
			this.prototype = new GOverlay();
		};

		this.initialize = function(map) {
			var div = $('<div />');
			div.css({
				position : 'absolute',
				width : 234
			}).appendTo(map.getPane(G_MAP_FLOAT_PANE))
		
			this.map_ = map;
			this.div_ = div;
		
			this.update(html);
		};
		
		this.update = function(html){
			this.html_ = html;		
			this.div_.empty();
			
			var content = $("<div/>").html(html);
			var closeButton = $("<a/>").attr({
				"href": "#",
				"class": "close"
			}).html("[x]");
			content.append(closeButton);
			$("<div />").addClass("infowin-content").html(content).appendTo(this.div_);				

			this.redraw(true);
		};

		this.remove = function() {
			this.div_.remove();
		};

		this.copy = function() {
			return new Infowin(this.latlng_, this.html_);
		};
		
		this.redraw = function(force) {
			if (!force) return;

			var point = this.map_.fromLatLngToDivPixel(this.latlng_);
		
			var image = $(this.div_).find("img").get(0);
			var div = this.div_;
			if (image && !image.complete) {
				div.hide();
				$(image).bind("load", function() {
					div.css({
						left: point.x - 33,
						top: point.y - div.height() + 24
					});
					div.show();		
				});	
			} else {
				div.css({
					left: point.x - 33,
					top: point.y - div.height() + 24
				});		
			}
		};
		
		this.show = function() {
			if (!this.visible) {
				if (tco.map.activeInfoWindow != null) {
					tco.map.activeInfoWindow.hide();
				}
				if (!this.initialized) {
					this.setup();
				}
				map.addOverlay(this);
				map.panTo(this.latlng_);
				tco.map.activeInfoWindow = this;
				this.visible = true;				
			}
		};
		
		this.hide = function() {
			if (this.visible) {
				map.removeOverlay(this);
				this.visible = false;				
				tco.map.activeInfoWindow = null;;
			}
		};
		
		this.toggle = function() {
			if (this.visible) {
				this.hide();
			} else {
				this.show();
			}
		}
	};
	
	var DOMReady = function() {
		if (document.getElementById("f100-map")) {
			var key = null;
			if (location.href.indexOf("tcotidningen.se") != -1) {
				//key = "ABQIAAAAz4m0IsIIqHpFecZfcfoDLBTcy1eceD-U0KuetpTEDJyIGLwPVhTWOMKmQJ_Qux2SnOAxAH5sQJiGPQ";
				key = "ABQIAAAAtyWBJCetgHs2SpAcGs8v_hSRO4sIgh7Cu7jATCCHW0iIpoRCYhS8f_X3NyZYiuBTP3CWDnWu9pd0kA";
			} else if (location.href.indexOf("tcotidning.test.dropit.se") != -1) {
				key = "ABQIAAAAz4m0IsIIqHpFecZfcfoDLBQVkgv9iZzNE7lDTLgztF5_GvA9BBRUOWrB0RP5DdWdq6zoDbyEETV7Vw";
			} else if (location.href.indexOf("127.0.0.1") != -1) {
				key = "ABQIAAAAha0OUuJrIMapSnLc1F1YZRTpH3CbXHjuCVmaTc5MkkU4wO1RRhSOvlY5Hy4sSxQ6PNJBrD07MOpQLg";
			} else if (location.href.indexOf("tco.sector5.local") != -1) {
				key = "ABQIAAAAtyWBJCetgHs2SpAcGs8v_hQwac9tb4bFxIxpuTlHJEWv5SdRahSHQXyBwqfdSpv0Az5BnPSzMIOAXA";
			} else {
				key = "ABQIAAAAsalFPDFTLbG4SJOKQvtGRBQNqsavyR7oXCpaC-ANoE8jDaMTxRSZJ12WHWsmZNVA4rNO0kcH9nrc0g";
			}
			$.getScript("http://maps.google.se/maps?file=api&v=2&async=2&callback=tco.map.setup&key=" + key);
		}
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		},
		setup: function() {
			if (typeof(GBrowserIsCompatible) == "function") {
				if (GBrowserIsCompatible()) {
					var mapEl = $("#f100-map");
					var latlng = [];
					var latlngbounds = new GLatLngBounds();
					var lis = mapEl.find("li");
					var locations = [];
					var noOfLis = lis.length;
					var noOfLisParsed = 0;
					
					var icon = new GIcon();
					icon.image = "/img/tco_nal.png";
					icon.shadow = "/img/tco_nal-shadow.png";
					icon.iconSize = new GSize(32, 32);
					icon.iconAnchor = new GPoint(8, 8);
					icon.infoWindowAnchor = new GPoint(8, 9);
					
					var activeId = O.getHash(window.location.href);
					lis.each(function(){
						var li = $(this);
						latlng = li.find(".latlng").html().split(",");
						point = new GLatLng(latlng[0], latlng[1]);
						if(point) {
							locations.push({
								point: point,
								html: li.find(".info").html(),
								active: li[0].id == activeId
							});
							latlngbounds.extend(point);
						}
						noOfLisParsed++;
						if (noOfLis == noOfLisParsed) {
							map = new GMap2(mapEl[0]);
							map.addControl(new GLargeMapControl3D());
							map.addControl(new GMapTypeControl());
													
							jQuery.each(locations, function(i) {
								var marker = new GMarker(this.point, {
									icon: icon
								});
								marker.infoWindow = new infoWin(locations[i].point, $(locations[i].html));
								map.addOverlay(marker);
								
								GEvent.addListener(marker, "click", function() {
									marker.infoWindow.toggle();
								});

								if (this.active) {
									tco.map.activeInfoWindow = marker.infoWindow;
								}
							});
							map.setCenter(latlngbounds.getCenter(), map.getBoundsZoomLevel(latlngbounds));
							if (tco.map.activeInfoWindow != null) {
								tco.map.activeInfoWindow.show();
							}
						}
					});
					$("#f100-map .close").live("click", function() {
						tco.map.activeInfoWindow.hide();
						return false;
					});
				}
			}			
		}
	};
}();


tco.init();