﻿try {
	console.log("Initializing console...");
} catch (er) {
	console = { log: function() { } };
}
(function($) {
	$.fn.BigImageBox = function(options) {
		var container = $(this);
		var pagination = $(".pagination", this);
		var nextButton = $(".next", pagination);
		var prevButton = $(".prev", pagination);
		var paginationText = $(".text", pagination);

		var updatePagination = function() {
			container.addClass('transition');
			var images = $(".images > .image", container);
			var totalCount = images.length;
			var thisIndex = (images.index(this) + 1);
			var text = thisIndex + "/" + totalCount;
			paginationText.text(text);
		}
		var afterTransition = function() {
			container.removeClass('transition');
		}
		var settings = {
			prev: prevButton,
			next: nextButton,
			before: updatePagination,
			after: afterTransition,
			timeout: 15000
		};

		var stopCycle = function() {
			$(".images", container)[0].cyclePause = 1;
		}
		nextButton.click(stopCycle);
		prevButton.click(stopCycle);

		var images = $(".images > .image", this);
		if (images.length > 1) {
			$(".images", container).cycle(settings);
			pagination.show();
		}

	};

	$.fn.ActivityMap = function(activities) {
		var markerPath = PF.MapSprite;
		var infoPath = PF.InfoBubble;
		if ($.browser.msie && $.browser.version <= 6) {
			markerPath = markerPath.replace("_png24.png", "_png8.png");
		}
		var PinSize = { width: 41, height: 36 };
		var Anchor = { x: 15, y: 34 };
		var Positions = {
			activity: { x: 880, y: 209 },
			accommodation: { x: 930, y: 209 },
			events: { x: 980, y: 209 },
			selected: { x: 0, y: 40 }
		}

		var infoWindows = {};
		var openInfoWindow = 0;

		var mapsContainer = this;
		var mapsWidth = mapsContainer.width();
		var latlng = new google.maps.LatLng(58.75395576156743, 13.444519105468755);
		var myOptions = { center: latlng, zoom: 6,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			styles: [{
				featureType: "poi.business",
				elementType: "labels",
				stylers: [{ visibility: "off" }]
			}]
		};
		if ($(this).width() < 400)
			myOptions.mapTypeControl = false;
		var map = new google.maps.Map(mapsContainer[0], myOptions);
		var geocoder = new google.maps.Geocoder();

		var geoCode = function(place) {
			geocoder.geocode({ 'address': place }, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					map.setCenter(results[0].geometry.location);
				}
			});
		}
		var bounds = new google.maps.LatLngBounds();

		var openInfoWindow = function() {
			var marker = this;
			var url = infoPath + this.productId;
			if (openInfoWindow > 0 && typeof (infoWindows[openInfoWindow]) != 'undefined')
				infoWindows[openInfoWindow].close();
			if (typeof (infoWindows[marker.productId]) == 'undefined') {
				$.get(url, function(data, textStatus, request) {
					var infowindow = new google.maps.InfoWindow({
						content: data,
						pixelOffset: new google.maps.Size(-5, 10),
						maxWidth: 300
					});
					infoWindows[marker.productId] = infowindow;
					openInfoWindow = marker.productId;
					infowindow.open(map, marker);
				});
			} else {
				infoWindows[marker.productId].open(map, marker);
				openInfoWindow = marker.productId;
			}
		}

		var addMarker = function(m) {
			var size = new google.maps.Size(PinSize.width, PinSize.height);
			var offset = new google.maps.Point(Positions.activity.x, Positions.activity.y);
			if (typeof (Positions[m.type]) != "undefined") {
				offset.x = Positions[m.type].x;
				offset.y = Positions[m.type].y;
				if (m.selected) {
					offset.x += Positions.selected.x;
					offset.y += Positions.selected.y;
				}
			}
			var anchor = new google.maps.Point(Anchor.x, Anchor.x);
			var markerImage = new google.maps.MarkerImage(markerPath, size, offset, anchor);
			var latlng = new google.maps.LatLng(m.lat, m.lng);
			var marker = new google.maps.Marker({
				position: latlng,
				map: map,
				icon: markerImage,
				title: m.title
			});
			marker.productId = m.productId;
			bounds.extend(latlng);

			if (mapsWidth > 400)
				google.maps.event.addListener(marker, 'click', openInfoWindow);
		}

		for (var i = 0; i < activities.length; i++) {
			addMarker(activities[i]);
		}

		if (activities.length == 1) {
			map.setCenter(bounds.getCenter());
			map.setZoom(10);
		} else if (activities.length > 1) {
			map.fitBounds(bounds);
		}
	}

	$.fn.CalendarActivity = function() {
		var infoWindows = {};
		var infoWindow = false;
		var showInfoWindow = function(text, pageX, pageY) {
			if (!infoWindow) {
				infoWindow = $('<div id="infobubble"><div class="inner">' + text + '</div><span class="close"></span><span class="arrow"></span></div>');
				infoWindow.appendTo(document.body);
				$('.close', infoWindow).click(function() {
					infoWindow.hide();
				});
			} else {
				$(".inner", infoWindow).html(text);
				infoWindow.show();
			}
			var xpos = pageX - 65;
			var ypos = pageY - (infoWindow.outerHeight(true) + 73);
			infoWindow.css({
				'position': 'absolute',
				'top': ypos + "px",
				'left': xpos + "px"
			});
		}

		var ActivityClick = function(e) {
			e.preventDefault();
			var act = $(this);
			var url = $(this).attr('href');
			if (typeof (infoWindows[url]) == 'undefined') {
				$.get(url, function(data, textStatus, request) {
					infoWindows[url] = data;
					showInfoWindow(infoWindows[url], e.pageX, e.pageY);
				});
			} else {
				showInfoWindow(infoWindows[url], e.pageX, e.pageY);
			}
		}

		$("a.activity", this).click(ActivityClick);

	}



	$.fn.TrackClick = function(category, action, attrName) {
		$(this).click(function(e) {
			var val;
			if (typeof (attrName) != "undefined") {
				val = $(this).attr(attrName);
			} else {
				val = $(this).attr('href');
			}
			if (typeof (pageTracker) != "undefined" && isNaN(pageTracker)) {
				pageTracker._trackEvent(category, action + " click", val);
			}
		});
	}

	$.fn.CufonMultiLine = function() {
		this.each(function() {
			var lh = parseInt($(this).css('line-height'));
			var fz = parseInt($(this).css('font-size'));
			var height = $(this).height();
			if (height > (lh + (fz / 2))) {
				$(this).parent().addClass('multiline');
			}
		});
	}

	$.fn.ReadMore = function(selector) {
		$(this).click(function(e) {
			e.preventDefault();
			$(selector).slideDown('slow');
			$(this).hide();
		});
	}
	$.fn.ReadMoreWithLink = function(selector) {
		$(this).click(function(e) {
			e.preventDefault();
			if ($(selector + ":first").is(":hidden")) {
				$(selector).slideDown(600);
			} else {
				$(selector).slideUp(600);
			}
		});
	}

	$.fn.NewsfeedMore = function() {
		$(this).each(function() {
			var hiddenElements = $(this).parent().find(".actionList").find(".hidden");
			$(this).click(function() {
				hiddenElements.toggleClass('hidden');
				$(this).toggleClass('expandedrm');
				$(".showall").toggle();
				$(".hideall").toggle();
			}).css('cursor', 'pointer');
		});
	}

	$.fn.cbDialog = function(width, color, closeCallback) {
		var wrapper = $(this);
		var dialogClass = "dialog";
		if (typeof (color) != 'undefined')
			dialogClass += " " + color + "dialog";

		if (typeof (closeCallback) == 'undefined') {
			closeCallback = function() { };
		}

		$.fn.colorbox({ inline: true, href: wrapper, innerWidth: width + 'px', transition: "none", scrolling: false,
			onOpen: function() { $("#colorbox").addClass(dialogClass); },
			onClosed: function() { $("#colorbox").removeClass(dialogClass); $('.button', wrapper).unbind(); closeCallback(); },
			opacity: 0.65
		});
		$(".cancelbutton", this).click(function(e) {
			e.preventDefault();
			$.fn.colorbox.close();
		});

		Cufon.replace($("#cboxContent h2, #cboxContent h3"));
		$.fn.colorbox.resize();

	}

	$.fn.Rater = function(options, updateSelector) {
		var rating = 0;
		var ratelist = $(this);
		var stars = $("li", ratelist);
		var overTarget = false;
		var hoverRating = function() {
			$(this).addClass('selected');
			$(this).prevAll().addClass('selected');
			$(this).nextAll().removeClass('selected');
		};

		var clickRating = function() {
			rating = stars.index(this) + 1;
			sendRating(rating);
		};

		var sendRating = function(ratingVal) {
			options.rating = ratingVal;
			$.post(PF.SetRating, options, updateRating, 'json');
		};

		var updateRating = function(data) {
			if (typeof (data.NewAverageRating) != 'undefined' && typeof (updateSelector) != 'undefined') {
				var toUpdate = $(updateSelector);
				toUpdate.attr('title', data.NewAverageRating);
				var statusIndicators = $("span", toUpdate);
				statusIndicators.css('width', '0%');
				var fullInd = Math.floor(data.NewAverageRating);
				var partWidth = Math.round((data.NewAverageRating % 1) * 100);
				statusIndicators.slice(0, fullInd).css('width', '100%');
				statusIndicators.eq(fullInd).css('width', partWidth + "%");
			}
		}

		var keepRating = function() {
			overTarget = true;
		};

		var resetRating = function() {
			stars.removeClass('selected');
			stars.slice(0, rating).addClass('selected');

		};

		stars.mouseover(hoverRating).click(clickRating).css('cursor', 'pointer');
		$(this).hover(keepRating, resetRating);
	}

	$.fn.FreePostbackModal = function() {
		if (this.length == 0)
			return;
		$('object, select, embed').each(function() {
			if ($(this).parents('#PopUp').length > 0) {
			} else {
				$(this).css('visibility', 'hidden');
			}
		});

		$("div.modalPopUpCover").height($(document.body).height());
	}

	$.fn.HelpDialog = function() {
		$(this).click(function(e) {
			e.preventDefault();
			$.HelpDialog($(this).attr('href'));
		});
	}

	$.HelpDialog = function(url) {
		var str = "<div id='helpModal'><div class='header'><h2>" + PF.Lang.HelpHeader + "</h2></div><iframe frameborder='0' id='helpIframe' name='helpIframe' src='" + url + "' /><div class='footer'></div>";
		$.fn.colorbox({ html: str, innerHeight: '835px', innerWidth: '770px', transition: "none", scrolling: false,
			onOpen: function() { $("#colorbox").addClass("helpDialog"); },
			onClosed: function() { $("#colorbox").removeClass("helpDialog"); },
			opacity: 0.65
		});
		Cufon.replace($("#helpModal h2"));
	}

	$.fn.AjaxAndRemove = function(message) {
		return $(this).click(function(e) {
			e.preventDefault();
			var url = $(this).attr('href');
			$.get(url);
			$(this).remove();
			if (typeof (message) != "undefined") {
				$.FlashMessage(message);
			}
		});
	}

	$.FlashMessage = function(message, queue) {
		var msgBox = $("<div id='flashmessage'>" + message + "</div>");
		msgBox.hide().appendTo($("body"));
		var posy = (($(window).height() - $(msgBox).height()) / 2) + $("html").scrollTop();
		var posx = (($(window).width() - $(msgBox).width()) / 2) + $("html").scrollLeft();

		msgBox.css({ 'position': 'absolute',
			'top': posy + "px",
			'left': posx + "px",
			'z-index': '10000'
		});
		msgBox.fadeIn('slow', function() {
			msgBox.delay(3000).fadeOut('slow', function() {
				msgBox.remove();
				if (typeof (queue) != 'undefined' && queue.length > 0)
					$.FlashMessage(queue.shift(), queue);
			});
		});
	}

	$.FlashMessageQueue = function(queue) {
		if (queue.length == 0)
			return;
		$.FlashMessage(queue.shift(), queue);
	}

	$.fn.PopupAutoPosition = function() {
		var popup = $(this);
		var wrapper = popup.parent();
		var prevalign = false;
		var prevposition = 0;
		var positionBox = function(bottomalign, initial) {
			if (typeof (initial) == 'undefined')
				initial = false;
			var posy = 100;
			var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
			if (viewportHeight < popup.height()) {
				posy = wrapper.position().top;
				if (initial) {
					posy = $(document).scrollTop() + 50;
				} else {
					if (bottomalign) {
						if ((wrapper.position().top + popup.height() + 50) > ($(document).scrollTop() + viewportHeight)) {
							posy = wrapper.position().top;
						} else {
							posy = (viewportHeight + $(document).scrollTop()) - popup.height() - 50;
						}
					} else {
						if (wrapper.position().top < $(document).scrollTop()) {
							posy = wrapper.position().top;
						} else {
							posy = $(document).scrollTop() + 50;
						}
					}
				}
			} else {
				if (wrapper.position() != null && initial === true && ((wrapper.position().top + popup.height()) < ($(document).scrollTop() + viewportHeight) && wrapper.position().top > $(document).scrollTop())) {
					return;
				}
				posy = ((viewportHeight - popup.height()) / 2) + $(document).scrollTop();
			}
			var posx = 0;
			if ($(window).width() > popup.width())
				posx = (($(popup).parents(".modalPopUpContentWrapper").width() - popup.width()) / 2) + $(document).scrollLeft();

			wrapper.css({ 'top': posy + "px",
				'left': posx + "px",
				'margin-left': "0px",
				'margin-top': "0px"
			});
			prevalign = bottomalign;
		}
		var scrollPosition = function(e) {
			var curposition = $(document).scrollTop();
			var diff = (curposition - prevposition);
			var scrolldir = true;
			if (diff < 0)
				scrolldir = false;
			// Calc scroll direction
			prevposition = curposition;
			positionBox(scrolldir);
		}
		var resizePosition = function(e) {
			positionBox(prevalign);
		}


		$(window).scroll(scrollPosition);
		$(window).resize(resizePosition);
		positionBox(true, true);
	}

	$.fn.MenuNotificationBubble = function() {
		$(this).each(function() {
			var bubble = $(this);
			var menuitem = bubble.parent();
			menuitem.addClass('hover');
			var pos = bubble.offset();
			menuitem.removeClass('hover');
			bubble.hide().appendTo(document.body);
			bubble.css({ 'position': 'absolute',
				'top': pos.top + "px",
				'left': pos.left + "px",
				'z-index': 10000
			});
			menuitem.hover(function() {
				bubble.show();
			},
			function() {
				bubble.hide();
			});
		});
	}

	$.fn.LabelExample = function() {
		var labelClick = function() {
			$(this).prev('input').focus();
		}

		var inputFocus = function() {
			$(this).next('.example').hide();
		}

		var inputBlur = function() {
			if ($(this).val() == '') {
				$(this).next('.example').show();
			}
		}

		var createExample = function(element) {
			var input = $(element);
			var label = $("<span class='example' title='" + input.attr('title') + "'>" + input.attr('title') + "</span>");
			var positionLabel = function() {
				var position = input.position();
				var top = "1px";
				var left = "1px";
				label.css({ 'position': 'absolute',
					'top': top,
					'left': left,
					'padding-left': input.css('padding-left'),
					'padding-right': input.css('padding-right'),
					'padding-top': input.css('padding-top'),
					'padding-bottom': input.css('padding-bottom'),
					'line-height': input.height() + "px",
					'font-size': input.css('font-size'),
					'height': input.height() + "px",
					'width': input.width() + "px",
					'overflow': 'hidden'
				});
			}

			if (input.val() != '')
				label.hide();

			input.wrap("<div />").parent().css({ 'position': 'relative',
				'float': input.css('float')
			});
			label.insertAfter(input);
			label.click(labelClick);
			input.blur(inputBlur).focus(inputFocus).blur();
			positionLabel();
		}


		$(this).each(function() {
			var title = $(this).attr('title');
			if (title.length > 0) {
				createExample(this);
			}
		});
	}

	
	$.fn.ImageScroller = function() {
		var imagecontainer = $(this);
		var mainimage = $('img.mainimage', imagecontainer);
		$('div.thumb:first-child', imagecontainer).addClass('activethumb');
		
		$('div.thumb', imagecontainer).click(function () {
			$('div.thumb', imagecontainer).removeClass('activethumb');
			$(this).addClass('activethumb');
			var src = $(this).children('input').val();
			var title = $(this).children('img').attr('title');
			mainimage.attr('src', src);
			mainimage.attr('title', title);
		});
	}

	$.fn.CloseDiv = function() {
		$(this).click(function () {
			$('#addFriendMsg').addClass('hidden');
			$('#addFriendPopUpCover').addClass('hidden');
		});
	}

	$.fn.CloseDivCard = function() {
		$(this).click(function () {
			$('#addFriendMsgCard').addClass('hidden');
			$('#addFriendPopUpCoverCard').addClass('hidden');
		});
	}

	/* Custom jquery selectors */
	$.expr[':'].external = function(obj) {
		return obj.href.length > 0 && !obj.href.match(/^mailto\:/) // Ignore mail links
			&& !obj.href.match(/^javascript\:/) // Ignore webforms postback links
            && (obj.hostname != location.hostname);
	};
	$.expr[':'].notarget = function(obj) {
		var $this = $(obj);
		return ($this.attr('target') == '');
	};
})(jQuery);



$(function() {
	var loginlink = $('#toplogininfo a.loginlink');
	if (loginlink) {
		$('a.needlogin').attr('href', loginlink.attr('href'));
	}

	$('#AdsBody a').TrackClick("Annonser", "Banner", 'title');
	$('a.trackclick').TrackClick("Annonser", "Kampanj", 'title');
	$('input[type="text"]').addClass('inputText');
	$('input[type="radio"]').addClass('inputRadio');
	$('input[type="password"]').addClass('inputPassword');
	$('input[title]').LabelExample();
	$('select').uniform();
	$('input:radio').uniform();
	$('input:checkbox').uniform();
	$('input.datepicker').datepicker({ defaultDate: 0, minDate: 0 });
	$('input.datepicker').siblings(".icon").css('cursor', 'pointer').click(function() {
		$(this).siblings('input.datepicker').focus();
	});
	/* Set all external links to open in new window */
	$('a:external:notarget').attr('target', '_blank');
	$('#LargeCalendar').CalendarActivity();
	$('#RightContentArea h2').CufonMultiLine();
	$('div.modalPopUpHost:visible').FreePostbackModal();
	$('a.helplink').HelpDialog();
	$('a.remindlink').AjaxAndRemove(PF.Lang.SentReminder).show();
	$("#PopUp").PopupAutoPosition();

	if (typeof (PF.ToRate) != 'undefined') {
		$(PF.ToRate).each(function() {
			$(this.selector).Rater(this.settings, this.update);
		});
	}

	$("#MainMenu ul.main li .speechbubble").MenuNotificationBubble();
	$.FlashMessageQueue(PF.MessageQueue);

	// Imagescroller
	$('#blogImagesContainer').ImageScroller();

	// Close friend request popup
	$('#addFriendMsgClose').CloseDiv();
	$('#addFriendMsgCloseCard').CloseDivCard();

	if ($.browser.msie && $.browser.version <= 6) {
		$("#MainMenu ul.main .side").removeClass('side').addClass('side');
		$("#MainMenu ul.main li").hover(function() {
			$(this).addClass("hover");
			if ($(this).hasClass('first'))
				$(this).addClass('firsthover');
		},
		function() {
			$(this).removeClass("hover");
			$(this).removeClass("firsthover");
		});
		$("#MainMenu ul.main li").mousedown(function() {
			$(this).addClass('active');
			if ($(this).hasClass('first'))
				$(this).addClass('firstactive');
		}).mouseup(function() {
			$(this).removeClass('active');
			$(this).removeClass('firstactive');
		}).mouseout(function() {
			$(this).removeClass('active');
			$(this).removeClass('firstactive');
		});
		var radiocount = 0;
		$("ul.radiolist label").each(function() {
			if ($(this).attr('for').length == 0) {
				$(this).attr('for', 'radiolistitem' + radiocount);
				$("input", this).attr('id', 'radiolistitem' + radiocount);
				radiocount++;
			}
		});
		$("img[align='right']").css('float', 'right');
	}
});
