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', $("label[for='mailafriend-message']").text()).focus(inputFocus).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, content_url, 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 );
	
	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 );
	} 
	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 ) );
		    	showFade();
		    	$(box).show()
		    	
		    	if ( options.onShow ) {
		    		options.onShow();	
		    	}
		   }
		 });
	} else {
		if ( options.html ) {
			$("#" + box_id + " .box-content").html( options.html );
		}
		
		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,	null, { html: html_message } );
}

function showMemberEdit() {
	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';
		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",
	   async: false,
	   success: function( htmlResult ){
	    	$("#member-edit .box-content").html(htmlResult);
	   }
	 });

	
	
	$(user_edit_box).show();
}


function UpdateMemberDataForm() {		
	$.ajax({
		type: "GET",
		url: "GetMemberDataForm.plex?update=1",
		success: function( htmlResult ){
			$("#member-edit .box-content").html(htmlResult);
		}
	});
}

function ShowForgotPassword() {
	hideBox('user-login');	
	ShowBox( 
		"forgot-password", 
		"Glemt adgangskode", 
		"GetForgotPasswordForm.plex?action=init"
	);
}

function ShowForgotPasswordAnswer(username) {
	hideBox('forgot-password');	
	ShowBox( 
		"forgot-password-answer", 
		"Glemt adgangskode", 
		"GetForgotPasswordForm.plex?action=send&send_username=" + username
	);	
}

function ShowForgotPasswordChange( enc, user_id ) {
	ShowBox( 
		"forgot-password-change", 
		"Glemt adgangskode", 
		"GetForgotPasswordForm.plex?action=change&enc=" + enc + "&user_id=" + user_id
		, {
			onShow: ValidateChangePasswordForm		
		}
	);	
}

function parentItemIdChange(r) {
	if ($(r).val() == 0) {
		$(r.form.topic_id).removeAttr('disabled');
	} else {
		$(r.form.topic_id)[0].selectedIndex = 0;
		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,
		"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',
		"accept_terms.plex?page=" + terms_page_id, {
			showCloseButton : false,
			width: 420
		}
	);
	return false;		
}