var active_list_box_id = '';

$(document).ready(function(){
	
	$(".rep-calendar .item").ThreeDots( { max_rows: 1 } );
	
	$.each(
		$(".rep-calendar .item"), 
		function( index, item) {
			var url = $(item).attr('threeDotsUrl');
			if ( url != undefined ) {
				var anchor = $('<a onfocus="if(this.blur)this.blur();" />' );
				anchor.attr('src', url );
						
				var title = $(item).attr('threeDotsTitle')
				var title_html = ''
				if ( title ) {
					title_html = ' title="' + title + '"';
				}
				
				var wrapper = '<a' + title_html + ' href="' + url + '" onfocus="if(this.blur)this.blur();" />';
				
				$(item).find('.ellipsis_text,.threedots_ellipsis').wrapInner( wrapper);
			}		
		}
	);
	
	$(".locked a").click(function () {
			showLogin(this.href);
			return false;
		});
	
	$(".main-menu div.locked").append('<img class="lockimage" src="graphics/lock_white.png" />');
	
	$('#login-username,#login-password')
		.focus( function(){ $(this.parentNode).css("background-image",'none'); 	})
		.blur( function(){ 
			if ( this.value == '') {
				$(this.parentNode).css("background-image",'url(graphics/' + $(this.parentNode).attr("className") + '_default_bg.gif)'); 	
			}
		})
		.keypress(function (e) {   
	        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {   
	            this.form.submit();
	        } else {   
	            return true;   
	        }   
	    });
	
	$('#mailafriend-sendername').data('default', $("label[for='mailafriend-sendername']").text()).focus(inputFocus).blur(inputBlur).trigger('blur');
	$('#mailafriend-sender').data('default', $("label[for='mailafriend-sender']").text()).focus(inputFocus).blur(inputBlur).trigger('blur');
	$('#mailafriend-name').data('default', $("label[for='mailafriend-name']").text()).focus(inputFocus).blur(inputBlur).trigger('blur');
	$('#mailafriend-email').data('default', $("label[for='mailafriend-email']").text()).focus(inputFocus).blur(inputBlur).trigger('blur');
	$('#mailafriend-safetyCode').data('default', $("label[for='mailafriend-safetyCode']").text()).focus(inputFocus).blur(inputBlur).trigger('blur');
	$('#mailafriend-message').data('default', "\n\n"+$("label[for='mailafriend-message']").text()).blur(inputBlur).trigger('blur');

	$('#search-q').data('default', $("label[for='search-q']").text()).focus(inputFocus).blur(inputBlur).trigger('blur');
	
	$('#safetyCode_user').data('default', $("label[for='safetyCode_user']").text()).focus(inputFocus).blur(inputBlur).trigger('blur');
	
	showClocks();
	
	if (jQuery.validator ) {
	
		jQuery.validator.addMethod("required-selection", function( value, element ) {
			var sel_val = element.options[element.selectedIndex].value;
			return ( sel_val == -1 ? false : true )		
		}, "Fejl: Valg mangler!");
		
		jQuery.validator.addMethod("required-date-format", function( value, element ) {
			var dateRegEx = /^\d{2}\/\d{2}\/\d{4}$/;
			return ( dateRegEx.test(element.value));
		}, 'Fejl: Ugyldigt datoformat! Det skal v' + String.fromCharCode(230) + 're dd-mm-' + String.fromCharCode(229) + String.fromCharCode(229) + String.fromCharCode(229) + String.fromCharCode(229) + ' ( f.eks. 27-03-2009 )');
		
		jQuery.validator.addMethod("required-time-format", function( value, element ) {
			var dateRegEx = /^\d{2}\:\d{2}$/;
			return ( dateRegEx.test(element.value));
		}, 'Fejl: Ugyldigt tidsformat! Det skal v' + String.fromCharCode(230) + 're tt:mm ( f.eks. 13:45 )' );
		
		
		jQuery.validator.addMethod("required-time-value", function( value, element ) {
			var dateRegEx = /^(\d{2})\:(\d{2})$/;
			var m = value.match(dateRegEx);
			
			if ( m ) {
				var hours = parseInt( m[ 1 ] );
				var mins = parseInt( m[ 2 ] );
				if ( 
						( hours >= 0 ) 
					&&	( hours <= 23 )
					&&	( mins	>= 0 )
					&&	( mins  <= 59 )
				) {
					return true
				}
			}
			 
			return false;
			
		}, "Fejl: Dette er ikke en gyldig dato!");
	
	}
	
	if ( show_forgot_password ) {
		ShowForgotPasswordChange( show_forgot_password_enc, show_forgot_password_id );	
	}	
	
	if ( show_forgot_password_failed ) {
		ShowAlert( 'Fejl', 'Der skete en fejl da du fors' + String.fromCharCode(248) + 'gte at f' + String.fromCharCode(229) + ' en ny adgangskode. Pr' + String.fromCharCode(248) + 'v venligt igen!' );
	}
});

function ValidateChangePasswordForm() {
	
	$("#forgot-password-change-form").validate({
		rules: {
			new_password1: "required",
			new_password2: {
				equalTo: "#new_password1"
			}
		},
		messages: {
			new_password1: 'Husk at indtaste en adgangskode',	
			new_password2: {
				required: 'Husk at gentage adgangskoden',
				equalTo: 'De to adgangskoder er ikke ens'	
			}
		}
	});	
}

function ValidateAddEventForm() {

	$.dpText = {
		TEXT_PREV_YEAR		:	'Forrige ' + String.fromCharCode(229) + 'r',
		TEXT_PREV_MONTH		:	'Forrige m' + String.fromCharCode(229) + 'ned',
		TEXT_NEXT_YEAR		:	'N' + String.fromCharCode(230) + 'ste ' + String.fromCharCode(229) + 'r',
		TEXT_NEXT_MONTH		:	'N' + String.fromCharCode(230) + 'ste m' + String.fromCharCode(229) + 'ned',
		TEXT_CLOSE			:	'Luk',
		TEXT_CHOOSE_DATE	:	'V' + String.fromCharCode(230) + 'lg',
		HEADER_FORMAT		:	'mmmm yyyy'
	};

	$("#add-event-form .date input").datePicker({
		clickInput: true,
		createButton: false
	});
	
	
	
	$("#add-event-frm").validate({
		messages: {
			date: {
				required: "Fejl: Dato mangler!"
			},
			time: {
				required: "Fejl: Tidspunkt mangler!"
			},
			headline: "Fejl: Overskrift mangler!",
			text: "Fejl: Tekst mangler!",
			contact: "Fejl: Kontaktinformation mangler!",
			address: "Fejl: Sted/adresseinformation mangler!",
			location_id: {
				required: "Fejl: Information om lokation mangler!"
			}			
		}
	});
	
	
	
}





function inputFocus(e) {
    var src = e.target;
    if ($(src).val() == $(src).data('default')) {
        $(src).val('');
    }
    if (src.id == 'quick_applicantpassword') {
        $('#passwordoverlay').hide();
        src.focus();
    }
}

function inputBlur(e) {
    var src = e.target;
    if ($(src).val() == '') {
        if (src.id == 'quick_applicantpassword') {
            $('#passwordoverlay').show();
        } else {
            $(src).val($(src).data('default'));
        }
    }
}

function toggle_list_box(layer_id, obj_type, obj_id ) {
	if ( active_list_box_id == layer_id ) {
		collapse_list_box( layer_id );
		active_list_box_id = '';
	} else if ( active_list_box_id != layer_id ) {
		if ( active_list_box_id != '' ) {
			collapse_list_box( active_list_box_id )
		}
		expand_list_box( layer_id, false, obj_type, obj_id );	
	}
	
}

function collapse_list_box( layer_id ) {
	$("#" + layer_id )
		.attr("className","list-box collapsed")
		.find(".content")
		.html("")
		.end()
		.find(".headline a")
			.attr("title","Fold ud");
	active_list_box_id = '';
	$.cookie('active_list_box', '');
	$("#" + layer_id + " .listbox_headline_backgroundimage").remove();
}

function expand_list_box( layer_id, alwaysExpanded, obj_type, obj_id, overview_page_id ) {
	var url = 'getRepListBox_t_' + obj_type + '_id_' + obj_id 
	if ( overview_page_id ) {
		url += '_oid_' + overview_page_id;
	}
	url +='.html';
	
	
	
	$("#" + layer_id )
		.removeClass('loading')
		.addClass('loading')
		.find(".content")
			.load( url, function() {
				if (alwaysExpanded) {
					$("#" + layer_id ).attr("className","list-box always-expanded");
				} else {
					$("#" + layer_id ).attr("className","list-box expanded");
				}
				handleListBoxImage(layer_id);
			})
		.end()
		.find(".headline a")
			.attr("title","Fold ind");	
			
	if (!alwaysExpanded) {
		active_list_box_id = layer_id;
	}
}

function handleListBoxImage (layer_id) {
	var first_listbox_item_imageurl = $("#" + layer_id + " .content .item_image:first").css("background-image");
	if (first_listbox_item_imageurl) {
		var fadedImage = $('<div class="listbox_headline_backgroundimage"></div>')
			.css("background-image", first_listbox_item_imageurl)
			.fadeTo(0, 0.20)
			.click( function () {
					collapse_list_box(layer_id);
				});

		$("#" + layer_id + " .content .item_image:first").css("background-position", "0px -30px");
		
		$("#" + layer_id + " .headline").prepend(fadedImage);
	}
	
}


var current_sel_tab = 0;
function show_tab_box_image( i ) {
	if ( current_sel_tab != 0 ) {
		$("#tab-image-" + current_sel_tab ).hide();			
	}
	$("#tab-image-" + i ).show();	
	current_sel_tab = i;
}


var latest_sel_tab = null;
function mark_latest_tab( obj ) {
	
	if (latest_sel_tab != null ) {
		latest_sel_tab.className ='';		
	}
	
	obj.className = 'active';
	
	latest_sel_tab = obj;
	
}

function repNetChangeCountry( select_box ) {
	var sel_opt = select_box.options[ select_box.selectedIndex ];
	
	var values = sel_opt.value.split(";");
	
	if ( values[ 0 ] == '-1' ) {
		return false;
	}else if ( values[ 1 ] == '1' ) {
		sel_opt.value = values[ 0 ];
		select_box.form.submit();	
	} else {
		window.location = 'index.dsp?area=' + values[ 0 ]; 	
	}
	return false;
}


function showFade() {
	$("#fade").show();	
}

function hideFade() {
	$("#fade").hide();	
}


function showLogin(url) {
	if (url) {
		var page = (url.match(/page=\d+/i) && url.match(/page=(\d+)/i)[1]);
		var area = (url.match(/area=\d+/i) && url.match(/area=(\d+)/i)[1]);
		if (area) {
			$("#login_area").val(area);
			$("#login_page").val('');
		} else if (page) {
			$("#login_area").val('');
			$("#login_page").val(page);
		}
	}
	showFade();	
	$("#user-login").show();
	//$("#login-username").focus();
}

function showSearch(){
	showFade();
	$("#search").show();
}

function showMailafriend () {
	showFade();
	$("#mailafriend .capcha-image")[0].src = "gd.plex?p=" + $("#encHTTP").val();
	$("#mailafriend").show();
}

function hideBox(id) {
	$("#" + id).hide();
	hideFade();
}

function deleteArticleSubject(link_obj) {
	var subjectEl = link_obj.parentNode.parentNode.parentNode.parentNode;
	
	
	var save_field = $(subjectEl).find("input[name='save_field']");
	
	save_field.attr( "value", false );
	
	$(subjectEl).hide();	
}

function createSubjectField(label,fieldName,defValue,fieldTypeId,boldLabel) {
	
	var field;
	var field_value;
	if ( fieldTypeId != 4 ) {
		field = document.createElement('div');
		field.className = 'float field';
		
		
		var field_label = document.createElement('div');
		field_label.className = 'label';
		field_label.innerHTML = label;
		
		if (boldLabel == true ) {
			$(field_label).css("font-weight","bold");	
		}
		
		$(field_label).appendTo(field);		
		
		field_value = document.createElement('div');
		field_value.className = 'value';
	}
		
		if ( fieldTypeId == 0 ) { /* html */
			field_value.innerHTML = defValue;
		} else if ( fieldTypeId == 1 ) { /* text */
			var textInput = document.createElement('input');
			textInput.type = 'text';
			textInput.name = fieldName;
			textInput.value = defValue;
			$(textInput).appendTo($(field_value));
		} else if ( fieldTypeId == 2 ) { /* textarea */
			var textAreaInput = document.createElement('textarea');
			textAreaInput.name = fieldName;
			$(textAreaInput).val( defValue );
			$(textAreaInput).appendTo($(field_value));
		} else if ( fieldTypeId == 3 ) { /* upload */
			var fileInput = document.createElement('input');
			fileInput.type = 'file';
			fileInput.name = fieldName;
			$(fileInput).appendTo($(field_value));		
		} else if ( fieldTypeId == 4 ) { /* hidden */
			field = document.createElement('input');
			field.type = 'hidden';
			field.name = fieldName;
			field.value = defValue;
		} else if ( fieldTypeId == 5 ) { /* read only */
			var readonlyInput = document.createElement('input');
			readonlyInput.type = 'text';
			readonlyInput.name = fieldName;
			readonlyInput.value = defValue;
			readonlyInput.readOnly = 'readOnly';
			readonlyInput.className = 'readonly';
			$(readonlyInput).appendTo($(field_value));	
		} else if ( fieldTypeId == 6 ) { /* checkbox */
			var checkboxInput = document.createElement('input');
			checkboxInput.name = fieldName;
			checkboxInput.type = 'checkbox';
			$(checkboxInput).appendTo($(field_value));
		}
		
		if ( fieldTypeId != 4 ) {
			$(field_value).appendTo(field);		
		}
		
	return ( field );
}

function addArticleSubject( link_obj, dir, defValue ) {
	
	var defText = '';
	var defName = '';
	var defImageId = '';
	var defImageName = '';
	if (defValue != null ) {
		defText = defValue.text;
		defName = defValue.name	
		defImageId = defValue.imageId;
		defImageName = defValue.imageName
	}
	
	var newSubject = document.createElement('div');
	newSubject.className = 'float subject';
	
	var name_field = createSubjectField( 'Emne:', 'articleName', defName, 1, true  );
	$(name_field).appendTo($(newSubject));
	
	var text_field = createSubjectField( 'Tekst:', 'articleText', defText, 2 );
	$(text_field).appendTo($(newSubject));
	
	var image_field = createSubjectField( 'Valgt billede:', 'imageName', defImageName, 5 )
	$(image_field).appendTo( $(newSubject) );
	
	if ( defImageId != 0 ) {
		var del_image_field = createSubjectField( 'Slet billede:', 'deleteImage', null, 6 )
	$(del_image_field).appendTo( $(newSubject) );			
	}
	
	var image_upload = createSubjectField( 'V&aelig;lg billede:', 'articleImage', null, 3 )
	$(image_upload).appendTo( $(newSubject) );
	
	var image_id_field = createSubjectField( 'hidden', 'currentImageId', defImageId, 4 )
	$(image_id_field).appendTo( $(newSubject) )
	
	var save_field = createSubjectField( 'hidden', 'save_field', true, 4 );
	$(save_field).appendTo( $(newSubject) )
	
	
	var btn_field = createSubjectField('','','<div class="button"><input type="button" onclick="deleteArticleSubject(this);return false" value="slet" /></div> <div class="button"><input type="button" onclick="addArticleSubject(this,-1);return false;" value="tilf&oslash;j f&oslash;r" /></div> <div class="button"><input type="button" onclick="addArticleSubject(this,+1);return false;" value="tilf&oslash;j efter" /></div>',0);
	$(btn_field).appendTo($(newSubject));
	
	if ( dir != 0 ) {
		var subjectEl = link_obj.parentNode.parentNode.parentNode.parentNode;	
		if ( dir == 1 ) {
			$(newSubject).insertAfter($(subjectEl));
		} else {
			$(newSubject).insertBefore($(subjectEl));
		}				
	} else {
		$(newSubject).appendTo($("#article-subjects"));
	}
	
	if ( defValue == null ) {
		document.location.replace('#anchor_bottom');
		$(name_field).find("input").focus();
	}
}

function printPage() {
	var url = document.location.href;
	url += (url.match(/\?/)) ? '&' : '?';
	url += 'print=1';
		
	window.open(url);
}

function showClocks() {
	var padZeros = function () {
		return ('00' + arguments[0]).slice(-2);
	}

	//Copenhagen
	var time = new Date();
	var offset_copenhagen = $("#clock_copenhagen").length && parseInt($("#clock_copenhagen").attr("class").match(/\soffset(.*)/)[1]);
	time.setMinutes(time.getMinutes() + time.getTimezoneOffset() + (offset_copenhagen / 60));
	$("#clock_copenhagen").text(padZeros(time.getHours()) + ':' + padZeros(time.getMinutes()));
	
	//London
	var time = new Date();
	var offset_london = $("#clock_london").length && parseInt($("#clock_london").attr("class").match(/\soffset(.*)/)[1]);
	time.setMinutes(time.getMinutes() + time.getTimezoneOffset() + (offset_london / 60));
	$("#clock_london").text(padZeros(time.getHours()) + ':' + padZeros(time.getMinutes()));
	
	//New York
	var time = new Date();
	var offset_newyork = $("#clock_newyork").length && parseInt($("#clock_newyork").attr("class").match(/\soffset(.*)/)[1]);
	time.setMinutes(time.getMinutes() + time.getTimezoneOffset() + (offset_newyork / 60));
	$("#clock_newyork").text(padZeros(time.getHours()) + ':' + padZeros(time.getMinutes()));
	
	//Hong Kong
	var time = new Date();
	var offset_hongkong = $("#clock_hongkong").length && parseInt($("#clock_hongkong").attr("class").match(/\soffset(.*)/)[1]);
	time.setMinutes(time.getMinutes() + time.getTimezoneOffset() + (offset_hongkong / 60));
	$("#clock_hongkong").text(padZeros(time.getHours()) + ':' + padZeros(time.getMinutes()));
	
	window.setTimeout(showClocks, 5000);
}

function ShowBox( box_id, box_title, options ) {
	var box = document.getElementById( box_id );
	var contentDiv;
	
	
	options = ( options == null ? {} : options );
	options.width = ( options.width == null ? 392 : options.width );	
	options.showCloseButton = ( options.showClosebutton == null ? true : options.showCloseButton );
	var content_url = options.content;
	
	if (box == null ) {
		var box = document.createElement('div');	
		box.id = box_id;
		box.className = "popupbox";
		if ( options.width ) {
			$(box).css("width", options.width );		
		}
		
		var innerDiv = document.createElement('div');
		innerDiv.className = 'inner';
		if ( options.width ) {
			$(innerDiv).css( "width", options.width - 10 );	
			$(innerDiv).css( "left", -(options.width / 2 ) );
		}
		
		$(innerDiv).appendTo(box);
		
		var headline = document.createElement('div');
		headline.className = 'headline';
		headline.innerHTML = box_title;
		if ( options.width ) {
			$(headline).css( "width", options.width - 15 );
		}
		
		$(headline).appendTo(innerDiv);
		
		if ( options.showCloseButton == true ) {
			var closeBtn = document.createElement('div');
			closeBtn.className = 'closePopup';
			closeBtn.innerHTML = '<a onfocus="if(this.blur)this.blur();" href="#" onclick="\$(this.parentNode.parentNode.parentNode).hide();hideFade();return false"></a>';
			$(closeBtn).appendTo(innerDiv);	
		}
		
		contentDiv = document.createElement('div');
		contentDiv.className = 'box-content';
		$(contentDiv).appendTo(innerDiv);
		
		document.body.appendChild( box );
	} 
	
	var scrollTop = $(window).scrollTop();
	
	if ( content_url ) {
		$.ajax({
		   type: "GET",
		   url: content_url,
		   async: false,
		   success: function( htmlResult ){
		    	$("#" + box_id + " .box-content").html(htmlResult);
				var content_height = $("#" + box_id ).height();
				$("#" + box_id + " .inner").css( "top", -( content_height / 2 ) + scrollTop );
		    	showFade();
		    	$(box).show()
		    	
		    	if ( options.onShow ) {
		    		options.onShow();	
		    	}
		   }
		 });
	} else {
		if ( options.html ) {
			$("#" + box_id + " .box-content").html( options.html );
		}
				
		var content_height = $("#" + box_id ).height();
		
		if ( options.top ) {
			$("#" + box_id + " .inner").css( "top", options.top + scrollTop );		
		} else {
			$("#" + box_id + " .inner").css( "top", -( content_height / 2 ) + scrollTop );
		}
				
		showFade();
		$(box).show();	
	}
}

function ShowAlert( boxTitle, message ) {
	var html_message = '<div class="form"><div class="field"><p>' + message + '</p></div></div>';
	ShowBox( "alert-box", boxTitle,	{ html: html_message } );
}

function showMemberProfile() {
	if($("#user-profile").css("display") == "none"){
		$("#showMemberProfileButton").text("Skjul");
		$("#user-profile").slideDown("fast");
	} else {
		$("#showMemberProfileButton").text("Vis");
		$("#user-profile").slideUp("fast");
	}
	
}

function showMemberEdit( params ) {
	
	if (params == null ){
		params = {};	
	}
	
	var user_edit_box = document.getElementById('member-edit');
	var contentDiv;
	
	showFade();
	
	if (user_edit_box == null ) {
		var user_edit_box = document.createElement('div');	
		user_edit_box.id = 'member-edit'
		
		var innerDiv = document.createElement('div');
		innerDiv.className = 'inner';
		$(innerDiv).appendTo(user_edit_box);
		
		var headline = document.createElement('div');
		headline.className = 'headline';
		
		if ( params.new_user ) {
			headline.innerHTML = 'Opret bruger';
		} else {
			if ( params.user_type == 'normal user' ) {
				headline.innerHTML = 'Ret brugeroplysninger';
			} else {
				headline.innerHTML = 'Ret medlemsoplysninger';
			}
		}
		
		$(headline).appendTo(innerDiv);
		
		var closeBtn = document.createElement('div');
		closeBtn.id = 'closeMemberEdit';
		closeBtn.className = 'closePopup';
		closeBtn.innerHTML = '<a onfocus="if(this.blur)this.blur();" href="#" onclick="\$(this.parentNode.parentNode.parentNode).hide();hideFade();return false"></a>';
		$(closeBtn).appendTo(innerDiv);	
		
		contentDiv = document.createElement('div');
		contentDiv.className = 'box-content';
		$(contentDiv).appendTo(innerDiv);
		
		document.body.appendChild( user_edit_box );
	} 
	
	 $.ajax({
	   type: "GET",
	   url: "GetMemberDataForm.plex",
	   data: params,
	   async: false,
	   success: function( htmlResult ){
	    	$("#member-edit .box-content").html(htmlResult);
	   }
	 });

	
	
	$(user_edit_box).show();
}

function deleteThread() {
	
	//Items to be deleted
	var params = [];
	var ids = $("#TopicItemsBox input:checked");
	ids.each(function() { params.push($(this).attr("name"))});
	$.ajax({
	  type: "POST",
	  url: "EditTopicItems.plex",
	  data: "ids="+params,
	  async: false,
	  success: function( htmlResult ){
	   	$("#TopicItemsBox").html(htmlResult);
	  }
	});
}

function showThreads() {
	var params = [];
	var ids = $("#TopicsBox input:checked");
	ids.each(function() { params.push($(this).attr("name"))});
	document.location.replace( 'index.dsp?page=3097&show_only_subscribed=1' );
	
}

function newThread() {
	document.location.replace( 'index.dsp?page=3097&action=add_item' );
}

function saveGroups() {
	var params = [];
	var ids = $("#groupsBox input:checked");
	ids.each(function() { params.push($(this).attr("name"))});
	$.ajax({
		type: "GET",
		url: "EditTopics.plex",
		data: "ids="+params,
		async: false,
		success: function( htmlResult ){
			$("#TopicsBox").html(htmlResult);
		}
	});
}

function showThread() {
	window.location = "index.dsp?page=3097";
}

function showAllContacts(all, search_str, country, name, group){ // all = "0" or "1"
	if(all){
		var url = "index.dsp?page=3106&all="+all;
		if(country != "Vælg et land"){url += "&country="+country;}
		if(group != 0){url += "&group="+group;}
		if(name != "Indtast navn"){url += "&name="+name;}
		if(search_str != "Fritekst s\u00F8gning"){url += "&search_str="+search_str;}
		window.location = url;
	}else{
		
		window.location = "index.dsp?page=3106&user_id="+search_str;
	}
	
}

function addContact(id){
	$.ajax({
	type: "GET",
	url: "AddContact.plex",
	data: "id="+id,
	async: false,
	success: function( htmlResult ){
		$("#contact_"+id).html(htmlResult);
	}
	});
}

function addFavContact(id){
	$.ajax({
	type: "GET",
	url: "AddContact.plex",
	data: "fav_id="+id,
	async: false,
	success: function( htmlResult ){
		$("#contact_"+id).html(htmlResult);
	}
	});
}

function deleteFavContact(id) {
	$.ajax({
	type: "GET",
	url: "DeleteContact.plex",
	data: "FavDeleteId="+id,
	async: false,
	success: function( htmlResult ){
		$("#contact_"+id).html(htmlResult);
	}
	});
}

function deleteContact(id) {
	$.ajax({
	type: "GET",
	url: "DeleteContact.plex",
	data: "DeleteId="+id,
	async: false,
	success: function( htmlResult ){
		$("#contact_"+id).html(htmlResult);
	}
	});
}

function ThreadFade(id) {
	if($("#"+id).next().is(":hidden")){
		$("#"+id).next().slideDown();
	} else {
		$("#"+id).next().slideUp();
	}
}

function UpdateMemberDataForm(params) {		
	
	if ( params.new_user_created != 1 ) {
		params.update = '1';
	};	
	
	$.ajax({
		type: "GET",
		url: "GetMemberDataForm.plex",
		data: params,
		success: function( htmlResult ){
			$("#member-edit .box-content").html(htmlResult);
			
			if ( params.image_error > 0 ) {
				var err_msg;
				if (params.image_error == 1 ) {
					err_msg = 'Billedet blev ikke opdateret fordi det var st' + String.fromCharCode(248) + 'rre end de tilladte 2 mb';
				} else if ( params.image_error == 2 ) {
					err_msg = 'Billedet blev ikke opdateret fordi det ikke var i JPG eller PNG formatet';
				} else if ( params.image_error == 3 ) {
					err_msg = 'Billedet blev ikke uploadet fordi det var st' + String.fromCharCode(248) + 'rre end 85 x 110 pixels';
				}
				alert( err_msg );
			}
		}
	});
}

function ShowForgotPassword() {
	hideBox('user-login');	
	ShowBox( 
		"forgot-password", 
		"Glemt adgangskode", 
		{ content : "GetForgotPasswordForm.plex?action=init" }
	);
}

function ShowForgotPasswordAnswer(username) {
	hideBox('forgot-password');	
	ShowBox( 
		"forgot-password-answer", 
		"Glemt adgangskode", 
		{ content : "GetForgotPasswordForm.plex?action=send&send_username=" + username }
	);	
}

function ShowForgotPasswordChange( enc, user_id ) {
	ShowBox( 
		"forgot-password-change", 
		"Glemt adgangskode", {
			onShow: ValidateChangePasswordForm,
			content: "GetForgotPasswordForm.plex?action=change&enc=" + enc + "&user_id=" + user_id		
		}
	);	
}

function parentItemIdChange(r, topic_id) {
	if ($(r).val() == 0) {
		$(r.form.topic_id).removeAttr('disabled');
	} else {
		$('#debate-topic-id-select').val(topic_id);
		if (!$(r.form.topic_id).attr('disabled')) {
			$(r.form.topic_id).attr('disabled', 'disabled');
		}
	}
}

function showAddEvent( action, id ) {
	
	var box_label;
	if ( action == 'edit_event' ) {
		box_label = 'Rediger event';	
	} else {
		box_label = 'Tilf' + String.fromCharCode(248) + 'j event';	
	}
	
	ShowBox(
		"add-event",
		box_label, {
			content : "GetAddEventForm.plex?action=" + action + '&id=' + id,
			showCloseButton : false,
			width: 420,
			onShow : ValidateAddEventForm
		}
	); 
			
}

function changeEventCountry( select_el, location_id ) {
	var sel_opt = select_el.options[ select_el.selectedIndex ];
	
	if ( sel_opt.value != -1 ) {
		$("#add-event-form .location .value").html("Opdaterer lokationer. Vent venligst...");
		$("#add-event-form .location .value").load("GetLocationOptions.plex", { country_id: sel_opt.value, location_id: location_id });		
	} else {
		$("#add-event-form .location select").attr("disabled", true); 
	}
}

function ShowCalendarTools( event_id ) {
	$.ajax({
		type: "GET",
		url: "GetCalendarTools.plex?event_id=" + event_id,
		success: function( htmlResult ){
			$("#page-tools").html(htmlResult);
		}
	});		
}

function qp_accept_terms( terms_page_id ) {
	ShowBox(
		"qp-terms",
		'Godkendelse af handelsbetingelser', {
			content: 'accept_terms.plex?page=' + terms_page_id,
			showCloseButton : false,
			width: 420
		}
	);
	return false;		
}



function load_meeting_place( params, debate_page ) {
	if(debate_page){
		window.location = "index.dsp?page=3088";
	} else {
		$("#MP-main").load('get_MP_main_column.plex', params, function(){
			$("#MP-right").load('get_MP_right_column.plex', params);	
		});
	}
	
	
	
}

function reload_MP_left() {
	$.get('get_MP_main_column.plex', function( data ) {
		$('#MP-main').html( data );	
		if ( $("#MP-right").html() == '' ) {
			reload_MP_right();
		}
	});	
}

function reload_MP_right() {
	$.get('get_MP_right_column.plex', function( data ) {
		$("#MP-right").html( data );	
	});
	
}

function activate_MP_profile( params ) {
	params.action = 'activate_profile';

	$("#MP-main").load( 'get_MP_main_column.plex', {action: "activate_profile"}, function(){
		$("#MP-right").load('get_MP_right_column.plex', {action: "activate_profile"});	
	
	});
	
};

function deactivate_MP_profile( params ) {
	params.action = 'deactivate_profile';

	$("#MP-main").load( 'get_MP_main_column.plex', {action: 'deactivate_profile'}, function(){
		$("#MP-right").load('get_MP_right_column.plex', {action: 'deactivate_profile'});	
	
	});
	
};


function submit_member_data(link_obj) {
	var errors = new Array();
	
	var frm = document.forms['member_edit_form'];
	
	var is_new_user = false;
	var is_new_user_field = frm.elements['new_user'];
	if ( is_new_user_field ) {
		if ( is_new_user_field.value == 1 ) {
			is_new_user = true;	
		} 	
	}
	
	var group_ids = new Array();
	var groups_ids_field = frm.elements['group_ids'];
	if ( groups_ids_field ) {
		var group_ids_str = groups_ids_field.value;
		group_ids = group_ids_str.split(',');
	};
	
	var is_normal_user = false;
	var is_member = false;
	for (var i = 0; i < group_ids.length; i++ ) {
		if ( group_ids[ i ] == 7 ) {
			is_normal_user = true;	
		} else if ( group_ids[ i ] == 3 ) {
			is_member = true;	
		}	
	};
	
	// Requirements for members
		if ( is_member ) {
			var extra_address_info = frm.elements['extra_address_info'].value;
			if ( extra_address_info == '' ) {
				errors.push("Feltet 'Adresse 1' mangler at blive udfyldt");
			}
			
			var postal_no_1 = frm.elements['postal_no_1'].value;
			var postal_no_2 = frm.elements['postal_no_2'].value;
			if ( (postal_no_1 == '') && ( postal_no_2 == '' ) ) {
				errors.push('Et af postnummer felterne skal udfyldes');	
			}			
		}
		
	// Requirements for all users
		var city = frm.elements['city'].value;
		if ( city == '' ) {
			errors.push("Feltet 'By' mangler at blive udfyldt");	
		}
		
		var show_conditions = frm.elements['show_conditions'].checked;
		if ( show_conditions == '' ) {
			errors.push("Feltet 'Betingelser' mangler at blive udfyldt");	
		}
		
		var country = frm.elements['country'].value;
		if ( country == '' ) {
			errors.push( "Feltet 'Land' mangler at blive udfyldt" );
		}
		
		// name
		var firstname = frm.elements['firstname'].value;
		var lastname = frm.elements['lastname'].value;
		if ( firstname == '' ) {
			errors.push( "Feltet 'Fornavn' mangler at blive udfyldt" );
		}
		
		if ( lastname == '' ) {
			errors.push( "Feltet 'Efternavn' mangler at blive udfyldt" );
		}
		
		var change_password = frm.elements['change_password'].value;
		var change_password_again = frm.elements['change_password_again'].value;
		if(change_password != '' || change_password_again != '') {
			if(change_password != change_password_again){
				errors.push('De nyindtastede adgangskoder er ikke ens!');
			}
		}
		
		// birthdate
		var birthdate = frm.elements['birthdate'].value;
		if (( birthdate != '' ) && ( birthdate != 'dd-mm-' + String.fromCharCode(229) + String.fromCharCode(229) + String.fromCharCode(229) + String.fromCharCode(229) + '' ) ){
			if ( ! birthdate.match( /^\d{2}\-\d{2}\-\d{4}$/ ) ) {
				errors.push( 'Feltet ' + String.fromCharCode(39) + 'F' + String.fromCharCode(248) + 'dselsdato:' + String.fromCharCode(39) + ' er angivet i et forkert format. Det skal angives i formatet: dd-mm-' + String.fromCharCode(229) + String.fromCharCode(229) + String.fromCharCode(229) + String.fromCharCode(229) + ' f.eks. 03-05-1965' );
			}
		}
		
		// E-mail
		var email = frm.elements['email'].value;
		var old_email = frm.elements['old_email'].value;
		if ( email == '' ) {
			errors.push( 'E-mail mangler' );	
		} else {
			var params = { email : email };
			if ( is_normal_user ) {
				params.check_username = '1';	
				params.old_email = frm.elements['old_email'].value;
			}
			
			$.ajax({
			   type: "GET",
			   url: 'validate_email.plex',
			   data: params, 
			   async: false,
			   success: function( htmlResult ){
			   		var result = htmlResult.split(',');
			   		var email_format_ok = result[ 0 ];
			   		var email_exist = result[ 1 ];
			   		
			   		if ( email_format_ok == '0' ) {
			   			errors.push('Gyldig E-mail mangler');
			   		}
			   		if ( email_exist == '0' ) {
			   			errors.push('En bruger med denne e-mailadresse som brugernavn eksisterer allerede.');	
			   		}
			   }
			 });
		}
	
		if ( errors.length > 0 ) {
			var msg = '';
			for ( var i = 0; i < errors.length; i++ ) {
				msg += '- ' + errors[ i ] + '\n';
			}
			
			alert( 'Fejl i indtastning:\n\n' + msg );		
		} else {
			$(link_obj).css('background-image','url(graphics/ajax-loader.gif)');
			$(link_obj).html('Gemmer...');
			frm.submit();
		}
	
		return false;
		
}

function set_MP_default_birthdate( el ) {
	if ( el.value == 'dd-mm-' + String.fromCharCode(229) + String.fromCharCode(229) + String.fromCharCode(229) + String.fromCharCode(229) + '' ) {
		el.value = ''
	};
}		

function toggle_MP_mails( id, user_id ) {
	var el = $('#MP-mails .' + id );
	
	var header = el.find('.header');
	
	var messages = el.find('.messages');
	
	if ( header.hasClass('expanded' ) ) {
		header.removeClass('expanded');
		header.addClass('collapsed');
		messages.slideUp('normal');
	} else {
		header.removeClass('collapsed');
		header.addClass('expanded');
		
		messages.load( 'MP_update_mail_list.plex', { type : id, user_id: user_id }, function() {
			messages.slideDown('normal');
		} );
		
	}	
}

function toggle_debates(topic_id, topic_header_id) {
	var header = $('#'+topic_header_id);

	if ( header.hasClass('expanded')) {
		header.removeClass('expanded');
		header.addClass('collapsed');
		$('#'+topic_id).slideUp('fast');
	} else {
		header.removeClass('collapsed');
		header.addClass('expanded');
		$('#'+topic_id).slideDown('fast');	
	}	
}

function show_all_MP_mails( id, user_id ) {
	var el = $('#MP-mails .' + id );
	var messages = el.find('.messages');
	messages.load( 'MP_update_mail_list.plex', { type : id, user_id: user_id, show_all: 1 });	
}

function show_limited_MP_mails( id, user_id ) {
	var el = $('#MP-mails .' + id );
	var messages = el.find('.messages');
	messages.load( 'MP_update_mail_list.plex', { type : id, user_id: user_id });	
}

function create_MP_mail( params ) {
	$('#MP-main').load( 'MP_create_mail.plex', params );
}

function send_MP_mail( params ) {
	var valid = true;
	
	params.message = $('#mail-reply-text').val();
	if ( params.message == '' ) {
		valid = false;	
	}
	
	if ( params.new_thread == '1' ) {
		params.subject = $('#MP-mail-subject-text').val();
		params.receiver_id = $('#MP-mail-receiver-select').val();
		if ( ( params.subject == '') || ( params.receiver_id == -1 ) || ( params.receiver_id == '---' ) ) {
			valid = false;	
		}
	}
	
	var request_accepted_valid = false;
	if ( $('#contact-acceptance-field').length ) {
		var request_accepted = $("input[@name='request_accept']:checked").val();
		
		if ( request_accepted != 'on' ) {
			params.request_accepted = request_accepted;
			request_accepted_valid = true;
		}
	} 	
	
	if ( valid || ( params.request_contact == 1 ) || request_accepted_valid ) {
		$.post( 'MP_save_mail.plex', params, function(data, textStatus) { 
			var ret_args = data.split(/,/);
			var message_id = ret_args[ 0 ];
			var starting_item_id = ret_args[ 1 ];
			
			if ( params.call_from_outside == '1' ) {
				create_MP_mail({ message_id: message_id, starting_item_id: starting_item_id, call_from_outside: 1 });
			} else {
				create_MP_mail({ message_id: message_id, starting_item_id: starting_item_id });
			}
			if(params.request_contact == 1){
				alert("Din anmodning om kontakt er sendt.");
			}
		} );	
	} else {
		alert('Alle felter skal udfyldes!');	
	}
}

function debate_item_delete_confirm( params ) {
	var confirm_text;
	if ( params.has_sub_items ) {
		confirm_text = 'Dette vil slette indl' + String.fromCharCode(230) + 'gget samt alle underindl' + String.fromCharCode(230) + 'g. ' + String.fromCharCode(216) + 'nsker du virkelig at g' + String.fromCharCode(248) + 're dette?';		
	} else {
		confirm_text = String.fromCharCode(216) + 'nsker du virkelig at slette indl' + String.fromCharCode(230) + 'gget?';		
	}
	
	if ( confirm( confirm_text ) ) {
		document.location.replace( params.url );	
	} 	
}

function submit_debate_form( params ) {
	var frm = document.forms['add_debate_item_form'];
	var frm_headline = frm.elements['name'].value;
	var frm_text = frm.elements['text'].value;
	var frm_email = frm.elements['email'].value;
	
	var topic_sel_el = $('#debate-topic-id-select');
	var errors = new Array();
	if ( !topic_sel_el.attr('disabled') ) {
		var category_id = topic_sel_el.val();
		if ( category_id == 0 ) {
			errors.push("- En v" + String.fromCharCode(230) + "rdi i feltet 'Kategori:' mangler at blive valgt!");
		}
	}
	
	if ( frm_headline == '' ) {
		errors.push("- Feltet 'Overskrift:' mangler at blive udfyldt!");	
	}
	
	if ( frm_text == '' ) {
		errors.push("- Feltet 'Tekst:' mangler at blive udfyldt!");	
	}
	
	if ( frm_email == '' ) {
		errors.push("- Feltet 'E-mail:' mangler at blive udfyldt!");	
	}
	
	if ( errors.length > 0 ) {
		var error_msg = errors.join('<br />');
		ShowAlert( 'Fejl i indtastning', error_msg );
	} else {
		frm.submit();
	}	
};

function show_contact_profile( params, debate_page ) {
	if(debate_page){
		$(".box").load('get_MP_main_column.plex?', params, function(){
		});
	} else {
		$("#MP-main").load('get_MP_main_column.plex?', params, function(){
			$("#MP-right").load('get_MP_right_column_light.plex', params);
		});
	}
	
	
}

function tip_moderator( item_id ) {
	ShowBox(
		'tip-moderator-box',
		'Tip moderator', {
			content: 'get_tip_moderator_form.plex?item_id=' + item_id,
			width: 460
		}
	);
}


function submit_tip_form() {
	var comment = $('#tip-comment').val();
	var email = $('#tip-email').val();
	var item_id = $('#tip-item-id').val();
	
	$.post('tip_moderator.plex', { comment: comment, email: email, item_id: item_id }, function( result ) {
		
		if ( result == '0' ) {
			hideBox( 'tip-moderator-box' );
			ShowAlert( 'Sendt', 'Dit tip er nu blevet sendt til en moderator.' );	
		} else {
			ShowAlert( 'Fejl', 'Der opstod en fejl ved afsendelse. Pr' + String.fromCharCode(248) + 'v igen senere og kontakt Danes hvis problemet forts' + String.fromCharCode(230) + 'tter. Oplys da fejlkoden: 00' + result );	
		}
	} );	
}

function submit_e_mail_form() {
	var message = $('#e-mail-message').val();
	var sender_id = $('#e-mail-sender-id').val();
	var receiver_id = $('#e-mail-receiver-id').val();
	
	$.post('send_email.plex', { message: message, sender_id: sender_id, receiver_id: receiver_id }, function( result ) {
		
		if ( result == '0' ) {
			hideBox( 'send-email-box' );
			ShowAlert( 'Sendt', 'Dit e-mail er nu blevet sendt.' );	
		} else {
			ShowAlert( 'Fejl', 'Der opstod en fejl ved afsendelse. Pr' + String.fromCharCode(248) + 'v igen senere og kontakt Danes hvis problemet forts' + String.fromCharCode(230) + 'tter. Oplys da fejlkoden: 00' + result );	
		}
	} );	
}





function toggle_tab( tab_el, layer_el ) {
	var tab = $(tab_el);
	var layer = $(layer_el);
	
	
	/* change tab */
	if ( window.current_tab != null ) {
		
		if ( $(window.current_tab).hasClass( 'button' ) ) {
			$(window.current_tab).find('a').toggleClass( 'active' );		
		} else { 
			$(window.current_tab).toggleClass( 'active' );		
		}
	}
	
	window.current_tab =  tab_el;
	if ( $(window.current_tab).hasClass( 'button' ) ) {
		$(window.current_tab).find('a').toggleClass( 'active' );		
	} else { 
		$(window.current_tab).toggleClass( 'active' );		
	}
	
	/* change layer */
	if ( window.current_layer != null ) {
		$(window.current_layer).toggleClass( 'active' );		
	}
	
	window.current_layer =  layer_el;
	$(window.current_layer).toggleClass( 'active' );		

}

function show_email_client( params ) {
	ShowBox(
		'send-email-box',
		'Skriv besked', {
			content: 'get_email_client_form.plex?receiver_id=' + params.user_id	
		}
	);
}

function deleteProfileImage(image_url) {	
	var answer = confirm ("Er du sikker på at du vil slette dit profilbillede?")
	if(answer){
		$.post('SaveMemberData.dsp', { delete_profile_image: image_url }, function( result ) {
			alert(result);
		});
	}
}