var jquery = jQuery.noConflict();
/*
* jQuery BBQ: Back Button & Query Library - v1.3pre - 8/26/2010
* http://benalman.com/projects/jquery-bbq-plugin/
* 
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($, r) { var h, n = Array.prototype.slice, t = decodeURIComponent, a = $.param, j, c, m, y, b = $.bbq = $.bbq || {}, s, x, k, e = $.event.special, d = "hashchange", B = "querystring", F = "fragment", z = "elemUrlAttr", l = "href", w = "src", p = /^.*\?|#.*$/g, u, H, g, i, C, E = {}; function G(I) { return typeof I === "string" } function D(J) { var I = n.call(arguments, 1); return function() { return J.apply(this, I.concat(n.call(arguments))) } } function o(I) { return I.replace(H, "$2") } function q(I) { return I.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/, "$1") } function f(K, P, I, L, J) { var R, O, N, Q, M; if (L !== h) { N = I.match(K ? H : /^([^#?]*)\??([^#]*)(#?.*)/); M = N[3] || ""; if (J === 2 && G(L)) { O = L.replace(K ? u : p, "") } else { Q = m(N[2]); L = G(L) ? m[K ? F : B](L) : L; O = J === 2 ? L : J === 1 ? $.extend({}, L, Q) : $.extend({}, Q, L); O = j(O); if (K) { O = O.replace(g, t) } } R = N[1] + (K ? C : O || !N[1] ? "?" : "") + O + M } else { R = P(I !== h ? I : location.href) } return R } a[B] = D(f, 0, q); a[F] = c = D(f, 1, o); a.sorted = j = function(J, K) { var I = [], L = {}; $.each(a(J, K).split("&"), function(P, M) { var O = M.replace(/(?:%5B|=).*$/, ""), N = L[O]; if (!N) { N = L[O] = []; I.push(O) } N.push(M) }); return $.map(I.sort(), function(M) { return L[M] }).join("&") }; c.noEscape = function(J) { J = J || ""; var I = $.map(J.split(""), encodeURIComponent); g = new RegExp(I.join("|"), "g") }; c.noEscape(",/"); c.ajaxCrawlable = function(I) { if (I !== h) { if (I) { u = /^.*(?:#!|#)/; H = /^([^#]*)(?:#!|#)?(.*)$/; C = "#!" } else { u = /^.*#/; H = /^([^#]*)#?(.*)$/; C = "#" } i = !!I } return i }; c.ajaxCrawlable(0); $.deparam = m = function(L, I) { var K = {}, J = { "true": !0, "false": !1, "null": null }; $.each(L.replace(/\+/g, " ").split("&"), function(O, T) { var N = T.split("="), S = t(N[0]), M, R = K, P = 0, U = S.split("]["), Q = U.length - 1; if (/\[/.test(U[0]) && /\]$/.test(U[Q])) { U[Q] = U[Q].replace(/\]$/, ""); U = U.shift().split("[").concat(U); Q = U.length - 1 } else { Q = 0 } if (N.length === 2) { M = t(N[1]); if (I) { M = M && !isNaN(M) ? +M : M === "undefined" ? h : J[M] !== h ? J[M] : M } if (Q) { for (; P <= Q; P++) { S = U[P] === "" ? R.length : U[P]; R = R[S] = P < Q ? R[S] || (U[P + 1] && isNaN(U[P + 1]) ? {} : []) : M } } else { if ($.isArray(K[S])) { K[S].push(M) } else { if (K[S] !== h) { K[S] = [K[S], M] } else { K[S] = M } } } } else { if (S) { K[S] = I ? h : "" } } }); return K }; function A(K, I, J) { if (I === h || typeof I === "boolean") { J = I; I = a[K ? F : B]() } else { I = G(I) ? I.replace(K ? u : p, "") : I } return m(I, J) } m[B] = D(A, 0); m[F] = y = D(A, 1); $[z] || ($[z] = function(I) { return $.extend(E, I) })({ a: l, base: l, iframe: w, img: w, input: w, form: "action", link: l, script: w }); k = $[z]; function v(L, J, K, I) { if (!G(K) && typeof K !== "object") { I = K; K = J; J = h } return this.each(function() { var O = $(this), M = J || k()[(this.nodeName || "").toLowerCase()] || "", N = M && O.attr(M) || ""; O.attr(M, a[L](N, K, I)) }) } $.fn[B] = D(v, B); $.fn[F] = D(v, F); b.pushState = s = function(L, I) { if (G(L) && /^#/.test(L) && I === h) { I = 2 } var K = L !== h, J = c(location.href, K ? L : {}, K ? I : 2); location.href = J }; b.getState = x = function(I, J) { return I === h || typeof I === "boolean" ? y(I) : y(J)[I] }; b.removeState = function(I) { var J = {}; if (I !== h) { J = x(); $.each($.isArray(I) ? I : arguments, function(L, K) { delete J[K] }) } s(J, 2) }; e[d] = $.extend(e[d], { add: function(I) { var K; function J(M) { var L = M[F] = c(); M.getState = function(N, O) { return N === h || typeof N === "boolean" ? m(L, N) : m(L, O)[N] }; K.apply(this, arguments) } if ($.isFunction(I)) { K = I; return J } else { K = I.handler; I.handler = J } } }) })(jQuery, this);
/*
* jQuery hashchange event - v1.3 - 7/21/2010
* http://benalman.com/projects/jquery-hashchange-plugin/
* 
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($, e, b) { var c = "hashchange", h = document, f, g = $.event.special, i = h.documentMode, d = "on" + c in e && (i === b || i > 7); function a(j) { j = j || location.href; return "#" + j.replace(/^[^#]*#?(.*)$/, "$1") } $.fn[c] = function(j) { return j ? this.bind(c, j) : this.trigger(c) }; $.fn[c].delay = 50; g[c] = $.extend(g[c], { setup: function() { if (d) { return false } $(f.start) }, teardown: function() { if (d) { return false } $(f.stop) } }); f = (function() { var j = {}, p, m = a(), k = function(q) { return q }, l = k, o = k; j.start = function() { p || n() }; j.stop = function() { p && clearTimeout(p); p = b }; function n() { var r = a(), q = o(m); if (r !== m) { l(m = r, q); $(e).trigger(c) } else { if (q !== m) { location.href = location.href.replace(/#.*/, "") + q } } p = setTimeout(n, $.fn[c].delay) } $.browser.msie && !d && (function() { var q, r; j.start = function() { if (!q) { r = $.fn[c].src; r = r && r + a(); q = $('<iframe tabindex="-1" title="empty"/>').hide().one("load", function() { r || l(a()); n() }).attr("src", r || "javascript:0").insertAfter("body")[0].contentWindow; h.onpropertychange = function() { try { if (event.propertyName === "title") { q.document.title = h.title } } catch (s) { } } } }; j.stop = k; o = function() { return a(q.location.href) }; l = function(v, s) { var u = q.document, t = $.fn[c].domain; if (v !== s) { u.title = h.title; u.open(); t && u.write('<script>document.domain="' + t + '"<\/script>'); u.close(); q.location.hash = v } } })(); return j })() })(jQuery, this);
// placeholder
(function($) { $.fn.setPlaceholder = function(text) { function init() { var input = $(this); if (!text) { var text = input.attr("placeholder") } var replacement = $('<input class="replacement placeholder" size="' + input.attr("size") + '" title="' + input.attr("title") + '"type="text" value="' + text + '" />'); var type = input.attr("type"); input.blur(function() { if (!input.val()) { if (type == "password") { input.hide(); replacement.insertBefore(input).show() } else { input.val(text).addClass("placeholder") } } }).focus(function() { if (input.is(".placeholder")) { input.removeClass("placeholder").val("") } }); replacement.focus(function() { $(this).hide().next("input").show().focus() }); if (!input.val() || input.val() == text) { if (type == "password") { input.hide(); replacement.insertBefore(input).show().width(input.width()) } else { input.val(text).addClass("placeholder") } } } return this.each(init) } })(jQuery);



(function($) {
	var test = {
		step: null,
		steps: [],
		mapScript: false,
		result: false,
		expanded: false,
		init: function() {
			if ($(".test.large").length > 0) {
				test.expanded = true;
				test.button();
				test.disableForms();
				test.attachExpandedEvent();
			} else {
				test.button();
				test.removeSmallWrapper();
				test.groupSteps();
				test.disableForms();
				test.createNotifications();
				test.showStep();
				$(window).bind("hashchange", function(e) {
					if (test.result) {
						// todo: get from variable string and url
						if (confirm("gör om testet?")) {
							document.location.href = "/";
						}
					} else if (parseInt(jQuery.bbq.getState("steg"), 10) - 1 !== test.step) {
						test.hideStep();
						test.step = parseInt(jQuery.bbq.getState("steg"), 10) - 1;
						test.showStep();
					}
				});
			}
		},
		attachExpandedEvent: function() {
			$(".test fieldset fieldset").find("label").each(function() {
				var label = $(this),
				input = label.find("input"),
				msg = label.attr("data-msg");
				// remove title for js-enabled devices
				label.removeAttr("title");

				// attach event for change to show notification.
				if (input.is(":checked")) {
					$(".did-you-know p").text(msg);
					test.nextQuestion();
				}
				input.change(function() {
					// GA
					if (readCookie("ga_initTest") === null) {
						createCookie("ga_initTest", "true");
						//alert("/virtuell/test/enkat/klick-falt/"+document.location.href);
						_gaq.push(["_trackPageview", "/virtuell/test/enkat/klick-falt/" + document.location.href]);
					}
					if ($(this).is(":checked")) {
						$(".did-you-know p").text(msg);
						if (!$(this).closest("fieldset").hasClass("checked")) {
							test.nextQuestion();
							$(this).closest("fieldset").addClass("checked");
						}
					}
				});
			});
		},
		removeSmallWrapper: function() {
			$(".test.small .small").each(function() {
				var ques = $(this).children().clone();
				ques.insertAfter($(this));
				$(this).remove();
			});
			$(".odd").removeClass("odd");
			$(".even").removeClass("even");
		},
		// ===========================================
		// = Groups elements into test.steps (Array) =
		// ===========================================
		groupSteps: function() {
			var groupIndex = 0,
			step = [],
			index = 0;
			$(".test fieldset>div").each(function(i) {
				step[index] = $(this);
				index += 1;
				if (i % 2 === 1) {
					$(this).addClass("even");
					index = 0;
					test.steps[groupIndex] = step;
					step = [];
					groupIndex += 1;
				} else {
					$(this).addClass("odd");
				}
			});
		},
		// ==========================================================
		// = Displays the step and checks if it's completed already =
		// ==========================================================
		showStep: function() {
			if (test.step === null || isNaN(test.step)) {
				test.step = 0;
			}
			$(test.steps[test.step]).each(function() {
				$(this).fadeIn(400);
			});
			test.stepComplete();
		},
		// ==============
		// = Hide steps =
		// ==============
		hideStep: function() {
			$(test.steps[test.step]).each(function() {
				$(this).hide();
			});
		},
		// ==============================
		// = Checks if step is complete =
		// ==============================
		stepComplete: function() {
			$("a.test-button").removeClass("disabled");
			$(test.steps[test.step]).each(function() {
				if ($(this).find("fieldset.checked").length === 0) {
					$("a.test-button").addClass("disabled");
					return;
				}
			});
		},
		// =================
		// = Steps forward =
		// =================
		stepForward: function() {
			test.step += 1;
		},
		// =====================================================
		// = Creates a temporary button and handles that click =
		// =====================================================
		/*
		TODO 
		- handle testButton click.
		*/
		button: function() {
			var testButton = $("button.test-button"),
			button = $(document.createElement("a"))
				.attr("href", "#")
				.addClass("test-button"),
			span = $(document.createElement("span"))
				.text(testButton.text());
			button.append(span);
			testButton.after(button);
			testButton.click(function(e) {
				e.preventDefault();
				test.submitTest($(this));
			});
			button.click(function(e) {
				e.preventDefault();
				if (!$(this).hasClass("disabled")) {
					if (!test.expanded) {
						$(".bar").hide();
						test.hideStep();
						if (test.step === test.steps.length - 1) {
							$(".bar").hide(300);
							jQuery.bbq.pushState({ "steg": test.step + 2 });
							testButton.trigger("click");
						} else {
							test.stepForward();
							jQuery.bbq.pushState({ "steg": test.step + 1 });
							test.showStep();
							$(".bar").show();
							$(test.steps[test.step][0]).find("input")[0].focus();
						}
					} else {
						testButton.trigger("click");
					}
				}
			});
			if (!test.expanded) {
				$(".test .bar>fieldset").append(button);
			}
		},
		submitTest: function(button) {
			//alert("/virtuell/test/enkat/fatt-testresultat/"+" klickat-resultat");
			_gaq.push(["_trackPageview", "/virtuell/test/enkat/fatt-testresultat/"], ["_trackEvent", "a-aktivitet", "tagit-test", "klickat-resultat"]);
			$.post($("form").attr("action"), inputFields.fetch(button), function(xmlHttp) {
				var response = $("<div/>").append(xmlHttp.replace(/<script(.|\s)*?\/script>/g, ""));
				var h1 = $(".bar h1");
				response.find(".bar").hide();
				_gaq.push(["_trackEvent", "a-aktivitet", "resultat", response.find(".bar.result p").text().substring(0, 30)]);
				if (!test.expanded) {
					$(".bar").replaceWith(response.find(".bar"));
					$(".bar.result").prepend(h1).fadeIn(300);
					test.expandTest();
				} else {
					$(".bar").after(response.find("#mapAndContactWrapper"));
					$(".did-you-know h2").replaceWith(response.find(".bar.result h2"));
					$(".did-you-know p").replaceWith(response.find(".bar.result p"));
					$(".did-you-know a").replaceWith(response.find(".bar.result a"));
					$(".did-you-know a").click(function(e) {
						e.preventDefault();
						//alert("/virtuell/klick/narmaste-vardcentral/"+"klickat-narmaste-vardcentral");
						_gaq.push(["_trackPageview", "/virtuell/klick/narmaste-vardcentral/"], ["_trackEvent", "b-aktivitet", "tagit-test", "klickat-narmaste-vardcentral"]);
						$(".bar").fadeOut(300, function() {
							$("#top .medium").fadeOut(200);
							setTimeout(function() {
								$("#mapAndContactWrapper").fadeIn(200, function() {
								    MCmap.init();
								});
								$(".call a.test-button").click(function(e) {
									//alert("/virtuell/klick/infor-lakarbesoket/"+"klickat-infor-lakarbesoket");
									_gaq.push(["_trackPageview", "/virtuell/klick/infor-lakarbesoket/"], ["_trackEvent", "b-aktivitet", "tagit-test", "klickat-infor-lakarbesoket"]);
									$("#mapAndContactWrapper").fadeOut(200);
									e.preventDefault();
									$.get($(this).attr("href"), function(xmlHttp) {
										var response = $("<div/>").append(xmlHttp.replace(/<script(.|\s)*?\/script>/g, ""));
										response.find("#mapAndContactWrapper").hide();
										$(".bar").replaceWith(response.find(".bar"));
										$(".bar").fadeIn(300);
										$("a.print").click(function(e) {
											//alert("/virtuell/skrivut/www.levamedkol.se/har-jag-kol/");
											_gaq.push(["_trackPageview", "/virtuell/skrivut/www.levamedkol.se/har-jag-kol/"]);
											e.preventDefault();
											var win = window.open($(this).attr("href"), 'myWindow', 'scrollbars=yes,resizable=yes,width=420,height=230');
										});
									});
								});
							}, 400);
						});

					});
					//$(".bar.result").fadeIn(300);
					//test.expandTest();
				}
			});
		},
		// ===============================================
		// = To show the result, not expanded by default =
		// ===============================================
		expandTest: function() {
			$(".test-result").click(function(e) {
				e.preventDefault();
				//alert("/virtuell/klick/narmaste-vardcentral/"+"klickat-narmaste-vardcentral");
				_gaq.push(["_trackPageview", "/virtuell/klick/narmaste-vardcentral/"], ["_trackEvent", "b-aktivitet", "tagit-test", "klickat-narmaste-vardcentral"]);
				$(".result").fadeOut(300, function() {
					$("#top .medium").fadeOut(200);
					setTimeout(function() {
						$(".test").animate({ "width": "977px" }, 400, function() {
							$("#mapAndContactWrapper").fadeIn(200, function() {
								MCmap.init();
							});
							$(".call .test-button").click(function(e) {
								//alert("/virtuell/klick/infor-lakarbesoket/"+"klickat-infor-lakarbesoket");
								_gaq.push(["_trackPageview", "/virtuell/klick/infor-lakarbesoket/"], ["_trackEvent", "b-aktivitet", "tagit-test", "klickat-infor-lakarbesoket"]);
								$("#mapAndContactWrapper").fadeOut(200);
								e.preventDefault();
								$.get($(this).attr("href"), function(xmlHttp) {
									var response = $("<div/>").append(xmlHttp.replace(/<script(.|\s)*?\/script>/g, ""));
									response.find("#mapAndContactWrapper").hide();
									$(".bar").replaceWith(response.find(".bar"));
									$(".bar").fadeIn(300);
									$("a.print").click(function(e) {
										//alert("/virtuell/skrivut/www.levamedkol.se/har-jag-kol/");
										_gaq.push(["_trackPageview", "/virtuell/skrivut/www.levamedkol.se/har-jag-kol/"]);
										e.preventDefault();
										var win = window.open($(this).attr("href"), 'myWindow', 'scrollbars=yes,resizable=yes,width=420,height=230');
									});
								});
							});
						});
					}, 400);
				});

			});
		},
		createNotifications: function() {
			$(".test fieldset fieldset").each(function() {
				var notification = $(document.createElement("p"))
					.addClass("notify")
					.attr("aria-live", "assertive");

				// append empty notification element
				$(this).find("legend").after(notification);

				test.attachAnswerEvent($(this), notification);
			});
		},
		attachAnswerEvent: function(fieldset, notification) {
			fieldset.find("label").each(function() {
				var label = $(this),
				input = label.find("input"),
				msg = label.attr("data-msg");
				// remove title for js-enabled devices
				label.removeAttr("title");

				// attach event for change to show notification.
				if (input.is(":checked")) {
					test.notify(notification, msg);
					test.nextQuestion();
				}
				input.change(function() {
					// GA
					if (readCookie("ga_initTest") === null) {
						createCookie("ga_initTest", "true");
						//alert("/virtuell/test/enkat/klick-falt/"+document.location.href);
						_gaq.push(["_trackPageview", "/virtuell/test/enkat/klick-falt/" + document.location.href]);
					}
					if (jQuery.bbq.getState("steg") === undefined) {
						jQuery.bbq.pushState({ "steg": test.step + 1 });
					}
					if ($(this).is(":checked")) {
						test.notify(notification, msg);
						if (!$(this).closest("fieldset").hasClass("checked")) {
							test.nextQuestion();
							$(this).closest("fieldset").addClass("checked");
						}
					}
				});
			});
		},
		/*
		TODO 
		- needs to be more accurate than to check if .odd
		*/
		nextQuestion: function() {
			var fieldset = $($(".test .disabled")[0]);
			fieldset.removeClass("disabled")
				.find("input").removeAttr("disabled");
			if (fieldset.parent().hasClass("odd") && !test.expanded) {
				$("a.test-button").removeClass("disabled");
			}
			if ($(".question-index-6 .checked").length > 0 && test.expanded) {
				$("a.test-button").removeClass("disabled");
			}
		},
		disableForms: function(button) {
			$(".test fieldset fieldset, a.test-button").each(function(i) {
				// first fieldset is not disabled
				if (i > 0) {
					$(this).addClass("disabled").find("input").attr("disabled", "disabled");
				}
			});
		},
		notify: function(notification, msg) {
			if (msg && $.trim(msg).length > 0) {
				var span = $(document.createElement("span"))
				.text(msg);
				if (notification.find("span").length > 0) {
					test.hideNotification(notification, function() {
						test.showNotification(notification, span);
					});
				} else {
					notification.css("width", "0");
					test.showNotification(notification, span);
				}
			}
		},
		showNotification: function(notification, span) {
			if (notification.find("span").length === 0) {
				notification.append(span);
			} else {
				span = notification.find("span");
			}
			notification.addClass("measure");
			var spanWidth = span.outerWidth(true) + 30;
			span.hide();
			notification.removeClass("measure");
			notification.show();
			if (spanWidth > 200 && spanWidth < 300) {
				spanWidth = Math.floor(spanWidth / 2) + 10;
			} else if (spanWidth > 300) {
				spanWidth = Math.floor(spanWidth / 3) + 40;
			}

			notification.animate({ width: spanWidth }, 200, function() {
				notification.addClass("active");
				span.fadeIn(200);
			});
		},
		hideNotification: function(notification, callback) {
			notification.find("span").remove();
			notification.animate({ width: 10 }, 200, function() {
				if ($.isFunction(callback)) {
					callback.call();
				}
			});
		}
	};
	var SendCOPDTestMessage = {
		type: null,
		init: function() {
			SendCOPDTestMessage.typeOfContact();
			SendCOPDTestMessage.required();
			SendCOPDTestMessage.button();
		},
		typeOfContact: function() {
			if ($(".SendCOPDTestMessage input[type=radio]").length > 0) {
				$(".sms, .email").each(function() {
					if ($(this).find("input").is(":checked")) {
						// the label that is visible and required
						SendCOPDTestMessage.type = $(this).attr("class");
						var label = $(".for-" + $(this).attr("class")).addClass("show-type");
						label.addClass("show-type");
						label.find("input").attr({ "aria-required": true, "required": "required" });
					}
					$(this).find("input").change(function() {
						$(".show-type").each(function() {
							$(this).find("input").removeAttr("aria-required").removeAttr("required");
						}).removeClass("show-type");
						if ($(this).is(":checked")) {
							// the label that is visible and required
							SendCOPDTestMessage.type = $(this).parent().attr("class");
							var label = $(".for-" + $(this).parent().attr("class"));
							label.addClass("show-type");
							label.find("input").attr({ "aria-required": true, "required": "required" });
						}
					});
				});
			} else {
				$(".for-email").addClass("show-type");
				$(".for-email input").attr({ "aria-required": true, "required": "required" });
				SendCOPDTestMessage.type = "email";
			}

		},
		required: function() {
			$(".message, .name").attr({ "aria-required": true, "required": "required" });
		},
		button: function() {
			var testButton = $("button.test-button"),
			button = $(document.createElement("a"))
				.attr("href", "#")
				.addClass("test-button"),
			span = $(document.createElement("span"))
				.text(testButton.text());
			button.append(span);
			testButton.after(button);
			button.click(function(e) {
				e.preventDefault();
				if (SendCOPDTestMessage.validate()) {
					//alert("/virtuell/kontakt/formular-inskickat/"+"formular-inskickat");
					_gaq.push(["_trackPageview", "/virtuell/kontakt/formular-inskickat/"], ["_trackEvent", "b-aktivitet", "kontaktat", "formular-inskickat"]);
					testButton.trigger("click");
				}
			});
		},
		validate: function() {
			$(".not-valid").removeClass("not-valid");
			var valid = true,
			regExpMail = /^([A-Za-z0-9_\+\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
			regExpPhone = /^[0-9]+(\s|$)[0-9]+$/;
			$("input[required],textarea[required]").each(function() {
				if ($(this).hasClass("mail") && !regExpMail.test($(this).val())) {
					$(this).addClass("not-valid");
					valid = false;
					return;
				}
				if ($(this).val() !== $(this).attr("placeholder") && $(this).val().length === 0 || $(this).val() === $(this).attr("placeholder")) {
					$(this).addClass("not-valid");
					valid = false;
					return;
				}
			});
			return valid;
		}
	};
    
    // this client validation for contact form is not used now
    // it is replaced by ASP.NET validation
	var contact = {
		init: function() {
			contact.button();
			contact.required();
		},
		required: function() {
			$(".contact input, .contact textarea").attr({ "aria-required": true, "required": "required" });
		},
		validate: function() {
			$(".not-valid").removeClass("not-valid");
			var valid = true,
			regExpMail = /^([A-Za-z0-9_\+\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
			regExpPhone = /^[0-9]+(\s|$)[0-9]+$/;
			$("input[required],textarea[required]").each(function() {
				if ($(this).hasClass("mail") && !regExpMail.test($(this).val())) {
					$(this).addClass("not-valid");
					valid = false;
					return;
				}
				if ($(this).val() !== $(this).attr("placeholder") && $(this).val().length === 0 || $(this).val() === $(this).attr("placeholder")) {
					$(this).addClass("not-valid");
					valid = false;
					return;
				}
			});
			return valid;
		},
		button: function() {
			var testButton = $("button.test-button"),
			button = $(document.createElement("a"))
				.attr("href", "#")
				.addClass("test-button"),
			span = $(document.createElement("span"))
				.text(testButton.text());
			button.append(span);
			testButton.after(button);
			button.click(function(e) {
				e.preventDefault();
				if (contact.validate()) {
					testButton.trigger("click");
				}
			});
		}
	};
	var MCmap = {
		map: null, 		/* the map-object*/
		infowindow: null, /* popup window in map*/
		markers: [], 		/* array with all markers on the map */
		zoomLevel: 3, 	/* initial zoom*/
		startMessage: null,
		cityListHeading: null,
		healthCenterHeading: null,
		noHitsMessage: null,
		init: function() {
		    var mapCanvas = document.getElementById("map_canvas");
		    if(mapCanvas == null)
		        return;
		    
		    $.getJSON('?getcontent=StartMessage,CityListHeading,HealthCenterHeading,NoHitsMessage&type=portlet', function(json) {
				MCmap.startMessage = json[0].Value;
				MCmap.cityListHeading = json[1].Value;
				MCmap.healthCenterHeading = json[2].Value;
				MCmap.noHitsMessage = json[3].Value;
				if ($("#heading").length === 0) {
					$("#details").append("<li id='heading'>" + MCmap.startMessage + "</li>");
				}
			});


			// Create map object
			MCmap.map = new google.maps.Map(document.getElementById("map_canvas"), {
				zoom: 3,
				mapTypeControl: false,
				streetViewControl: false,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			});

			// bind events for geocode
			MCmap.initSearch();

			// set initialLocation To show map
			MCmap.setLocation(new google.maps.LatLng(63.2217815, 14.6022274), MCmap.zoomLevel);

			// when map is loaded
			google.maps.event.addListenerOnce(MCmap.map, "tilesloaded", function() {
				// Try if geolocation or google gears is supported and used
				// This function will alsp run initMarkers
				MCmap.geolocation();
			});
		},
		// =====================================
		// = binds events on input for geocode =
		// =====================================
		initSearch: function() {
			$(".search-mc").click(function(e) {
				e.preventDefault();
				MCmap.geocode($(".search-for-mcc input").val());
			});
			$(".search-for-mcc input").keypress(function(e) {
				if (e.keyCode === 13) {
					MCmap.geocode($(this).val());
					e.preventDefault();
				}
			});
		},
		// ================================================
		// = just centers a location in a given zommlevel =
		// ================================================
		setLocation: function(latLng, zoomLevel) {
			MCmap.map.setCenter(latLng);
			if (parseInt(zoomLevel, 10) > 0) {
				MCmap.map.setZoom(zoomLevel);
			}
		},
		// ===========================================================
		// = Checks for geolocation/google gears geolocation support =
		// ===========================================================
		geolocation: function() {
			// try native support for geolocation
			if (navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(function(position) {
					// setLocation with geolocation and zoomlevel
					var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
					MCmap.setLocation(location, 14);
					MCmap.initMarkers();
				}, function() {
					MCmap.handleNoGeolocation();
				});
				// Try Google Gears Geolocation
			} else if (google.gears) {
				var geo = google.gears.factory.create("beta.geolocation");
				geo.getCurrentPosition(function(position) {
					// setLocation with googlegears and zoomlevel
					var location = new google.maps.LatLng(position.latitude, position.longitude);
					MCmap.setLocation(location, 14);
					MCmap.initMarkers();
				}, function() {
					MCmap.handleNoGeolocation();
				});
				// Browser doesn't support Geolocation
			} else {
				MCmap.handleNoGeolocation();
			}
		},
		// ======================================
		// = Let's try to get coordinate via ip =
		// ======================================
		handleNoGeolocation: function() {
			$.getJSON(document.location.href, {
				getipcoordinate: true,
				json: true
			}, function(position) {
				if (position.Latitude > 0 && position.Longitude > 0) {
					var location = new google.maps.LatLng(position.Latitude, position.Longitude);
					MCmap.setLocation(location, 12);
					MCmap.initMarkers();
				} else {
					MCmap.initMarkers();
				}
			});
		},
		// ====================
		// = Initiate markers =
		// ====================
		initMarkers: function() {
			MCmap.info("Laddar");
			if (MCmap.map.zoom < 5) {
				MCmap.info("zooma in mer");
			} else {
				MCmap.getMarkers();
			}
			google.maps.event.addListener(MCmap.map, "dragend", function() {
				MCmap.info("Laddar");
				if (MCmap.map.zoom < 5) {
					MCmap.info("zooma in mer");
				} else {
					MCmap.getMarkers();
				}
			});
			google.maps.event.addListener(MCmap.map, "zoom_changed", function() {
				MCmap.info("Laddar");
				if (MCmap.infowindow) {
					MCmap.infowindow.close();
				}
				if (MCmap.map.zoom > 6) {
					if ((MCmap.zoomLevel === 11 && MCmap.map.zoom === 12) || (MCmap.zoomLevel === 12 && MCmap.map.zoom === 11)) {
						MCmap.clearAllMarkers();
					}
					MCmap.zoomLevel = MCmap.map.zoom;
					MCmap.getMarkers();
				} else {
					MCmap.clearAllMarkers();
					MCmap.info("zooma in mer");
				}
			});
			google.maps.event.addListener(MCmap.map, "dragstart", function() {
				if (MCmap.infowindow) {
					MCmap.infowindow.close();
				}
			});
		},
		// =================
		// = create marker =
		// =================
		initMarker: function(item) {
			var position = new google.maps.LatLng(item.Latitude, item.Longitude),
			marker = new google.maps.Marker({
				map: MCmap.map,
				animation: google.maps.Animation.DROP,
				position: position,
				title: item.Name,
				visible: false,
				id: item.Id,
				name: item.Name,
				address: item.Address === undefined ? "" : item.Address,
				cityName: item.CityName,
				phoneNumber: item.PhoneNumber,
				postalCode: item.PostalCode
			});
			google.maps.event.addListener(MCmap.map, "bounds_changed", function() {
				if (!MCmap.map.getBounds().contains(marker.position)) {
					MCmap.clearMarker(marker);
				}
			});
			if (!MCmap.markerAlreadyOnMap(marker)) {
				MCmap.addMarker(marker);
				marker.setVisible(true);
			}
		},
		// =============================================
		// = Add marker to map, list and MCmap.markers =
		// =============================================
		addMarker: function(marker) {
			google.maps.event.addListener(marker, "click", function() {
				if (MCmap.infowindow) {
					MCmap.infowindow.close();
				}
				if (MCmap.map.zoom <= 11) {
					MCmap.clearAllMarkers();
					MCmap.setLocation(marker.getPosition(), 12);
				} else {
					MCmap.infowindow = new google.maps.InfoWindow({
						content: "<div class='infowindow'><b>" + marker.title + "</b>" + "<div class='adress'>" + marker.address.toLowerCase() + ", " + marker.cityName.toLowerCase() + "</div>" + marker.phoneNumber + "</div>"
					});
					MCmap.infowindow.open(MCmap.map, marker);
					MCmap.getMarkers();
				}
			});
			var detail = document.createElement("li");
			detail.id = "detail" + marker.id;
			if (MCmap.map.zoom <= 11) {
				detail.innerHTML = "<b>" + marker.name.toLowerCase() + "</b>";
			} else {
				detail.innerHTML = "<b>" + marker.name.toLowerCase() + "</b><br/>" + marker.address.toLowerCase() + ", " + marker.cityName.toLowerCase() + "<a href='#'>" + marker.phoneNumber + "</a>";
			}
			$("#details").append(detail);
			detail.onclick = function(e, obj) {
				google.maps.event.trigger(marker, 'click');
			};
			MCmap.markers.push(marker);
		},
		// =====================================
		// = Check if marker is already on map =
		// =====================================
		markerAlreadyOnMap: function(marker) {
			var alreadyOnMap = false;
			if (MCmap.markers) {
				$.each(MCmap.markers, function() {
					if (this.id === marker.id) {
						alreadyOnMap = true;
						return;
					}
				});
				return alreadyOnMap;
			}
		},
		// =======================================================
		// = Clear all markers from map, list and MCmap.markers  =
		// =======================================================
		clearAllMarkers: function() {
			$("#details").children().not("#heading").remove();
			if (MCmap.markers) {
				$.each(MCmap.markers, function() {
					this.setMap(null);
				});
				MCmap.markers.length = 0;
			}
		},
		// =========================
		// = clear specifik marker =
		// =========================
		clearMarker: function(marker) {
			if (MCmap.markers) {
				$.each(MCmap.markers, function(i) {
					if (this.id === marker.id) {
						// remove from details list
						$("#detail" + marker.id).remove();
						// reomve from map
						this.setMap(null);
						// reomve from array
						MCmap.markers.splice(i, 1);
					}
				});
			}
		},
		// ============================
		// = get markers from backend =
		// ============================
		getMarkers: function() {
			$.getJSON(document.location.href, {
				"type": MCmap.map.zoom <= 11 ? "city" : "healthcenter",
				"lat1": MCmap.map.getBounds().getNorthEast().lat(),
				"long1": MCmap.map.getBounds().getNorthEast().lng(),
				"lat2": MCmap.map.getBounds().getSouthWest().lat(),
				"long2": MCmap.map.getBounds().getSouthWest().lng(),
				"json": true
			}, function(json) {
				if (json.length > 0) {
					if (MCmap.map.zoom >= 12) {
						$("#heading").text(MCmap.healthCenterHeading);
					} else {
						$("#heading").text(MCmap.cityListHeading);
					}
					$(json).each(function() {
						MCmap.initMarker(this);
					});
					MCmap.hideInfo();
				} else {
					$("#heading").text(MCmap.noHitsMessage);
				}
			});
		},
		// =================================================
		// = displays information on map (yellow top left) =
		// =================================================
		info: function(text, hideTimout) {
			var mcInfo;
			if ($("#mc-info").length === 0) {
				mcInfo = $(document.createElement("P")).attr("id", "mc-info").hide();
				$("#map_canvas").append(mcInfo);
			} else {
				mcInfo = $("#mc-info");
			}
			mcInfo.text(text + " …").show();
			if (hideTimout) {
				setTimeout(function() {
					MCmap.hideInfo();
				}, hideTimout);
			}
		},
		// ==============================================
		// = hides information on map (yellow top left) =
		// ==============================================
		hideInfo: function() {
			$("#mc-info").hide();
		},
		// =================================
		// = geocode input value below map =
		// =================================
		geocode: function(address) {
			//alert("/virtuell/sok/?q="+address);
			_gaq.push(["_trackPageview", "/virtuell/sok/?q=" + address]);
			var geocoder = new google.maps.Geocoder();
			geocoder.geocode({ "address": address + ", " + Location.country }, function(results, status) {
				if (status === google.maps.GeocoderStatus.OK) {
					MCmap.clearAllMarkers();
					MCmap.setLocation(results[0].geometry.location, 13);
				} else {
					MCmap.info("ingen sökträff", 2000);
				}
			});
		}
	};
	var slideShow = {
		pagingInterval: null,
		init: function() {
			slideShow.initPaging();
			slideShow.bind();
		},
		initPaging: function() {
			var paging = $(document.createElement("UL")).addClass("paging");
			$(".slide-show > div").each(function(index) {
				$(this).attr("id", "slide-" + index);
				var li = $(document.createElement("LI")),
				link = $(document.createElement("A"));
				link.attr({ "href": "#slide-" + index }).text("slide-" + index);
				if ($(this).is(":first-child")) {
					li.addClass("selected");
				}
				li.append(link);
				paging.append(li);
			});
			$(".slide-show").append(paging);
			slideShow.paging();
		},
		paging: function() {
			if (slideShow.pagingInterval !== null) {
				clearInterval(slideShow.pagingInterval);
			}
			slideShow.pagingInterval = setInterval(function() {
				if ($(".paging .selected").is(".paging li:last-child")) {
					$(".slide-show .paging :first-child a").trigger("auto");
				} else {
					$(".slide-show .selected").next("li").find("a").trigger("auto");
				}
			}, 7000);
		},
		bind: function() {
			$(".paging a").click(function(e) {
				e.preventDefault();
				if (!$(this).parent("li").hasClass("selected")) {
					$(".paging .selected").removeClass("selected");
					$(this).parent("li").addClass("selected");
					$(".slide-show>div").fadeOut(700);
					$($(this).attr("href")).fadeIn(700);
					slideShow.paging();
				}
			}).bind("auto", function() {
				$(".paging .selected").removeClass("selected");
				$(this).parent("li").addClass("selected");
				$(".slide-show>div").fadeOut(700);
				$($(this).attr("href")).fadeIn(700);
			});
		}
	};
	var inputFields = {
		fetch: function(jqButton) {
			var obj = {};
			$(":input").not($("button")).add(jqButton).each(function() {
				switch ($(this).attr("type")) {
					case "button":
						obj[$(":hidden[name$='EVENTTARGET']").attr("name")] = $(this).attr("name");
						obj[$(":hidden[name$='EVENTARGUMENT']").attr("name")] = "";
						if (!ie6) {
							obj[$(this).attr("name")] = "";
						}
						break;
					case "checkbox":
					case "radio":
						if (!$(this).is(":checked")) {
							break;
						}
					default:
						obj[$(this).attr("name")] = $(this).val();
						break;
				}
			});
			return obj;
		}
	};
	jQuery.fn.log = function(msg) {
		console.log("%s: %o", msg, this);
		return this;
	};
	function createCookie(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		}
		else var expires = "";
		document.cookie = name + "=" + value + expires + "; path=/";
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for (var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		createCookie(name, "", -1);
	}

	$(function() {
		if (!$("body").hasClass("print-test")) {
			if (!$("#top>.small").hasClass("test")) {
				$("#top>.small").addClass("no-test");
			}
			if (readCookie("mobile_message") === "hide") {
				$(".mobile").hide();
			}
			$(".mobile .close").click(function(e) {
				e.preventDefault();
				createCookie("mobile_message", "hide");
				$(".mobile").hide();
				$("body").addClass("hide-mobile-message");
			});
			if ($("article.test").length > 0) {
				test.init();
			}
			if ($("#map_canvas").length > 0) {
				//alert("sss");
				MCmap.init();
			}
			if ($("article.SendCOPDTestMessage").length > 0) {
				SendCOPDTestMessage.init();
			}
			if ($("fieldset.contact").length > 0) {
				//contact.init();
			}
			if ($(".slide-show").length > 0) {
				slideShow.init();
			}
			$("input[placeholder],textarea[placeholder]").setPlaceholder();
			$("#top article.medium").addClass("paperstack");
			$("#bottom article").addClass("small");
			$("#bottom .small:last-child").addClass("last-child");
			$("#bottom ul").addClass("links");
			// GA
			$("a.test-link").click(function(e) {
				e.preventDefault();
				document.location.href = $(this).attr("href") + "&FromUrl=" + document.location.href.toString().substring(7);
			});
			$("ol.themed li").each(function(i) {
				$(this).addClass("item-" + i);
			});
			$(".twitter-share-button").click(function() {
				////alert("a-aktivitet", "delat-sida", "twitter");
				_gaq.push(["_trackEvent", "a-aktivitet", "delat-sida", "twitter"]);
			});
			$(".share-email").click(function() {
				//alert("a-aktivitet", "delat-sida", "e-post");
				_gaq.push(["_trackEvent", "a-aktivitet", "delat-sida", "e-post"]);
			});
			$("a[href^='http://']").not(".share-fb, .twitter-share-button, .share-email").click(function(e) {
				//alert("/virtuell/external/"+$(this).attr("href").replace("http://",""))
				_gaq.push(["_trackPageview", "/virtuell/external/" + $(this).attr("href").replace("http://", "")]);
			});
			if ($(".SendCOPDTestMessage .bar section.medium p").length > 0) {
				_gaq.push(["_trackPageview", "/virtuell/kontakt/formular-inskickat/"], ["_trackEvent", "b-aktivitet", "kontaktat", "formular-inskickat"]);
			}
		} else {
			if ($("body.print-test").length > 0) {
				window.print();
				window.close();
			}
		}
	    // track Sent-action for Contact form
	    if(window.trackContactSent)
    	    _gaq.push(['_trackPageview', '/virtuell/kontakta-oss/fraga-inskickat/'], ['_trackEvent', 'b-aktivitet', 'kontakta-oss', 'fraga-inskickat']);
	});
} (jquery));
