﻿(function ($) {
	var ieQuirks = $.browser.msie && !$.boxModel;

	var returnurl;

	var io = document.URL.indexOf("ReturnUrl=");
	if (io != -1)
		returnurl = document.URL.substring(parseInt(io) + 13);

	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

	try {
		var pageTracker = _gat._getTracker("UA-10454320-1");
		pageTracker._trackPageview();
	} catch (err) { }

	$(document).ready(function () {
		$("input:checkbox").loveliicheck();
		$("input.integer").validate({ 'type': 'numeric' });
	});

	$.fn.validate = function (options) {
		var defaults = {
			type: 'numeric'
		};
		var opts = $.extend(defaults, options);
		return this.each(function () {
			switch (opts.type) {
				case 'numeric':
					$(this).keypress(function (e) {
						if (e.which != 13 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
							e.preventDefault();
						}
					});
					break;
			}
		});
	};

	$.fn.watermark = function(text) {		
		return this.each(function() {
			var t = $(this);
			if (t.val().length == 0)
				t.val(text);
			t.focus(function() {
				if (t.val() == text)
					t.val("");
			});
			t.blur(function() {
				if ($.trim(t.val()).length == 0)
					t.val(text);
			});
		});
	};

	Array.prototype.remove = function (name, value) {
		var rest = $.grep(this, function (item) {
			return (item[name] !== value); // <- You may or may not want strict equality
		});

		this.length = 0;
		this.push.apply(this, rest);
		return this; // <- This seems like a jQuery-ish thing to do but is optional
	};

	$.isEmail = function (value) {
		var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
		if (!filter.test(value))
			return false;
		return true;
	}

	$.fn.loveliiselect = function (options) {
		var defaults = {
			containercss: 'loveliilist',
			maxwidth: 0,
			columns: 5,
			canslide: true
		};
		var options = $.extend(defaults, options);
		return this.each(function () {
			var e = $(this);
			e.hide();
			var inner;
			var l = $("label[for='" + e.attr("id") + "']");
			if (options.canslide) {
				if (l != null) {
					l.hide();
					var labelc = $("<div>" + l.text() + "</div>").css("margin-left", "10px");
					l.replaceWith(labelc);
					inner = $("<div></div>").addClass("inner");
					labelc.before($("<div></div>").addClass("loveliicheck").append(inner));
					labelc.addClass("listlabel").click(function () {
						lc.slideToggle();
					});
				}
				setStyle(inner, e);
			}

			var lc = $("<div>").addClass(options.containercss);

			if (options.maxwidth != 0)
				lc.css("width", options.maxwidth);

			e.parent().append(lc);
			var cw = parseInt((lc.width() / options.columns) - 10);
			e.children().each(function () {
				var option = $(this);
				var o = $("<div class='listelement'>" + $(this).text() + "</div>").css("width", cw + "px");
				if ($(this).attr("selected"))
					o.addClass("selected");
				o.click(function () {
					option.attr("selected", !option.attr("selected"));
					o.toggleClass("selected");
					if (options.canslide)
						setStyle(inner, e);
				});
				lc.append(o);
			});
		});

		function setStyle(i, e) {
			e.children(":selected").length == 0 ? i.removeClass("checked") : i.addClass("checked");
		}
	}

	$.fn.loveliicheck = function (options) {
		var defaults = {
			containercss: 'loveliicheck'
		};
		var options = $.extend(defaults, options);
		return this.each(function () {
			var chk = "checked";
			var e = $(this).hide();
			var c = $("<div></div>").attr("class", e.attr("class")).addClass(options.containercss);
			e.hide().after(c);
			var inner = $("<div></div>");
			if (e.attr(chk))
				inner.addClass(chk);
			c.click(function () {
				inner.toggleClass(chk);
				e.trigger("click");
			}).append(inner);
			e.change(function () {
				inner.toggleClass(chk);
				if (e.attr("checked")) {
					e.removeAttr("checked");
				}
				else
					e.attr("checked", "on");
			})
		});
	}

	$.fn.loveliihoverprofile = function (u) {
		var e = $(this);
		var interval = null;
		e.mouseenter(function () {
			interval = setInterval(showtip, 100);
		});
		e.mouseleave(function () {
			clearInterval(interval)
			var d = $("#loveliitip");
			d.fadeOut(100, function () {
				d.remove();
			});
		});

		function showtip() {
			var ul = $("<ul>").append("<li>" + u.u + "</li>");
			var content = $("<div>").append(ul);

			if (u.a != null)
				ul.append("<li>" + u.a + " år</li>");

			if (u.area != null)
				ul.append("<li>Fra " + u.area + "</li>");

			var os = e.offset();
			var d = null;
			if ($("#loveliitip").length == 0) {
				d = $("<div/>", { "id": "loveliitip" }).hide();
				d.html(content).css("left", (os.left - (e.width() / 2))).css("top", os.top - 120);
				d.append("<img src='/content/images/tipbottom.png'>");
				$("body").append(d);
				d.fadeIn(200);
			}
		}
	}

	$.fn.loveliidropdown = function (options) {
		var defaults = {
			containercss: 'loveliidropdowncontainer',
			dropcss: 'loveliidropdown',
			items: ''
		};
		var options = $.extend(defaults, options);
		return this.each(function () {
			var e = $(this);
			var w = parseInt(e.css("width").replace("px", ""));
			if (e.attr("multiple"))
				return;
			e.hide();
			var con = $("<div class='" + options.containercss + "' />").css("width", (w + 5) + "px").css("border", e.css("border"));

			e.after(con);

			var d = $("<input readonly type='text'>").css("height", "26px").css("line-height", "26px").val(e.children(":selected").text());
			con.append(d).append($("<div />").addClass("dropmarker").css("left", e.width() - 20));
			d.css("width", w - 30 + "px");

			var drop = $("<div></div>").addClass(options.dropcss);
			$("body").append(drop);

			d.keydown(function (k) {
				if (k.which == 9)
					drop.hide();
				if (k.which == 27)
					drop.hide();
				if (k.which == 40) {
					if (e.attr("selectedIndex") < e.children().length) {
						e.attr("selectedIndex", e.attr("selectedIndex") + 1);
						d.val(e.find(":selected").text());
					}
				}
				if (k.which == 38) {
					if (e.attr("selectedIndex") != 0) {
						e.attr("selectedIndex", e.attr("selectedIndex") - 1);
						d.val(e.find(":selected").text());
					}
				}
			})
			d.keyup(function (k) {
				if (k.which == 18)
					dropdown(drop, d, e);
			});
			con.click(function () {
				if (drop.css("display") != "none") {
					drop.hide();
				}
				else {
					dropdown(drop, d, e);
				}
			});
		});

		function dropdown(drop, d, e) {
			$("." + options.dropcss).hide();
			if (drop.children().length != 0) {
				drop.children().remove();
			}
			e.children("[selected=false]").each(function (index, i) {
				if (!$(i).attr("disabled")) {
					var item = $("<div>" + $(this).text() + "</div>");
					drop.append(item.click(function () {
						e.val($(i).attr("value"));
						d.val(item.text()).focus();
						e.trigger("change");
						drop.hide();
					}));
				}
			});
			var t = d.offset().top - $(window).scrollTop();
			var b = ($(window).height() - t) - d.height();
			var offset = d.parent().offset();
			var p = offset.top;
			if (b < 300 && b < t) {
				if (drop.height() > t)
					drop.css("height", t - 20);
				drop.css("top", p - drop.height() - 9);
				if (drop.height() > t)
					drop.height(t - 40);
			}
			else {
				p += d.height();
				drop.css("top", p);
				if (drop.height() > b)
					drop.height(b - 40);
			}
			drop.css("width", d.parent().innerWidth());
			drop.css("width", drop.width() - (drop.innerWidth() - drop.width()));
			drop.css("left", offset.left);
			drop.show();
		}

		// dc = dropcontainer, d = dropcontainer s = screen realestate left		
		function setHeight(dc, d, s, it) {
			if (d.height() > s)
				d.css("height", s - 20);
			drop.css("top", dc.offset.top - d.height() - 9);
		}
	}

	$.fn.profilescroller = function (options) {
		var defaults = {
			images: '',
			islinked: true
		};
		var options = $.extend(defaults, options);
		return this.each(function (i, item) {
			$(options.images).each(function (index, u) {
				$(item).append($.loveliithumbuser(u, {
					islinked: options.islinked
				}));
			});
		});
	}

	$.loveliithumbuser = function (u, options) {
		var defaults = {
			islinked: true,
			hashoverinfo: true
		};
		var opts = $.extend(defaults, options);
		var lt = $.loveliithumb(u.ii, u.g);

		var app = lt;

		if (opts.islinked) {
			var a = $("<a></a>").attr("href", "/profiles/" + u.u.toLowerCase());
			app = a.append(lt);
		}

		if (opts.hashoverinfo)
			app.loveliihoverprofile(u);
		return app;
	}

	$.loveliithumb = function (id, g, options) {
		var defaults = {
			isactive: true,
			small: false
		};
		var options = $.extend(defaults, options);
		var itc = $("<div>", { "class": "imagethumbcontainer" });
		var ic = $("<div>", { "class": "imagethumb" });
		itc.append(ic);
		if (options.small) {
			ic.addClass("small");
		}
		var profilepath = getbygender(g);

		var image = new Image();
		var img = $(image);
		if (id == null) {
			ic.append("<img src='" + profilepath + "'>");
			return itc;
		}

		var i = $("<img>");

		ic.append(i);

		profilepath = "/content/userimages/thumbs/" + id + ".jpg";

		img.load(function () {
			ic.append(i.attr("src", profilepath));
		});
		img.error(function () {
			ic.append(i.attr("src", getbygender(g)));
		});
		img.attr("src", profilepath);
		return itc;

		function getbygender(g) {
			var p = "/content/images/femalethumb.png";
			if (g != null && g == 1)
				p = "/content/images/malethumb.png";
			return p;
		}
	}

	$.loveliiminiprofile = function (u, options) {
		var mp = $("<div class='miniprofile'>");

		var defaults = {
			visitdate: null
		};
		var options = $.extend(defaults, options);

		mp.append($.loveliithumb(u.ii, u.g, { isactive: u.ia }).click(function () {
			window.location = "/profiles/" + u.u.toLowerCase();
		}));

		var mpm = $("<div class='miniprofilemain'>");
		var ul = $("<ul>");

		var li = $("<li>");
		if (u.io)
			li.append($("<div class='onlinebullet'>"));
		li.append("<a href='/profiles/" + u.u.toLowerCase() + "'>" + (u.u.length > 14 ? u.u.substr(0, 14) + ".." : u.u) + "</a>");
		ul.append(li);

		var as = "";

		if (u.a != null)
			as = u.a + " " + res.Year;
		if (u.a != null && u.g != null)
			as += ", ";
		if (u.g != null)
			as += u.g == 1 ? "mand" : "kvinde";
		if (as.length != 0)
			ul.append("<li>" + as + "</li>");

		if (u.area != null)
			ul.append("<li>Fra " + u.area + "</li>");

		mpm.append(ul);

		if (options.visitdate != null)
			mpm.append("<div class='miniprofilevisit'>" + $.settimestamp(options.visitdate) + "</li>");

		return mp.append(mpm);
	}

	$.fn.loveliimenu = function (options) {
		var e = $(this);
		var defaults = {
			containersub: "containersubmenu",
			menu: '',
			authorized: true
		};
		var options = $.extend(defaults, options);
		return this.each(function () {
			var u = $("<ul></ul>");
			$(options.menu).each(function (key) {
				var m = options.menu[key]
				var l = $("<li></li>");
				var a = $("<a>" + m.N + "</a>").addClass("menu").attr("href", "#");
				if (m.NA == 0 && !options.authorized)
					a.addClass("authorize").addClass("lock");
				else {
					a.attr("href", m.P);
					if (options.authorized) {
						if (m.I)
							buildsubmenu(options.containersub, m.SMI);
						l.hoverIntent(function () {
							buildsubmenu(options.containersub, m.SMI);
						}, function () { });
					}
				}
				l.append(a);
				u.append(l);
			});
			e.append(u);
		});
	}

	$.fn.buildmail = function (options) {
		var defaults = {
			containercss: 'loveliicheck'
		};
		var options = $.extend(defaults, options);
		return this.each(function () {

		});
	}

	var dragging = false;

	$.fn.buildimage = function (options) {
		var defaults = {
			image: null,
			onSelected: function () { },
			onDelete: function () { },
			onBuilt: function () { },
			isme: false
		};
		var options = $.extend(defaults, options);
		var cx, cy, current = null;
		return this.each(function () {
			var e = $(this);
			var i = options.image;
			var ic = $("<div />").addClass("imagecontainer");
			var image = new Image();
			var img = $(image);
			img.load(function () {
				var imgc = $("<div/>").css("background-image", "url(/content/userimages/thumbs/" + i + ".jpg)").addClass("imagethumb").css("width", image.width).css("height", image.height);
				ic.append(imgc);
				if (options.isme) {
					var ifc = $("<div />").addClass("containerdelete");
					ifc.append($("<a>Slet</a>").attr("href", "#").click(function () {
						$.loveliimessagebox("Er du sikker på du vil slette dette billede?", {
							onTrue: function () {
								$.post("/Images/DeleteImage", { guid: i }, function (result) {
									if (typeof options.onDelete == 'function') {
										options.onDelete(result);
									}
									ic.fadeOut("fast");
								});
							}
						});
						return false;
					}));
					imgc.append(ifc);
					imgc.mouseenter(function () {
						if (!dragging)
							ifc.fadeTo("fast", 0.8);
					});
					imgc.mouseleave(function () {
						ifc.fadeTo("fast", 0.01);
					});
				}
				e.append(ic);
				if (typeof options.onBuilt == 'function')
					options.onBuilt(imgc, i);
			});
			img.attr("src", "/content/userimages/thumbs/" + i + ".jpg");
		});
	}

	$.fn.loveliidragable = function (options) {
		var defaults = {
			onDrag: function () { },
			onDropped: function () { }
		};
		var options = $.extend(defaults, options);
		var mid = false, x, y
		return this.each(function () {
			$(this).each(function (index, m) {
				var elem = $(this);
				elem.mousedown(function (e) {
					current = elem;
					x = e.pageX;
					y = e.pageY;
					mid = true;
					elem.bind("mousemove", createdragableclone);
				});
				elem.mouseup(function () {
					mid = false;
				});
			});
		});

		function createdragableclone(e) {
			if (mid) {
				if (e.pageX != x || e.pageY != y) {
					dragging = true;
					current.unbind("mousemove");
					var c = $(current).clone();
					c.find("div").remove();
					c.css("position", "absolute").fadeTo(0, 0.8);
					$(document.body).append(c);
					if (typeof options.onDrag == 'function')
						options.onDrag();
					$(document.body).mouseup(function (ex) {
						dragging = false;
						$(document.body).unbind("mouseup").unbind("mousemove");
						c.remove();
						if (typeof options.onDropped == 'function')
							options.onDropped(ex);
						return false;
					});
					$(document.body).mousemove(function (e) {
						c.css("top", e.pageY);
						c.css("left", e.pageX);
						return false;
					});
				}
			}
			return false;
		}
	}

	$.fn.buildguestbook = function (options) {
		var defaults = {
			messages: null,
			isme: false
		};
		var options = $.extend(defaults, options);
		var cx, cy, current = null;
		return this.each(function () {
			var e = $(this);
			$(options.messages).each(function (index, m) {
				e.addguestbookmessage({ message: m, isme: options.isme });
			});
		});
	}

	$.fn.addguestbookmessage = function (options) {
		var defaults = {
			message: null,
			isme: false,
			onDeleted: function () { }
		};
		return this.each(function () {
			var m = options.message;
			var e = $(this);
			var gbc = $("<div></div>").css("margin-bottom", "5px");
			gbc.append($("<div></div>").addClass("gbimagecontainer").loveliithumb(m.PI, { isactive: m.IA }));
			var mc = $("<div></div>").addClass("gbmessagecontainer").text("Skrevet af: ").append($("<a>" + m.U + "</a>").attr("href", "/profiles/" + m.U)).append(" <span>Klokken " + m.C + "</span>");
			mc.append($("<div>" + m.B + "</div>").css("margin-top", "10px"));
			if (options.isme) {
				mc.append($("<div></div>").css("margin-top", "10px").append($("<a href='#'>Slet besked</a>").click(function () {
					$.post("/guestbook/delete", { id: m.I }, function () {
						if (typeof options.onDeleted == 'function')
							options.onDeleted(m);
					});
					gbc.hide();
				})));
			}
			gbc.append(mc);
			e.prepend(gbc);
		});
	}

	$.fn.buildbackdragger = function (options) {
		var defaults = {
			image: null,
			onSelected: function () { },
			onCompleted: function () { },
			onDragEnd: function () { }
		};
		var options = $.extend(defaults, options);
		var cx, cy, backx, backy, current = null;
		return this.each(function () {
			var e = $(this);
			var i = options.image;
			var ip = "/content/userimages/thumbs/" + i.I + ".jpg";

			var tc = $("<div></div>").addClass("profilethumbimage");

			// Load Image
			var image = new Image();
			var img = $(image);
			img.load(function () {
				tc.css("background-image", "url(" + ip + ")").css("cursor", "move").css("background-position", "-" + i.L + "px -" + i.T + "px");
				tc.mouseover(function (e) {
				});
				tc.mousedown(function (e) {
					if (typeof options.onSelected == 'function')
						options.onSelected(i);
					current = image;
					sc(e);
					tc.bind("mousemove", dragBackground);
					return false;
				});
				tc.mouseup(function () {
					tc.unbind("mousemove", dragBackground);
					if (typeof options.onDragEnd == 'function')
						options.onDragEnd(backx, backy);
					return false;
				});
				tc.mouseleave(function () {
					tc.trigger("mouseup");
					return false;
				});
				if (typeof options.onCompleted == 'function')
					options.onCompleted(options.image);
			});
			img.attr("src", ip);
			e.append(tc);
		});

		function sc(e) { cx = e.pageX; cy = e.pageY; }

		function dragBackground(e) {
			var bp = "background-position";
			var a = $(this).css(bp).replace(/px/g, "").split(" ");
			var x = parseInt(a[0]), y = parseInt(a[1]);
			var xw = current.width - $(this).width();
			var yw = current.height - $(this).height();
			if (e.pageX > cx)
				x += e.pageX - cx;
			if (e.pageX < cx)
				x -= cx - e.pageX;
			if (e.pageY > cy)
				y += e.pageY - cy;
			if (e.pageY < cy)
				y -= cy - e.pageY;
			if (x > xw) { x = xw; }

			if (x < (xw - (xw * 2))) x = xw - (xw * 2)
			if (x >= 0) x = parseInt(a[0]);
			if (y > yw) y = yw;
			if (y < (yw - (yw * 2))) y = yw - (yw * 2)
			if (y >= 0) y = parseInt(a[1]);

			$(this).css(bp, x + "px " + y + "px");

			backx = x;
			backy = y;
			cx = e.pageX;
			cy = e.pageY;

			return false;
		}
	}

	$.loveliimessage = function (message, options) {
		var ct = false;
		var defaults = {
			timer: 3000,
			animate: false,
			overlaycloses: true
		};
		var options = $.extend(defaults, options);
		$.loveliimodal({
			container: $("<div>" + message + "</div>"),
			width: 400,
			height: 60,
			onClose: function () {
				ct = true;
			},
			showoverlay: true,
			animate: options.animate,
			dialogclass: "loveliimessage",
			overlaycloses: options.overlaycloses
		});
		if (options.timer != 0) {
			window.setTimeout(function () {
				if (!ct)
					$.loveliimodal.close();
			}, options.timer);
		}
	}

	$.loveliimessagebox = function (message, options) {
		var ct = false;
		var defaults = {
			onTrue: function () { },
			onFalse: function () { },
			labelTrue: "Ja",
			labelFalse: "Nej",
			showLabelFalse: true,
			height: 110,
			width: 400
		};
		var options = $.extend(defaults, options);
		var c = $("<div></div>");
		var mc = $("<div class='standard'>" + message + "</div>");
		c.append(mc);
		var bc = $("<div style='text-align: center;' />");
		c.append(bc);
		bc.append($("<button>" + options.labelTrue + "</button>").click(function () {
			$.loveliimodal.close();
			if (typeof options.onTrue == 'function')
				options.onTrue();
		}));
		if (options.showLabelFalse) {
			bc.append($("<button>" + options.labelFalse + "</button>").click(function () {
				$.loveliimodal.close();
				if (typeof options.onFalse == 'function')
					options.onFalse();
			}));
		}
		$.loveliimodal({
			container: c,
			width: options.width,
			height: options.height,
			showoverlay: true,
			animate: options.animate,
			dialogclass: "loveliimessagebox",
			overlaycloses: options.overlaycloses
		});
	}

	$.loveliitouch = function (options) {
		return $.loveliitouch.impl.init(options);
	};

	$.loveliitouch.defaults = {
		onComplete: new Array(),
		intervalId: 0
	};

	$.loveliitouch.register = function (fn) {
		$.loveliitouch.impl.register(fn);
	};

	$.loveliitouch.stop = function () {
		$.loveliitouch.impl.stop();
	};

	$.loveliitouch.runatonce = function () {
		$.loveliitouch.impl.stop();
		$.loveliitouch.impl.run();
		$.loveliitouch.impl.start();
	};

	$.loveliitouch.impl = {
		opts: null,
		init: function (options) {
			opts = $.extend({}, $.loveliitouch.defaults, options);
			this.start();
		},
		start: function () {
			opts.intervalId = setInterval(function () {
				$.loveliitouch.impl.run();
			}, 10000)
		},
		run: function () {
			$.getJSON("/mail/touch", {}, function (data) {
				if (typeof opts.onComplete == 'object') {
					for (var i = 0; i < opts.onComplete.length; i++) {
						opts.onComplete[i](data);
					}
				}
			}, "json");
		},
		stop: function () {
			clearInterval(opts.intervalId);
		},
		register: function (fn) {
			//opts.onComplete.push(fn);
		}
	};

	$.loveliimodal = function (options) {
		return $.loveliimodal.impl.init(options);
	};

	$.fn.loveliimodal = function (options) {
		return this.click(function () { $.loveliimodal.impl.init(this, options) });
	};

	$.loveliimodal.defaults = {
		container: null,
		height: 400,
		width: 470,
		onClose: function () { },
		showoverlay: true,
		overlayclass: "loveliimodaloverlay",
		dialogclass: "loveliimodal",
		overlaycloses: true
	};

	$.loveliimodal.close = function () {
		$.loveliimodal.impl.close();
	};

	$.sendletter = function (t, b, options) {
		var defaults = {
			onSuccess: function () { }
		};
		var options = $.extend(defaults, options);
		b = jQuery.trim(b);
		if (b.length == 0) {
			$.jGrowl("Det giver ikke megen mening at sende tomme beskeder?");
			return;
		}
		$.post("/mail/sendletter", { id: t, body: b }, function (result) {
			if (!result)
				$.jGrowl(result, { life: 20000 });
			else {
				if (typeof options.onSuccess == 'function')
					options.onSuccess(result);
			}
		}, "json");
	};

	var resources;

	$.setresource = function (resource) {
		resources = resource;
	};

	$.loveliimodal.impl = {
		opts: null,
		init: function (options) {
			opts = $.extend({}, $.loveliimodal.defaults, options);
			this.create();
		},
		close: function () {
			if (typeof opts.onClose == 'function')
				opts.onClose();
			if (!opts.animate)
				dialog.hide();
			else
				dialog.fadeOut(500);
			overlay.hide();
		},
		overlay: {},
		dialog: {},
		create: function () {
			var w = $(document).width(), h = $(document).height();
			if (ieQuirks)
				w = $('body').attr('clientWidth'), h = $('body').attr('clientHeight')
			overlay = $('<div/>', {
				"class": opts.overlayclass,
				css: {
					height: h,
					width: w
				}
			});

			dialog = $('<div/>', {
				"class": opts.dialogclass,
				css: {
					height: opts.height + "px",
					width: opts.width + "px",
					top: ($(window).height() / 2) - opts.height / 2,
					left: (w / 2) - opts.width / 2
				}
			});
			overlay.appendTo("body");
			if (opts.overlaycloses)
				overlay.click(destroy);
			opts.container.show().appendTo(dialog);
			dialog.appendTo("body");

			function show() {
				if (opts.showoverlay)
					overlay.show();
				dialog.fadeIn(500);
			}

			function destroy() {
				overlay.hide();
				dialog.hide();
			}
			show();
		}
	};

	$.getdatefromjson = function (datetime) {
		var d = datetime.toString().substr(0, 2);
		var mm = parseInt(datetime.toString().substr(2, 2) - 1, 10);
		var y = parseInt(20 + datetime.toString().substr(4, 2), 10);
		var h = datetime.toString().substr(6, 2);
		var m = datetime.toString().substr(8, 2);
		var s = datetime.toString().substr(10, 2);
		return new Date(y, mm, d, h, m, s);
	}

	var res = { "Year": "år", "Years": "år", "Month": "måned", "Months": "måneder", "Day": "dag", "Days": "dage", "Hour": "time", "Hours": "hours", "Minute": "minut", "Minutes": "minutter", "Second": "sekund", "Seconds": "sekunder", "Ago": "siden", "JustPosted": "Lige blevet postet" }

	$.settimestamp = function (jsondatevalue) {
		var mili = new Date(new Date() - $.getdatefromjson(jsondatevalue)).getTime(), sec = Math.floor(mili / 1000), min = Math.floor(sec / 60), hour = Math.floor(min / 60), day = Math.floor(hour / 24), month = Math.floor(day / 31), year = Math.floor(day / 365);
		ra = res.Ago;
		if (year == 1) return sts(res.Year);
		if (year > 1) return year + " " + res.Years + " " + ra;
		if (month == 1) return sts(res.Month);
		if (month > 1) return month + " " + res.Months + " " + ra;
		if (day == 1) return sts(res.Day);
		if (day > 1) return day + " " + res.Days + " " + ra;
		if (hour == 1) return sts(res.Hour);
		if (hour > 1) return hour + " " + res.Hours + " " + ra;
		if (min == 1) return sts(res.Minute);
		if (min > 1) return min + " " + res.Minutes + " " + ra;
		if (sec == 1) return sts(res.Second);
		if (sec > 1) return sec + " " + res.Seconds + " " + ra;
		if (sec <= 1) return res.JustPosted;
		function sts(value) { return "1 " + value + " " + ra; }
	}

	$.initprofileimages = function (token, userimages, currentpi) {
		$('#fileupload').uploadify({
			'uploader': '/scripts/uploadify.swf',
			'scriptData': { token: token },
			'script': '/images/uploadprofileimage',
			'auto': true,
			'wmode': 'transparent',
			'hideButton': true,
			'height': 30,
			'width': 250,
			'multi': false,
			'onSelect': function (e, id, file) {
				$.loveliimessage("Uploader billedet", {
					timer: 0,
					animate: true,
					overlaycloses: false
				});
				return false;
			},
			'onError': function (e, id, file, err) {
				alert(err.info);
			},
			'onComplete': function (e, id, file, response, data) {
				var g = eval(response);
				var path = "/content/userimages/medium/" + g + ".jpg";
				var image = new Image();
				var img = $(image);
				img.load(function () {
					var cb = $("<img id='cropbox'>");
					cb.attr("src", path);

					if (!$.browser.msie)
						cb.attr("height", image.naturalHeight).attr("width", image.naturalWidth);

					$.loveliimodal.close();

					$("#profileimageoverview").fadeOut(200, function () {
						$("#cropcontainer").fadeIn(300, function () {
							$(this).find(".largeimagecontainer").append(cb);
							var cropapi = $.Jcrop('#cropbox', {
								aspectRatio: 3 / 4,
								onSelect: setCoords,
								onChange: setCoords
							});
							var x = 0, y = 0, w, h;

							w = cb.width();
							h = cb.height();
							if (w > h) {
								h -= 10;
								y = 5;
								w = h * 0.75;
								x = (cb.width() - w) / 2;
							}
							cropapi.setSelect([x, y, w, h]);

							function setCoords(c) {
								x = c.x;
								y = c.y;
								w = c.w;
								h = c.h;
							}

							$("#savecroppedimage").fadeIn(500).click(function () {
								$.post("/images/cropimage", { id: g, x: x, y: y, w: w, h: h }, function (ui) {
									$("#savecroppedimage").unbind("click");
									if (currentpi != null)
										buildimage(currentpi);
									setprofileimage(ui);
									currentpi = ui;
									cropapi.destroy();
									$("#cropcontainer").fadeOut(200, function () {
										cb.remove();
										$("#profileimageoverview").fadeIn(400);
									});
								}, "json");
							});
						});
					});
				});
				img.attr("src", path);
			}
		});

		currentpi = getimage(currentpi);

		$.each(userimages, function (index, ui) {
			var b = true
			if (currentpi != null && currentpi.i == ui.i)
				b = false;
			if (b)
				buildimage(ui);
		});

		function getimage(id) {
			var retval = null;
			$.each(userimages, function (index, ui) {
				if (ui.i == id) {
					retval = ui;
					return;
				}
			});
			return retval;
		}

		function buildimage(ui) {
			var it = $.loveliithumb(ui.i, 1);
			it.mouseenter(function () {
				var tf = $("<div class='thumbfunctions'>");
				tf.append($("<a href=''>SLET</a>").click(function (e) {
					e.preventDefault();
					$.loveliimessagebox("Er du sikker på du vil slette dette billede?", {
						onTrue: function () {
							$.post("/images/deleteimage", { guid: ui.i }, function (result) {
								if (typeof options.onDelete == 'function') {
									options.onDelete(result);
								}
							});
							it.fadeOut("fast");
						}
					});
				}));
				tf.append($("<a href=''>ANVEND</a>").click(function (e) {
					e.preventDefault();
					$.loveliimessagebox("Er du sikker på du vil anvende dette billede?", {
						onTrue: function () {
							var newpi;
							$.post("/images/setprofileimage", { id: ui.i }, function (result) {
								setprofileimage(result);
								it.fadeOut(300, function () {
									buildimage(currentpi);
									currentpi = result;
								});
							}, "json");
						}
					});
				}));

				it.append(tf);
				tf.css("width", it.width() + "px");
			});
			it.mouseleave(function () {
				it.find(".thumbfunctions").remove();
			});
			$("#currentprofileimages").append(it.hide());
			it.fadeIn(300);
		}

		function setprofileimage(ui) {
			$("#largeprofileimage").css("background-image", "url('/content/userimages/profilelarge/" + ui.i + ".jpg')");
			checklargeoptions();
		}

		function checklargeoptions() {
			var lp = $("#largeprofileimage");
			if (lp.css("background-image").indexOf("userimages") != -1) {
				lp.mouseenter(function () {
					var con = $("<div class='thumbfunctions'>");
					con.css("width", lp.width()).css("top", "100px");
					con.append($("<a href=''>SLET</a>").click(function (e) {
						e.preventDefault();
						$.loveliimessagebox("Er du sikker på du vil slette dette billede?", {
							onTrue: function () {
								$.post("/images/deleteimage	", { guid: currentpi.i }, function (result) {
									if (typeof options.onDelete == 'function') {
										options.onDelete(result);
									}
								});
								con.remove();
								lp.css("background-image", "");
							}
						});
					}));
					lp.append(con);
				});
				lp.mouseleave(function () {
					lp.find(".thumbfunctions").remove();
				});
			}
		}
		checklargeoptions();
		$("#largeprofileimage").trigger("mouseleave");
	}

	$.initprofile = function (u, res, gallery, profileslikethis) {

		$(".interestlevel").click(function (e) {
			e.preventDefault();

			var el = $(this);

			var interestlevel = 0;

			if (el.parent().hasClass("selected")) {
				el.parent().removeClass("selected").addClass("notselected");
			}
			else {
				$(".interestlevel").parent().removeClass("selected").addClass("notselected");
				el.parent().removeClass("notselected").addClass("selected");
				if (el.hasClass("interested"))
					interestlevel = 2;
				if (el.hasClass("favourite"))
					interestlevel = 1;
				if (el.hasClass("blocked"))
					interestlevel = 3;
			}
			$.post("/profiles/" + u + "/setinterestlevel", { name: u, id: interestlevel }, function (data) {
				//				$.jGrowl(data ? res.FavouriteAdded.replace("{0}", "<b>" + u + "</b>") : res.FavouriteRemoved.replace("{0}", "<b>" + u + "</b>"));
			}, "json");
		});

		if (profileslikethis.length != 0) {
			var plt = $("#profileslikethis");
			$.each(profileslikethis, function (i, u) {
				plt.append($.loveliithumbuser(u));
			});
		}

		if (gallery.length != 0) {
			var gb = $("#gallerybar").show();
			$.each(gallery, function (index, i) {
				var itc = $("<div>", { "class": "imagethumbcontainer" }).css("cursor", "pointer").click(function () {
					window.location = "/profiles/" + u.toLowerCase() + "/gallery";
				});
				var ic = $("<div>", { "class": "imagethumb" });
				ic.css("background-image", "url('/content/userimages/thumbs/" + i + ".jpg')");
				itc.append(ic);
				gb.find(".rightprofileinfo").append(itc);
			});
		}

		$.each($("#basicinfocontainer td"), function (i, td) {
			if (td.innerText == res.NoValue) {
				$(td).parent().css("color", "#aaa");
			};
		});
	}

	$.initsearch = function () {
		$("select").loveliidropdown();
		$("select[multiple]").loveliiselect({
			canslide: false,
			maxwidth: 690
		});
		$("#buttonsearch").bind("click", PerformSearch);

		function PerformSearch() {
			$("#buttonsearch").attr("disabled", "disabled");
			$("#searchcontainer form").submit();
		};

		$("*").keypress(function (e) {
			if (e.which == 13) {
				PerformSearch();
				return false;
			}
		});
	}

	$.initgallery = function (token, userimages) {
		$('#fileupload').uploadify({
			'uploader': '/scripts/uploadify.swf',
			'scriptData': { token: token },
			'script': '/images/uploadgalleryimage',
			'auto': true,
			'wmode': 'transparent',
			'hideButton': true,
			'height': 30,
			'width': 250,
			'multi': true,
			'onSelect': function (e, id, file) {
				$.loveliimessage("Uploader billedet", {
					timer: 0,
					animate: true,
					overlaycloses: false
				});
				return false;
			},
			'onError': function (e, id, file, err) {
				alert(err.info);
			},
			'onComplete': function (e, id, file, response, data) {
				$.loveliimodal.close();
				eval("var ui = " + response);
				buildgalleryimage(ui);
			}
		});

		$.each(userimages, function (i, ui) {
			buildgalleryimage(ui);
		});

		function buildgalleryimage(ui) {
			var gc = $("<div class='galleryimagecontainer'>");

			gc.mouseenter(function () {
				var tf = $("<div class='thumbfunctions'>");
				gc.append(tf);
				tf.css("width", gc.width() + "px");
				tf.append($("<a href=''>SLET</a>").click(function (e) {
					e.preventDefault();
					$.loveliimessagebox("Er du sikker på du vil slette dette billede?", {
						onTrue: function () {
							$.post("/images/deleteimage", { guid: ui.i }, function (result) { });
							gc.fadeOut("fast");
						}
					});
				}));
			});
			gc.mouseleave(function () {
				gc.find(".thumbfunctions").remove();
			});

			gc.append("<img src='/content/userimages/thumbs/" + ui.i + ".jpg'>");
			$("#profilegalleryoverviewinner").append(gc);
		};
	}

	$.initsplash = function (jsonimages) {
		$("#meettheloveliis").profilescroller({ images: jsonimages, islinked: false });

		$("#frontlogin input").keypress(function (e) {
			if (e.which == 13) {
				$("form").submit();
			}
		});

		$("select").loveliidropdown();
		$("#topsplashbox h2").hide();

		var th = $("#topsplashbox h2");
		var ch = 0;
		$(th[ch]).show();
		setTimeout(cycle, 10000);

		function cycle() {
			$(th[ch]).fadeOut(500, function () {
				ch = ch == th.length - 1 ? 0 : ch + 1;

				$(th[ch]).fadeIn(2000);
				setTimeout(cycle, 6000);
			});
		}

		moveboat(900);
		function moveboat(move) {
			$("#boat").animate({ "left": "-=" + move + "px" }, 70000, "linear", function () {
				$("#boat").css("left", "1000px");
				moveboat(1100);
			});
		}
	}



})(jQuery);
