var hideSubmenu = new Array();

$(document).ready(function() {
	// Menu position fix
	var menu = $("div.wrapper div.top div.menu");
	var menuTop = menu.offset().top;
	
	$(window).scroll(function() {
		if (menuTop - $(window).scrollTop() <= 0) {
			menu.removeClass("fix");
			menu.addClass("float");
		} else if (menuTop - $(window).scrollTop() > 0) {
			menu.removeClass("float");
			menu.addClass("fix");
		}
	});
	
	$("input.close.welcome").click(function() {
		$("div.boogleInfo.welcome").hide();
	});

	// Menu, first level
	$("div.wrapper div.top div.menu ul li.menu").mouseover(function() {		
		hideSubmenu[$(this).attr("id")] = false;
		var activeSubmenu = $("> div", $(this));
		
		var currentIsDisplayed = activeSubmenu.css("display") == "block";
		
		if (!currentIsDisplayed) {
			activeSubmenu.show();
			$(this).addClass("active");
		
			var rightLimit = menu.offset().left + menu.width();
			var menuLimit = activeSubmenu.offset().left + activeSubmenu.width();
	
			if (menuLimit > rightLimit) {
				activeSubmenu.css("margin-left", rightLimit - menuLimit - 11);
			}
		}
	});
	$("div.wrapper div.top div.menu ul li.menu").mouseout(function() {
		hideSubmenu[$(this).attr("id")] = true;
		var subMenuId = $("> div", $(this)).attr("id");
		var menuId = $(this).attr("id");
		setTimeout("hideMenu('" + subMenuId + "', '" + menuId + "')", 100);
	});
	
	// Make all menu clickable, not just text
	$("div.wrapper div.top div.menu li, div.wrapper div.top div.menu div.start, div.wrapper div.top div.menu div.profile, div.wrapper div.top div.menu div.mail").click(function() {
		var href = $("> a", $(this)).attr("href");
		var target = $("> a", $(this)).attr("target");
		
		if (href) {
			if (target == "_blank") {
				window.open(href);
			} else {
				document.location.href = href;
			}
		}
		
		return false;
	});

	// Menu, second level
	$("div.wrapper div.top div.menu ul li div ul > li").mouseover(function() {
		$(this).addClass("active");
	});
	$("div.wrapper div.top div.menu ul li div ul > li").mouseout(function() {
		$(this).removeClass("active");
	});

	
	// Menu, third level
	$("div.wrapper div.top div.menu ul > li div ul > li").mouseover(function() {
		$("div", $(this)).css("margin-top", ($(this).position().top - 28) + "px");
		$("div", $(this)).show();
	});
	$("div.wrapper div.top div.menu ul > li div ul > li").mouseout(function() {
		$("div", $(this)).hide();
	});
	
	// Community menu
	$("div.wrapper div.top div.menu ul li.image.com div.profile").mouseover(function() {
		hideSubmenu["profile"] = false;
		var activeSubmenu = $("ul.submenu.profile");
		
		var currentIsDisplayed = activeSubmenu.css("display") == "block";
		
		if (!currentIsDisplayed) {
			activeSubmenu.show();
		}
	});
	$("div.wrapper div.top div.menu ul li.image.com div.profile").mouseout(function() {
		hideSubmenu["profile"] = true;		
		setTimeout("hideMenu('menu_profile', 'profile')", 100);
	});
	$("div.wrapper div.top div.menu ul li.image.com div.mail").mouseover(function() {
		hideSubmenu["mail"] = false;
		var activeSubmenu = $("ul.submenu.mail");
		
		var currentIsDisplayed = activeSubmenu.css("display") == "block";
		
		if (!currentIsDisplayed) {
			activeSubmenu.show();
		}
	});
	$("div.wrapper div.top div.menu ul li.image.com div.mail").mouseout(function() {
		hideSubmenu["mail"] = true;		
		setTimeout("hideMenu('menu_mail', 'mail')", 100);
	});
	$("div.wrapper div.top div.menu ul li.image.com div.start").mouseover(function() {
		hideSubmenu["start"] = false;
		var activeSubmenu = $("ul.submenu.start");
		
		var currentIsDisplayed = activeSubmenu.css("display") == "block";
		
		if (!currentIsDisplayed) {
			activeSubmenu.show();
		}
	});
	$("div.wrapper div.top div.menu ul li.image.com div.start").mouseout(function() {
		hideSubmenu["start"] = true;		
		setTimeout("hideMenu('menu_start', 'start')", 100);
	});
	
	
	// Top search
	$("div.wrapper div.top div.search span").click(function() {
		$("div.wrapper div.top div.search form").submit();
	});
	
	$("a.closeFullscreen").click(function() {
		$("div.fullscreen").hide();
	});
	
	$("form.loginForm").submit(function() {
		var username = $("input[name=username]", $(this)).val();
		username = username.replace("@crossnet.se", "");
		var password = $("input[name=password]", $(this)).val();
		ajaxXML($(this).attr("action"), "username=" + username + "&password=" + password,
				function(xml) {
					var error = $(xml).find("error").text();
					
					if (error != "") {
						$("div.login form input.submit").removeClass("wait");
						$("div.login div.boogle.errorLogin").show();
					} else {
						var forwardTo = $(xml).find("success").text();
						if (forwardTo.indexOf("?") < 0) {
							forwardTo = forwardTo + "?"
						} else {
							forwardTo = forwardTo + "&"
						}
						forwardTo = forwardTo + "fromLogin=true";
						
						document.location.href = forwardTo;
					}
				}, 
				function(xml) {
					showGeneralError();
				});
		
		return false;
	});
	
	$("div.profile_left div.status a.status.delete").click(function() {
		ajaxXML("/portal/statusDelete.do", "", function() {
			$("div.profile_left div.status form").show();
			$("div.profile_left div.status div.statusText").hide();
			$("div.profile_left div.status span.links").hide()
			$("div.profile_left div.status span em").hide()
		});
		
		return null;
	});
	
	$("div.profile_left div.status input.infoValue").focus(function() {
		$(this).val("");
		$(this).removeClass("infoValue");
	});
	
	$("div.profile_left div.status form").submit(function() {
		var form = $(this);
		ajaxXMLFromForm($(this), 
				function(xml) {
					var error = $(xml).find("error").text();
					
					if (error != "") {
						showError(error);
					} else {
						$("input.submit", form).removeClass("wait");
						
						$("div.profile_left div.status div.boogle.hidden").hide();
						
						form.hide();
						$("div.profile_left div.status div.statusText").text($("input[type=text]", form).val());
						$("div.profile_left div.status div.statusText").show();
					}
				}, 
				function(xml) {
					showGeneralError();
				});
		
		return false;
	});
	
	$("div.login .forgot").click(function() {
		window.open('/portal/forgotPassword1.jsp','ForgotPassword','menubar=0,resizable=0,width=350,height=250');
		return false;
	});
	
	$("input#hide").click(function() {
		ajaxXML("/portal//welcomeUpdate.do", "hide=" + $(this).attr("checked"));
	});
	
	$("a.boogle").click(function(e) {
		$("div.boogle.hidden").hide();
		var boogle = $(this).next("div.boogle");
		var width = boogle.width();
		var height = boogle.height();
		
		var left = e.pageX - width / 2;
		if (left <= 10) {
			left = 10;
		}

		var bottom = $(window).height() - e.pageY;
		
		boogle.css("left", left);
		boogle.css("bottom", bottom);
		boogle.slideDown(200);
		return false;
	});
	
	$("div.boogle img.close").click(function() {
		$(this).parent("div.boogle").fadeOut(200);
	});
	
	$("div.boogle input.submit.friend").click(function() {
		var activeBoogle = $(this).parents("div.boogle.hidden").get(0);
		
		ajaxXMLFromForm($(this).parents("form"), 
			function(xml) {
				var error = $(xml).find("error").text();
				
				if (error != "") {
					showError(error);
				} else {
					$("form", activeBoogle).hide();
					$("span.success", activeBoogle).show();
				}
			}, 
			function(xml) {
				showGeneralError();
			});
		
		return false;
	});
	
	$("div.boogle input.submit.report").click(function() {
		var activeBoogle = $(this).parent().parent().parent().parent();
		
		ajaxXMLFromForm($(this).parents("form"), 
			function(xml) {
				var error = $(xml).find("error").text();
				
				if (error != "") {
					showError(error);
				} else {
					$("form", activeBoogle).hide();
					$("span.success", activeBoogle).show();
				}
			}, 
			function(xml) {
				showGeneralError();
			});
		
		return false;
	});
	
	initSubmit();
	
	// Paginator
	$("div.paginator div").click(function() {
		var pageIndex = $(this).attr("id").replace("page", "");
		
		if (pageIndex == "") {
			return;
		}
		
		var url = document.location.href;
		if (url.indexOf("&page=") > 0) {
			url = url.substr(0, url.indexOf("&page="));
		}
		if (url.indexOf("?page=") > 0) {
			url = url.substr(0, url.indexOf("?page="));
		}

		document.location.href = url + (url.indexOf("?") > 0 ? "&" : "?") + "page=" + pageIndex;
	});
	
	// Boogle cancel buttons
	$("div.boogle input.cancel, div.boogle input.close").click(function() {
		$(this).parents("div.boogle.hidden").hide();
	});
	
	$("div.boogleInfo input.cancel, div.boogleInfo input.close").click(function() {
		$(this).parents("div.boogleInfo.hidden").hide();
	});
	
	$("div.boogleInfoPodcastSubscribe input.cancel, div.boogleInfoPodcastSubscribe input.close").click(function() {
		$(this).parents("div.boogleInfoPodcastSubscribe.hidden").hide();
	});
	
	// Name displayers (Small profile img show name)
	$("img.nameDisplayer").mouseover(function() {
		$(this).after("<div class=\"boogleName outer\"><div class=\"boogleName\">" + $(this).attr("alt") + "</div></div>");
		$("div.boogleName.outer").css("left", $(this).offset().left + ($(this).width() / 2) - 52);
		$("div.boogleName.outer").css("top", $(this).offset().top - 61);
	});
	$("img.nameDisplayer").mouseout(function() {
		$("div.boogleName.outer").remove();
	});
	
	
	$("div.boogleInfo input.city").keyup(function() {
		if ($(this).val().length >= 2) {
			searchCity($(this));
		}
	});
	$("div.boogleInfo input.city").blur(function() {
		setTimeout("$('div.searchResult').remove();", 300);
	});
	
	if ($("div.profile_menu").length) {
		$("div.profile_menu a:not(a.selected)").mouseover(function() {
			$(this).after("<div class=\"boogleName outer\"><div class=\"boogleName\">" + $("span", $(this)).text() + "</div></div>");
			$("div.profile_menu div.boogleName.outer").css("left", $(this).offset().left + ($(this).width() / 2) - 52);
			$("div.profile_menu div.boogleName.outer").css("top", $(this).offset().top - 61);
		});
		$("div.profile_menu a:not(a.selected)").mouseout(function() {
			$("div.profile_menu div.boogleName.outer").remove();
		});
	}
	
	$("div.profile_left div.profileimg").mouseover(function() {
		$("div.profile_left div.profileimg a.change").css("display", "block");
	});
	$("div.profile_left div.profileimg").mouseout(function() {
		$("div.profile_left div.profileimg a.change").hide();
	});	
	
	$("div.profile_left div.profileimg a.change").click(function() {
		$("div.profile_left div.profileimg div.boogle.hidden").fadeIn(200);
	});
	
	$("div.profile_left div.profileimg form input.submit").click(function() {
		var submit = $(this);
		var form = $(this).parents("form");
		
		var options = { 
		        target: '#output2', 
		        success: function(xml, statusText) {
					var error = $(xml).find("error").text();
					
					if (error != "") {
						showError(error);
					} else {
						var img = $(xml).find("img").text();
						
						$("div.profile_left div.profileimg img").attr("src", img);
						$("div.profile_left div.profileimg div.boogle.hidden").hide();
						
						submit.removeClass("wait");
						$("input[name=attr_image]", form).val("");
					}
				},		  
		        type: "post", 
		        dataType:  "xml" 
		    }; 
		
		form.ajaxSubmit(options); 
		
		return false;
	});
	
	$("a.webbradio").click(function() {
		window.open('http://beta.crossnet.net/crossnetflow/radio/new.php','cwebbradio','menubar=0,resizable=0,width=312,height=227');
		return false;
	});
	
	$("a.mediaplayer").click(function() {
		if ($(this).attr("href") != "" && $(this).attr("href") != "#") {
			window.open($(this).attr("href"), 'cmediaplayer','menubar=0,resizable=0,width=760,height=630');
		} else {
			window.open('http://mediaplayer.crossnet.se/viewNavMenu.do?menuID=2', 'cmediaplayer','menubar=0,resizable=0,width=760,height=630');
		}
		return false;
	});
	
	initArticleImage();
	
	
	$("div.top div.search form input[name=search]").keyup(function() {
		var searchString = $(this).val();
	
		if (searchString.length > 1) {
			ajaxXML("/portal/friendAndGroupSearch.do", "search=" + searchString, 
				function(xml) {
					var error = $(xml).find("error").text();
					
					if (error != "") {
						showError(error);
					} else {
						$("div.top div.boogle.search").show();
						$("div.top div.boogle.search div ul li:gt(0)").remove();
						$("users user", xml).each(function(){
							if ($("div.top div.boogle.search div ul li").length <= 9) {
								var id = $("id", this).text();
								var name = $("name", this).text();
								var imgurl = $("img", this).text();
								var username = $("username", this).text();
								
								var newRow = $("div.top div.boogle.search div ul li:first").clone();
								$("em", newRow).html(name);
								$("input", newRow).attr("value", id);
								$("img", newRow).attr("src", imgurl);
								$("div.top div.boogle.search div ul li:last").after(newRow);
								$("div.top div.boogle.search div ul li:odd").addClass("odd");
								newRow.show();
								
								newRow.click(function() {
									document.location.href = "http://crossnet.se/" + username;
								});
							}
						});
						$("users group", xml).each(function(){
							if ($("div.top div.boogle.search div ul li").length <= 9) {
								var id = $("id", this).text();
								var name = $("name", this).text();
								var imgurl = $("img", this).text();
								
								var newRow = $("div.top div.boogle.search div ul li:first").clone();
								$("em", newRow).html(name);
								$("input", newRow).attr("value", id);
								$("img", newRow).attr("src", imgurl);
								$("div.top div.boogle.search div ul li:last").after(newRow);
								$("div.top div.boogle.search div ul li:odd").addClass("odd");
								newRow.show();
								
								newRow.click(function() {
									document.location.href = "http://crossnet.se/portal/group.do?group=" + id;
								});
							}
						});
						
						if ($("div.top div.boogle.search div ul li").length == 1) {
							$("div.top div.boogle.search").hide();
						}
					}
				});
		}
	});
	$("div.top div.search form input[name=search]").blur(function() {
		setTimeout("$('div.top div.boogle.search').hide()", 200);
	});
	
	$("div.churchPodcast input[name=church]").click(function() {
		var value = $(this).val();
		var isChecked = $(this).attr("checked");
		if (value != 0 && isChecked) {
			$("div.churchPodcast input#church_0").attr("checked", false);
		} else if (value == 0 && isChecked) {
			$("div.churchPodcast input[name=church]").attr("checked", false);
			$("div.churchPodcast input#church_0").attr("checked", true);
		}
	});
	
	$("div.churchPodcast input[name=category]").click(function() {
		var value = $(this).val();
		var isChecked = $(this).attr("checked");
		if (value != -1 && isChecked) {
			$("div.churchPodcast input#cat_-1").attr("checked", false);
		} else if (value == -1 && isChecked) {
			$("div.churchPodcast input[name=category]:gt(0)").attr("checked", false);
		}
	});
	
	$("div.churchPodcast input[type=checkbox]").click(function() {		
		var churches = "";
		$("div.churchPodcast input[name=church]").each(function(){
			if ($(this).val() != 0 && $(this).attr("checked")) {
				churches += "," + $(this).val();
			}
		});
		if (churches.length > 0) {
			churches = churches.substr(1);
		}
		var cats = "";
		$("div.churchPodcast input[name=category]").each(function(){
			if ($(this).val() != -1 && $(this).attr("checked")) {
				cats += "," + $(this).val();
			}
		});
		if (cats.length > 0) {
			cats = cats.substr(1);
		}

		if ($("div.churchPodcast input[name=church]:checked").length == 0 && $("div.churchPodcast input[name=category]:gt(0):checked").length == 0) {
			$("div.churchPodcast input#church_0").attr("checked", true);
			$("div.churchPodcast input#cat_-1").attr("checked", true);
			
			$("div.churchPodcast div.url.standard textarea").html("http://" + $("div.churchPodcast span.url.hidden").html());
			//$("div.churchPodcast div.url.itpc a").html("itpc://" + $("div.churchPodcast span.url.hidden").html());
			$("div.churchPodcast div.url.itpc a").attr("href", "itpc://" + $("div.churchPodcast span.url.hidden").html());
		} else if ($("div.churchPodcast input[name=church]:checked").length == 0) {
			$("div.churchPodcast input#church_0").attr("checked", true);
			
			$("div.churchPodcast div.url.standard textarea").html("http://" + $("div.churchPodcast span.url.hidden").html() + "?cat=" + cats);
			//$("div.churchPodcast div.url.itpc a").html("itpc://" + $("div.churchPodcast span.url.hidden").html() + "?cat=" + cats);
			$("div.churchPodcast div.url.itpc a").attr("href", "itpc://" + $("div.churchPodcast span.url.hidden").html() + "?cat=" + cats);
		} else if ($("div.churchPodcast input[name=category]:gt(0):checked").length == 0) {
			$("div.churchPodcast input#cat_-1").attr("checked", true);
			
			$("div.churchPodcast div.url.standard textarea").html("http://" + $("div.churchPodcast span.url.hidden").html() + "?church=" + churches);
			//$("div.churchPodcast div.url.itpc a").html("itpc://" + $("div.churchPodcast span.url.hidden").html() + "?church=" + churches);
			$("div.churchPodcast div.url.itpc a").attr("href", "itpc://" + $("div.churchPodcast span.url.hidden").html() + "?church=" + churches);
		} else {
			$("div.churchPodcast div.url.standard textarea").html("http://" + $("div.churchPodcast span.url.hidden").html() + "?church=" + churches + "&cat=" + cats);
			//$("div.churchPodcast div.url.itpc a").html("itpc://" + $("div.churchPodcast span.url.hidden").html() + "?church=" + churches + "&cat=" + cats);
			$("div.churchPodcast div.url.itpc a").attr("href", "itpc://" + $("div.churchPodcast span.url.hidden").html() + "?church=" + churches + "&cat=" + cats);
		}
		
		if ($("div.churchPodcast input[name=flow]").attr("checked")) {
			var flow = "";
			if ($("div.churchPodcast div.url.standard textarea").html().indexOf("?") > 0) {
				flow = "&flow=true";
			} else {
				flow = "?flow=true";
			}
			
			$("div.churchPodcast div.url.standard textarea").html($("div.churchPodcast div.url.standard textarea").html() + flow);
			//$("div.churchPodcast div.url.itpc a").html($("div.churchPodcast div.url.itpc a").html() + flow);
			$("div.churchPodcast div.url.itpc a").attr("href", $("div.churchPodcast div.url.itpc a").attr("href") + flow);
		}
	});
	
	$("div.profile_left a.joinGroup, div.profile_left a.leaveGroup").click(function() {
		var link = $(this);
		var groupId = link.attr("href").substring(link.attr("href").indexOf("group=") + 6);
		groupId = groupId.substring(0, groupId.indexOf("&"));

		ajaxXML(link.attr("href"), "", 
				function(xml) {
					var error = $(xml).find("error").text();
					
					if (error != "") {
						showError(error);
					} else {
						document.location.href = "/portal/group.do?group=" + groupId;
					}
				}, 
				function() {
					showGeneralError();
				});
		
		return false;
	});
	
	$("ul.logg li img.delete").click(function() {
		var id = $(this).attr("id");
		
		ajaxXML("/portal/deleteLogg.do", "oid=" + id, 
		function(xml, textStatus) {
			var error = $(xml).find("error").text();
			
			if (error != "") {
				showError(error);
			} else {
				var li = $("ul.logg li#logg_" + id);
				li.slideUp(200);
				var thisIndex = $("ul.logg li").index(li);
				$("ul.logg li:gt(" + thisIndex + ")").toggleClass("odd");
			}
		}, 
		function(XMLHttpRequest, textStatus, errorThrown) { 
			showGeneralError();
		});
	});
	
	$("#podcastQuantity").change(function() {
		updatePodcastScript();
	});
	
	$("input[name=podcastWidth]").change(function() {
		updatePodcastScript();
	});
	
});

function updatePodcastScript() {
	var quantity = $("#podcastQuantity").val();
	var churchId = $("#podcastChurchId").val();
	var small;
	$("input[name=podcastWidth]").each(function() {
		if($(this).attr("checked")) {
			small = $(this).val();
		}
	});
	
	$("#podcastScript").text("<script type=\"text/javascript\" src=\"http://www.crossnet.se/podcastadmin/box/?churchOid=" + churchId + "&quantity=" + quantity + "&small=" + small + "\"></script>");
	$("#podcastPreview").attr("href", "http://www.crossnet.se/podcastadmin/box/preview.jsp?churchOid=" + churchId + "&quantity=" + quantity + "&small=" + small);
}

jQuery.urlParameter = function(url, name) {
    var r = {};
    if (url) {
        var q = url.substring(url.indexOf('?') + 1); // remove everything before ?
        q = q.replace(/\&$/, ''); // remove trailing &
        jQuery.each(q.split('&'), function() {
            var splitted = this.split('=');
            var key = splitted[0];
            var val = splitted[1];
            
            // convert numbers
            if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
            
            // convert booleans
            if (val == 'true') val = true;
            if (val == 'false') val = false;
            
            // ignore empty values
            if (typeof val == 'number' || typeof val == 'boolean' || val.length > 0) r[key] = val;
        });
    }
    
    return r[name];
};

function initArticleImage() {
	$("div.article div.articleImages a").click(function() {
		var href = $(this).attr("href");
		
		ajaxHTML(href, "",
				function(html) {
					$("div.article div.articleImages").html(html);
					initArticleImage();
				},
				function () {
					showGeneralError();
				});
		
		return false;
	});
}

function initSubmit() {
	$("input.submit").click(function() {
		$(this).addClass("wait");
	});
}


function initFriendSearch(url, x, y, callback) {
	$("div.boogle.userSelector div.boogle").load(url, "", function() {
		$("div.userSelector input.search").keyup(function() {
			searchFriend($(this).val());
		});
		
		$("div.userSelector input").focus(function() {
			if ($(this).hasClass("infoValue")) {
				$(this).val("");
				$(this).removeClass("infoValue");
			}
		});
		
		$("div.userSelector ul li input").click(function() {
			if (!$(this).attr("checked")) {
				$(this).attr("checked", "checked");
			} else {
				$(this).removeAttr("checked");
			}
		});
		
		$("div.userSelector ul li").click(function() {
			if (!$("input", $(this)).attr("checked")) {
				$("input", $(this)).attr("checked", "checked");
				$(this).addClass("selected");
			} else {
				$("input", $(this)).removeAttr("checked");
				$(this).removeClass("selected");
			}
		});
		
		$("div.userSelector input.cancel").click(function() {
			$("div.userSelector").hide();
		});
		
		$("div.userSelector").fadeIn(200);
		
		callback();
	});

	$("div.userSelector").css("top", y);
	$("div.userSelector").css("left", x - ($("div.userSelector").width() / 2));
}

function searchFriend(searchString) {
	ajaxXML("/portal/friendSearch.do", "search=" + searchString + "&multiple=false", 
		function(xml) {
			var error = $(xml).find("error").text();
			
			if (error != "") {
				showError(error);
			} else {
				$("div.userSelector ul li:gt(0)").remove();
				$("users user", xml).each(function(){
					var id = $("id", this).text();
					var name = $("name", this).text();
					var imgurl = $("img", this).text();
					
					var newRow = $("div.userSelector ul li:first").clone();
					$("span", newRow).text(name);
					$("input", newRow).attr("value", id);
					$("img", newRow).attr("src", imgurl);
					$("div.userSelector ul li:last").after(newRow);
					$("div.userSelector ul li:odd").addClass("odd");
					newRow.show();
					
					newRow.click(function() {
						if (!$(this).attr("checked")) {
							$(this).attr("checked", "checked");
						} else {
							$(this).removeAttr("checked");
						}
					});
					newRow.click(function() {
						if (!$("input[type=checkbox]", $(this)).attr("checked")) {
							$("input[type=checkbox]", $(this)).attr("checked", "checked");
							$(this).addClass("selected");
						} else {
							$("input[type=checkbox]", $(this)).removeAttr("checked");
							$(this).removeClass("selected");
						}
					});
				});
			}
		});
}

function searchCity(input) {
	var country = $("select.country").val();
	
	ajaxXML("/portal/citySearch.do", "country=" + country + "&search=" + input.val(), 
		function(xml) {
			var error = $(xml).find("error").text();
			
			if (error != "") {
				showError(error);
			} else {
				if ($("div.searchResult").length == 0) {
					input.after("<div class=\"searchResult\"></div>");
					$("div.searchResult").css("top", input.position().top + 18);
					$("div.searchResult").css("left", input.position().left);
				}
				
				$("div.searchResult").html("");
				
				if ($("cities city", xml).length == 0) {
					$("div.searchResult").remove();
				}
				
				$("cities city", xml).each(function(){
					var id = $("id", this).text();
					var name = $("name", this).text();
					
					$("div.searchResult").append("<a href=\"#\" id=\"" + id + "\">" + name + "</a>");
				});
				
				$("div.boogleInfo div.searchResult a").click(function() {
					$("div.boogleInfo input.city").val($(this).html())
					$("div.searchResult").remove();
					return false;
				});
			}
		});
}

function copyBoogleInfo(boogleInfo) {
	var newBoogleInfo = boogleInfo.clone();
	boogleInfo.before(newBoogleInfo);
	return newBoogleInfo;
}

function initBoogleInfo(boogleInfo) {
	initSubmit();
	
	$("input.cancel, input.close", boogleInfo).click(function() {
		$(this).parents("div.boogleInfo").hide();
		$(this).parents("div.boogleInfo").remove();
	});
}

function hideMenu (subMenuId, menuId) {
	if (hideSubmenu[menuId]) {
		$("#" + menuId).removeClass("active");
		$("#" + subMenuId).hide();
	}
}



function ajaxXML(urlPost, dataPost, successFunc, errorFunc) {
	$.ajax({
	      url: urlPost,
	      type: "POST",
	      data: dataPost,
	      dataType: "xml",
	      success: successFunc,
	      error: errorFunc
	   }
	);
}

function ajaxHTML(urlPost, dataPost, successFunc, errorFunc) {
	$.ajax({
	      url: urlPost,
	      type: "POST",
	      data: dataPost,
	      dataType: "html",
	      success: successFunc,
	      error: errorFunc
	   }
	);
}

function ajaxXMLFromForm(form, successFunc, errorFunc) {
	var url = form.attr("action");
	
	ajaxXMLFromFormWithUrl(form, url, successFunc, errorFunc);
}

function ajaxXMLFromFormWithUrl(form, url, successFunc, errorFunc) {
	var data = "";
	
	$("input[type=text], input[type=password], input[type=hidden]", form).each(function() {
		var name = $(this).attr("name");
		var value = escape(utf8Encode($(this).val()));
		
		if (name != "") {
			data += name + "=" + value + "&";
		}
	});
	
	$("input[type=checkbox]", form).each(function() {
		var name = $(this).attr("name");
		var value = $(this).attr("checked");
		
		if (name != "") {
			data += name + "=" + value + "&";
		}
	});
	
	$("input[type=radio]", form).each(function() {
		var name = $(this).attr("name");
		if (data.indexOf(name) < 0) {
			var value = escape(utf8Encode($("input[name=" + name + "]:checked").val()));
	
			if (name != "") {
				data += name + "=" + value + "&";
			}
		}
	});
	
	$("textarea", form).each(function() {
		var name = $(this).attr("name");
		var value = escape(utf8Encode($(this).val()));

		if (name != "") {
			data += name + "=" + value + "&";
		}
	});	
	
	$("select", form).each(function() {
		var name = $(this).attr("name");
		var value = escape(utf8Encode($(this).val()));

		if (name != "") {
			data += name + "=" + value + "&";
		}
	});
	
	ajaxXML(url, data, successFunc, errorFunc);
}

function utf8Encode(string) {
	var utftext = "";

	for (var n = 0; n < string.length; n++) {

		var c = string.charCodeAt(n);

		if (c < 128) {
			utftext += String.fromCharCode(c);
		}
		else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		}
		else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}

	}

	return utftext;
}

function showError(text) {
	alert(text);
}

function showGeneralError() {
	showError("Ett okänt fel har uppstått. Försök igen.");
}

/* ************************************************************
Created: 20060120
Author:  Steve Moitozo <god at zilla dot us> -- geekwisdom.com
Description: This is a quick and dirty password quality meter 
		 written in JavaScript so that the password does 
		 not pass over the network.
License: MIT License (see below)
Modified: 20060620 - added MIT License
Modified: 20061111 - corrected regex for letters and numbers
                     Thanks to Zack Smith -- zacksmithdesign.com
---------------------------------------------------------------
Copyright (c) 2006 Steve Moitozo <god at zilla dot us>

Permission is hereby granted, free of charge, to any person 
obtaining a copy of this software and associated documentation 
files (the "Software"), to deal in the Software without 
restriction, including without limitation the rights to use, 
copy, modify, merge, publish, distribute, sublicense, and/or 
sell copies of the Software, and to permit persons to whom the 
Software is furnished to do so, subject to the following 
conditions:

   The above copyright notice and this permission notice shall 
be included in all copies or substantial portions of the 
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY 
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 
AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 
OR OTHER DEALINGS IN THE SOFTWARE. 
---------------------------------------------------------------

************************************************************ */
function testPassword(passwd)
{
	var intScore   = 0;
		
	if (passwd.length < 5) {
		intScore = (intScore + 3);
	} else if (passwd.length > 4 && passwd.length < 8) {
		intScore = (intScore + 6);
	} else if (passwd.length > 7 && passwd.length < 16)	{
		intScore = (intScore + 12);
	} else if (passwd.length > 15) {
		intScore = (intScore + 18);
	}		
		
	if (passwd.match(/[a-z]/)) {
		intScore = (intScore + 1);
	}
		
	if (passwd.match(/[A-Z]/)) {
		intScore = (intScore + 5);
	}
		
	if (passwd.match(/\d+/)) {
		intScore = (intScore + 5);
	}
		
	if (passwd.match(/(.*[0-9].*[0-9].*[0-9])/)) {
		intScore = (intScore + 5);
	}
				
	if (passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)) {
		intScore = (intScore + 5);
	}

	if (passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) {
		intScore = (intScore + 5);
	}
	
	if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
		intScore = (intScore + 2);
	}

	if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) {
		intScore = (intScore + 2);
	}
 
	if (passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/)) {
		intScore = (intScore + 2);
	}
	
	return intScore;
}

