function showGlassPane() {
	var glasspane = $('#glasspane');
	if(glasspane.attr('id') == null)
		$('<div id="glasspane"></div>').appendTo($("body"));
	
	var glasspane = $('#glasspane');
	glasspane.css('opacity', '0.6');
	$('#glasspane').css('display','inline');
	$('#glasspane').click (function() {
		closePopUp();
	});
	$(document).keyup(function(e) {
  		var code = (e.keyCode ? e.keyCode : e.which);
  		if(code == 27) { //Esc keycode
   			closePopUp();
 		}
	});
}

function placeDialog(dialogid) {
	var popup = $(dialogid);
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	var popupHeight = popup.height();
	var popupWidth = popup.width();

	popup.css( {
	   'opacity' :'1.0',
	   'top' :'' + windowHeight / 2 - popupHeight / 2,
	   'left' :'' + windowWidth / 2 - popupWidth / 2
	});
}

function closePopUp() {
	
	$('#rollpopup').css('display','none');
	$('#existingmemberpopup').css('display','none');
	$('#newmemberpopup').css('display','none');
	$('#recurringactivitypopup').css('display','none');
	$('#newactivitypopup').css('display','none');
	
	$('#glasspane').css('display','none');
}

function showRollDialog(data, isJustText) {
	showGlassPane();
	$('#rollpopup').css('display','inline');
	placeDialog('#rollpopup');
	var close = $('<div class="loginlinks"><a id="closeroll" href="#"><img id="closeroll" src="image/cancel.gif"></a></div>');
	close.click( function() {
		closePopUp();
		return false;
	});
	if(isJustText)
		data = "<span>" + data + "</span>";
	var dataEl = $(data);
	$("#rollpopup").empty();
	$("#rollpopup").append(close).append(dataEl);
	
}

var isOK = false;
$(document).ready( function() {
	$("#username").blur( function() {
		if(this.value=='') {
			this.value='Användarnamn';
			$(this).attr("class", "initlogin");
		}
	});
	
	$("#username").focus( function() {
		if(this.value=='Användarnamn') {
			this.value='';
			$(this).attr("class", "");
		}
	});
	
	var pwdblurfunc = function() {
		if(this.value=='') {
			var pwdlbl = $("#passwordlabel");
			var pwd = $("#password");
			pwdlbl.show();
			pwd.hide();
			pwdlbl.focus(pwdfocusfunc);
		}
	}
	
	var pwdchangefunc = function() {
		var pwdlbl = $("#passwordlabel");
		var pwd = $("#password");
		pwdlbl.hide();
		pwd.show();
		pwd.blur( pwdblurfunc );
	}
	
	var pwdfocusfunc = function() {
		//if(this.value=='Lösenord') {
			pwdchangefunc();
			setTimeout(function() {
				$("#password").select().focus();
			}, 0); 
		//}
	}
	
	$("#password").blur( pwdblurfunc );
	
	// $("#password").focus( pwdfocusfunc );
	$("#passwordlabel").focus( pwdfocusfunc );
	
	var activateCodeFunc = function() {
		$("#activatemsgdiv").html("Vänta medan vi kontrollerar!");
	
		$.ajax({
			  type: 'POST',
			  url: "SubmitActivateCheck.action",
			  data: $("#activateForm").serialize(),
			  success:  function(data) {
						data = jQuery.trim(data);
						if(data == '') {
							$("#activatemsgdiv").html("FEL");
						} else if(data.substring(0,4) == "FEL:") {
							$("#activatemsgdiv").html(data.substring(4));
						} else if(data.substring(0,5) == "ROLL:") {
							showRollDialog(data.substring(5));
						} else {
							$("#activatemsgdiv").html(data);
						}
					},
				error: function() {
						$("#activatemsgdiv").html("Fel har inträffat");
					}
			});
		
			return false;
	};
	
	$("#changeroll").click(function() {
		showRollDialog("Vänta medan roller laddas", true);
		
		$.ajax({
			  type: 'POST',
			  url: "SubmitLoginCheck.action",
			  data: $("#changeform").serialize(),
			  success:  function(data) {
						data = jQuery.trim(data);
						if(data == '') {
							$("#loginmsgdiv").html("FEL");
							showRollDialog("FEL", true);
						} else if(data.substring(0,4) == "FEL:") {
							$("#loginmsgdiv").html(data.substring(4));
							showRollDialog(data.substring(4));
						} else if(data.substring(0,5) == "ROLL:") {
							showRollDialog(data.substring(5));
							$("#activateCode").click(activateCodeFunc);
						} else {
							$("#loginmsgdiv").html(data);
							showRollDialog(data);
						}
					},
				error: function() {
						showRollDialog("Fel har inträffat", true);
					}
			});
		
			return false;
	});
	
	
	
	
	$("#loginform").ready(function() {
		if($.cookie("username") != undefined && $.cookie("username") != "")
			$("#username").val($.cookie("username"));
		
		if($.cookie("anlpersonal") == "true")
			$("#anlperslogin").attr("checked", "true");
		else
			$("#anlperslogin").attr("checked", "");
		
		if($("#username").val()!='Användarnamn') {
			$("#username").attr("class", "nofocus"); //not gray italic
		}
		
		setTimeout(function() {
			if($("#password").val()!='') { // om webläsaren har fyllt i
				pwdfocusfunc();
			}
		}, 10); 
		
		
	});
	
	$("#loginform").submit(function(){
		$("#loginmsgdiv").html("Vänta medan vi kontrollerar");
		showRollDialog("Vänta medan vi kontrollerar", true);
		if(!isOK) {
			$.ajax({
				  type: 'POST',
				  url: "SubmitLoginCheck.action",
				  data: $(this).serialize(),
				  success: function(data) {
						data = jQuery.trim(data);
						if(data == '') {
							isOK = true;
							$.cookie("anlpersonal", $("#anlperslogin").attr("checked"));
							$.cookie("username", $("#username").val());
							$("#loginform").submit();
						} else if(data.substring(0,4) == "FEL:") {
							$("#loginmsgdiv").html(data.substring(4));
							showRollDialog(data.substring(4));
						} else if(data.substring(0,5) == "ROLL:") {
							isOK = true;
							$.cookie("anlpersonal", $("#anlperslogin").attr("checked"));
							$.cookie("username", $("#username").val());
							showRollDialog(data.substring(5));
						} else {
							$("#loginmsgdiv").html(data);
							showRollDialog(data);
						}
					},
					error: function() {
						showRollDialog("Fel har inträffat", true);
					}
				});
			
			//$.post("SubmitLoginCheck.action", $(this).serialize() ,  );
		}
		return isOK;
	});
});

$(document).ready( function() {
	$(".pagehelp").find("a").click( function() {
		var helpwindow = window.open(this.href, "HelpWindow", "height=500, width=500, resizable=0, location=0, scrollbars=1, status=0");
		if (helpwindow!=null){
			helpwindow.focus();
		}
		return false;
	});
});

$(document).ready( function() {
	$(".terms").find("a").click( function() {
		var helpwindow = window.open(this.href, "TermsWindow", "height=500, width=500, resizable=0, location=0, scrollbars=1, status=0");
		if (helpwindow!=null){
			helpwindow.focus();
		}
		return false;
	});
});

$(document).ready( function() {
	$(".listen").find("a").attr("href", "http://isi.phoneticom.com/cgi-bin/rsxt?customerid=1&url=" + location.href);
});

$(document).ready( function() {
	$("[id*=slot]").hover(function(event) {
		var table = $('<table></table>');
		var data = TIMESLOTS[this.id];
		
		if(data) {
			$.each(data,  function (i, item) {
				var row = $('<tr></tr>');
				$('<TD></TD>').html(item.cn).appendTo($(row));
				$(row).appendTo($(table));
				
				row = $('<tr></tr>');
				$('<TD></TD>').html("(" + item.ab + " personer)").appendTo($(row));
				$(row).appendTo($(table));
				
				row = $('<tr></tr>');
				$('<TD></TD>').html(item.st + " " + item.et).appendTo($(row));
				$(row).appendTo($(table));
				
				row = $('<tr></tr>');
				$('<TD></TD>').html(item.acn + ", " + item.arn + ", " + item.tn).appendTo($(row));
				$(row).appendTo($(table));
				
				row = $('<tr></tr>');
				$('<TD></TD>').html(item.f).appendTo($(row));
				$(row).appendTo($(table));
				
				row = $('<tr></tr>');
				$('<TD></TD>').html("&nbsp;").appendTo($(row));
				$(row).appendTo($(table));
				
			});
			
			$('#titlediv').html(table);
			var offset = $('#titlediv').offset();
			var height = $(this).height();
			var width = $(this).width();
			var position = $(this).position();
			$('#titlediv').css({
			    left: position.left + (width/2) - offset.left,
			    top: position.top + height - offset.top 
			});
			$('#titlediv').show();
		}
		
		

	}, function(event) {
		$('#titlediv').hide();
	});
});

$(document).ready( function() {
	$("#ansSubmit").click( function() {
		if(!$("#isIntyg").attr('checked')) {
			alert("Var god intyga att ovanstående uppgifter är korrekta!");
			return false;
		}
		
	});
});


$(document).ready( function() {
	$("[name=item.hurOfta]").click( function() {
		if($(this).val() == 2 || $(this).val() == 5)
			$("#weekday1").attr('disabled', 'disabled');
		else
			$("#weekday1").attr('disabled', '');
		return true;
	});
});

function slowloadSubmit() {
	$('#glasspane').remove();
	$('#loadingpopup').remove();
	
	var glasspane = $('#glasspane');
	if(glasspane.attr('id') == null)
		$('<div id="glasspane"></div>').appendTo($("body"));
	$('<div id="loadingpopup"><div class="row1"><img src="image/bluewait.gif" alt="Sidan laddas..."/></div><div class="row2">Sidan laddas...</div><div class="row3"><a href="#">Stäng</a></div></div>').appendTo($("body"));

	var glasspane = $('#glasspane');
	glasspane.css('opacity', '0.6');

	var popup = $('#loadingpopup');
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	var popupHeight = popup.height();
	var popupWidth = popup.width();

	popup.css( {
	   'opacity' :'1.0',
	   'top' :'' + windowHeight / 2 - popupHeight / 2,
	   'left' :'' + windowWidth / 2 - popupWidth / 2
	});
	
	$('#loadingpopup a').click( function() {
		closePopUp();
	});
}

$( function() {
	
	$("form.slowload").submit( function() {
		slowloadSubmit();
	})
	$("input.slowload").click( function() {
		slowloadSubmit();
	})
	
	$("form.slowload,input.slowload").ready( function() {
		$('#loadingspan').remove();
	})	
});

$( function() {
	var inputs = $("form:not([class*=nofocus]) :input:visible").not(".nofocus");
	if (inputs.size()>0){
		for(var i=0 ; i<inputs.size();i++) {
			if(!inputs[i].disabled) {
				try {
					inputs[i].focus();
				} catch(err) {
				}
				break;
			}
		}
	}
})

function openInfoWindow(loc) {
	features = 
		   'toolbar=no, location=no, directories=no, status=yes, menubar=no, ' +
		   'scrollbars=yes, resizable=yes'; 
	menutitle=""
	window.open(loc,menutitle,features);
	return false;	
}

$(document).ready(
		function () {
			$(".hiddenloginlink").each(function () {
				//$(this).css("display","inline");
			});
		}
	);

$(document).ready(
		function() {
			$("#loginCornerButton").click( function() {
				$(".loginuppgifter").css("display","inline");
				$("#username").focus();
				$(".hiddenloginlink").css("display","none");
				return false;
			}
		);
	}
);

function contains(optionArray, id){ 
	  for(var i = 0; i < optionArray.length; i++) { 
	    if(optionArray[i].value == id){ 
	      return true; 
	    } 
	  } 
	  return false; 
	} 



$(document).ready( function() {
	$("#art").change( function() {
		$("#art option:selected").each(function () {
				var artid = $(this).val();
				
				var typlist = document.getElementById('typ');
				var typselected = typlist.options[typlist.selectedIndex].value
				
				var artlist = document.getElementById('art');
				var artselected = artlist.options[artlist.selectedIndex].value
				
				typlist.options.length = 0;
				typlist.options.add( new Option("", "") );
				
				for(var i=0;i<arttypListJsArr.length;i++){
					if(arttypListJsArr[i] && (artselected=="" || arttypListJsArr[i].artid == artid)) {
						var optn = new Option(arttypListJsArr[i].typname, arttypListJsArr[i].typid);
						if(!contains(typlist.options, optn.value))
							typlist.options.add( optn );
						if(typselected == arttypListJsArr[i].typid) {
							optn.selected = true;
						}
					}
				}
            });
      })
      
      
      $("#typ").change( function() {
		$("#typ option:selected").each(function () {
				var typid = $(this).val();
				
				var artlist = document.getElementById('art');
				var artselected = artlist.options[artlist.selectedIndex].value
				
				var typlist = document.getElementById('typ');
				var typselected = typlist.options[typlist.selectedIndex].value
				
				artlist.options.length = 0;
				artlist.options.add( new Option("", "") );
				
				for(var i=0;i<arttypListJsArr.length;i++){
					if(arttypListJsArr[i] && (typselected=="" || arttypListJsArr[i].typid == typid)) {
						var optn = new Option(arttypListJsArr[i].artname, arttypListJsArr[i].artid);
						if(!contains(artlist.options, optn.value))
							artlist.options.add( optn );
						if(artselected == arttypListJsArr[i].artid) {
							optn.selected = true;
						}
					}
				}
            });
      })
});

function setOption(searchlist, searchselected, newname, newid) {
	var optn = new Option(newname, newid);
	var place = 0;
	for(place = 0;place<searchlist.options.length;place++){
		if(searchlist.options[place].text.toLowerCase() > optn.text.toLowerCase())
			break;
	}
	
	if(!contains(searchlist.options, optn.value))
		searchlist.options.add( optn ,place);
	if(searchselected == newid) {
		optn.selected = true;
	}
}


function buildList(id, jsArr, list1, selected1, list2, selected2, j, j1, j2) {
	for(var i=0;i<jsArr.length;i++){
		if(jsArr[i] && (id=="" || jsArr[i].ids[j] == id)) {
			if(selected1=="" || jsArr[i].ids[j1] == selected1)
				setOption(list2, selected2, jsArr[i].names[j2], jsArr[i].ids[j2]);
			if(selected2=="" || jsArr[i].ids[j2] == selected2)
				setOption(list1, selected1, jsArr[i].names[j1], jsArr[i].ids[j1]);
		}
	}
}

function connectList(jsArr, elid, elid1, elid2, j, j1, j2) {
	initConnectList(true, jsArr, elid, elid1, elid2, j, j1, j2);
	$("#" + elid).change( function() {
		initConnectList(false, jsArr, elid, elid1, elid2, j, j1, j2);
    })
}

function initConnectList(isInit, jsArr, elid, elid1, elid2, j, j1, j2) {
	$("#" + elid + " option:selected" + (isInit?"[value!='']":"")).each(function () {
		var idsel = $(this).val();
		
		var list1 = document.getElementById(elid1);
		var selected1 = list1.options[list1.selectedIndex].value;
		
		var list2 = document.getElementById(elid2);
		var selected2 = list2.options[list2.selectedIndex].value;
		
		list1.options.length = 0;
		list1.options.add( new Option("", "") );
		
		list2.options.length = 0;
		list2.options.add( new Option("", "") );
		
		buildList(idsel, jsArr, list1, selected1, list2, selected2,  j, j1, j2);
    });
}

function resetLists(jsArr, elid1, elid2, elid3, j1, j2, j3) {
	var list1 = document.getElementById(elid1);
	var list2 = document.getElementById(elid2);
	var list3 = document.getElementById(elid3);
	
	list1.options.length = 0;
	list1.options.add( new Option("", "") );
	
	list2.options.length = 0;
	list2.options.add( new Option("", "") );
	
	list3.options.length = 0;
	list3.options.add( new Option("", "") );
	for(var i=0;i<jsArr.length;i++){
		if(jsArr[i]) {
			setOption(list1, "", jsArr[i].names[j1], jsArr[i].ids[j1]);
			setOption(list2, "", jsArr[i].names[j2], jsArr[i].ids[j2]);
			setOption(list3, "", jsArr[i].names[j3], jsArr[i].ids[j3]);
		}
	}
}

$(document).ready( function() {
	if(typeof verkarttypListJsArr != "undefined") {
		connectList(verkarttypListJsArr, 'art_v', 'typ_v', 'verk_v', 1, 2, 0);
		connectList(verkarttypListJsArr, 'typ_v', 'art_v', 'verk_v', 2, 1, 0);
		connectList(verkarttypListJsArr, 'verk_v', 'typ_v', 'art_v', 0, 2, 1);
		
		$("#reset1").click( function() {
			resetLists(verkarttypListJsArr, 'art_v', 'typ_v', 'verk_v', 1, 2, 0);
			return false;
		});
	}
	
	if(typeof facilityobjectListJsArr != "undefined") {
		connectList(facilityobjectListJsArr, 'omrade_1', 'facility_1', 'object_1', 2, 0, 1);
		connectList(facilityobjectListJsArr, 'object_1', 'facility_1', 'omrade_1', 1, 0, 2);
		connectList(facilityobjectListJsArr, 'facility_1', 'omrade_1', 'object_1', 0, 2, 1);
	
		connectList(facilityobjectListJsArr, 'omrade_2', 'facility_2', 'object_2', 2, 0, 1);
		connectList(facilityobjectListJsArr, 'object_2', 'facility_2', 'omrade_2', 1, 0, 2);
		connectList(facilityobjectListJsArr, 'facility_2', 'omrade_2', 'object_2', 0, 2, 1);
		
		$("#reset2").click( function() {
			resetLists(facilityobjectListJsArr, 'facility_1', 'omrade_1', 'object_1', 0, 2, 1);
			return false;
		});
		
		$("#reset3").click( function() {
			resetLists(facilityobjectListJsArr, 'facility_2', 'omrade_2', 'object_2', 0, 2, 1);
			return false;
		});
		
	}
});


$(document).ready( function() {
	$("#listaarttyp").click( function() {
		var helpwindow = window.open(this.href, "HelpWindow", "height=500, width=500, resizable=0, location=0, scrollbars=1, status=0");
		if (helpwindow!=null){
			helpwindow.focus();
		}
		return false;
	});
});
$(document).ready( function() {
		$("#addPost").click(function() {
				$("#allPost option:selected").each(function () {
					$("<option></option>").val($(this).val()).text($(this).text()).appendTo($("#selectedPost"));
					$(this).remove();
	            });
				return false;
		});
		
		$("#deletePost").click(function() {
			$("#selectedPost option:selected").each(function () {
				$("<option></option>").val($(this).val()).text($(this).text()).appendTo($("#allPost"));
				$(this).remove();
	           });
			return false;
		});
});
$(document).ready( function() { 
		$("#saveKategori").click(function() {
			var s = "";
			$("#selectedPost option").each(function (){
				s += $(this).val() + ","
			});
			$("#selectedPostIds").val(s);
			$("#selectedKategoriForSave").val($("#selectedKategori").val());
			$("#saveForm").submit();
		});
});
	
$(document).ready( function() {
			$("#addPostInterval").click(function() {
					var interval = $("#franday").val() + " " + $("#franmonth").val() + " - "  + $("#today").val() + " " + $("#tomonth").val()
					$("<option></option>").val(interval).text(interval).appendTo($("#oppetider"));
		            return false;
			});
			
			$("#deletePostInterval").click(function() {
				$("#oppetider option:selected").each(function () {
					$(this).remove();
	            });
				return false;
			});
	});
$(document).ready( function() { 
	$("#saveKategoriPost").click(function() {
		var s = "";
		$("#oppetider option").each(function (){
			s += $(this).val() + ","
		});
		$("#oppetiderText").val(s);
		$("#selectedKategoriForSave").val($("#selectedKategori").val());
		$("#selectedKategoriPostForSave").val($("#selectedKategoriPost").val());
		$("#saveForm").submit();
	});
});

$(document).ready( function() { 
	$(".nyGiro").click(function() {
		if($(this).val() == 'false') {
			$("#giro").attr('disabled', 'disabled');
		} else {
			$("#giro").attr('disabled', '');
		}
	});
});

$(document).ready(function() {
	// Automatic save bidrag after 20 min
	if($(".saveLater").length >0) {
		setTimeout(function() {
			slowloadSubmit();
			$("#saveLaterForm").append($("<input type='hidden' name='method:continueLater'/>"));
			$("#saveLaterForm").append($("<input type='hidden' name='automatic' value='true'/>"));
			$("#saveLaterForm").submit();
		}, 600000);
	}
	
});
