var email_clicked		= false;
var focused				= false;
var def_stop_date		= '';
var custom_stop			= '';
var focused				= false;
var stop_focused		= false;
var custom_start		= '';
var skip_submit_check	= false;
var person_data			= null;
var person_callcb		= false;
var person_callback		= null;
var collect_callback	= null;
var collected_data		= null;
var countdown			= 10;
var countdown_int		= null;

$(document).ready( function() {
	$('body').selectbox_all();
/*	alert( 'Vänligen avstå ifrån att använda formuläret tills dess att vi säkert kan säga att det fungerar normalt!' );*/

	var button = $('#leader_photo'), interval, leader_photo_def_src = '';
	$('#course_id option')[0].selected = true;
	$('#course_id').selectbox_reset();

	/*$('#submitBtn,.selectWrap').hover(	function() { $(this).addClass( 'hover' ); },
										function() { $(this).removeClass( 'hover' ); } );*/

	$('#submitBtn,#leader_photo,.selectWrap').mousedown( function() {
		$(this).addClass( 'pushed' ).addClass( 'pushed_' );
	}).mouseup( function() {
		$(this).removeClass( 'pushed' ).removeClass( 'pushed_' );
	}).mouseout( function( e ) {
		$(this).removeClass( 'pushed' );
	}).mouseover( function( e ) {
		if ($(this).hasClass( 'pushed_' )) {
			$(this).addClass( 'pushed' );
		}
	});

	//$('#contact_link').attr( 'href', $('#contact_link').attr( 'href' ) + '?ajax' );
	$('#contact_link').fancybox( {
		hideOnContentClick:	false,
		linkAppendix:		'?ajax',
		callbackOnShow: function() {
			ajaxUp.disable();
			$('#fancy_title_main div').html( $('#contact_link').attr( 'alt' ) );
			$('#contact_sendmail').hide();
			email_clicked = false;
			$('#email a').click( function() {
				if (email_clicked) {
					return false;
				}
				email_clicked = true;
				$('<img />').attr( 'src', k_img_path + 'ui/ani/ajax-loader.gif' ).appendTo( '#email' );
				url	= $('#sendmail_link').attr( 'href' ) + '?ajax';
				$.get( url, function( data ) {
					loadIntoFancy( data );
					$('#contact_form').submit( contact_form_submit );
				} );
				return false;
			} );
		},
		callbackOnClose: function() {
			ajaxUp.enable();
		}
	} );
	$('#collect_leader_info').fancybox( {
		hideOnContentClick:	false,
		linkAppendix:		'?ajax',
		frameWidth:			600,
		callbackOnShow:		function() {
			ajaxUp.disable();
			//$('#thanks').hide();

			if ( person_data.people.length > 1 ) {
				// Handle multiple...
			} else {
				person  = person_data.people[0];

				$('#c_person_pid').text( person.pid );
console.log( 'Person:  ' + person.name + ';' );
				phone = person.telephone;
				if ( ( person.mobile != '' ) && ( person.mobile != null ) ) {
					phone += ( phone != '' ? '&nbsp;/&nbsp;' : '' ) + person.mobile;
				}

				$('#l_name').text( person.name );
				$('#l_email').html( '<a href="mailto:' + person.email + '">' + person.email + '</a>'  );
				$('#l_phone').html( phone );
				$('#l_city').text( person.city );

				if ( ( person.zipcode == null ) && ( person.street == null ) ) {
					$('#l_addr_row').hide();
				} else {
					$('#l_address').html( person.street + "<br />\n" + person.zipcode + "&nbsp;" + person.city );
				}

				if ( ( person.photo == '' ) || ( person.photo == null ) ) {
					$('#l_photo_row').hide();
				} else {
					$('#l_photo').attr( 'src', $('#l_photo').attr( 'src' ) + person.photo );
				}

				$('#yes_btn').click( function() {
					person_callcb   = true;
					$('#person_pid').val( $('#c_person_pid').text() );
					fancy_close();
				} );
				$('#yes_but_btn').click( function() {
					person_callcb   = true;
					$('#person_pid').val( $('#c_person_pid').text() );
					fancy_close();
				} );
				$('#no_butemail_btn').click( function() {
					person_callcb   = true;
					fancy_close();
				} );
				$('#no_sharedemail_btn').click( function() {
					person_callcb   = true;
					$('#shared_email').val( true );
					fancy_close();
				} );
				$('#no_notatall_btn').click( function() {
					person_callcb   = true;
					fancy_close();
				} );
				$('#cancel_btn').click( function() { fancy_close(); } );
			}
		},
		callbackOnClose: function() {
			ajaxUp.enable();

			if ( person_callcb && ( typeof( person_callback ) == 'function' ) ) {
				person_callback();
			}
			person_callcb   = false;
		}
	} );
	$('#collect_cong_info').fancybox( {
		hideOnContentClick:	false,
		linkAppendix:		'?ajax',
		frameWidth:			600,
		callbackOnShow:		function() {
			ajaxUp.disable();
			$('#thanks').hide();
			//$('#fancy_title_main div').html( $('#collect_cong_info').attr( 'alt' ) );

			$('#cong_name').text( $('.congregation').val() );
			$('#name').val( $('.congregation').val() );

			$('#congrForm').ajaxSubmit( null, function( data ) {
				if ( ! data.success ) {
					alert( 'Det gick inte att spara informationen om församlingen!' );
					return false;
				}

				collected_data	  = data;

				$('#info_name'		).text( data.cong.name			);
				$('#info_county'	).text( data.county_name		);
				$('#info_city'		).text( data.cong.visit_city	);
				$('#info_email'		).text( data.cong.email			);
				$('#info_telephone'	).text( data.cong.telephone		);
				$('#address_row'	).hide();

				$('#thanks').slideDown( "slow", function( ) {
					countdown   	= 10;
					countdown_int	= setInterval( function() {
						countdown--;

						$('#timeleft').text( countdown );

						if (countdown <= 0) {
							clearInterval( countdown_int );
							$('#continue_reg').click();
						}
					}, 1000 );
				} );
				$('#collect_form').slideUp( "slow" );
			}, function( form ) {
				clearErroredFields();
				if ( $('#name').val().replace( ' ', '' ) == '' ) {
					markErroredField( 'name' );
					alert( 'Du måste ange ett namn för församlingen.' );
					return false;
				}
				if ( $('#email').val().replace( ' ', '' ) == '' ) {
					markErroredField( 'email' );
					alert( 'Du måste ange en e-postadress för församlingen.' );
					return false;
				} else if ( ! /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test( $('#email').val() ) ) {
					markErroredField( 'email' );
					alert( 'E-postadressen du har angett för församlingen verkar inte vara giltig.' );
					return false;
				}
				if ( $('#telephone').val().replace( ' ', '' ) == '' ) {
					markErroredField( 'telephone' );
					alert( 'Du måste ange minst ett telefonnummer för församlingen.' );
					return false;
				}

				if ( $('#visit_address').val().replace( ' ', '' ) == '' ) {
					markErroredField( 'visit_address' );
					alert( 'Du måste ange en besöksadress för församlingen.' );
					return false;
				} else if ( ( $('#visit_zipcode').val().replace( ' ', '' ) == '' ) ||
							( $('#visit_city').val().replace( ' ', '' ) == '' ) ) {
				// markErroredField( 'email' );
					alert( 'Du måste ange en besöksadress (inkl. postnr. & ort) för församlingen.' );
					return false;
				}

				if ( $('#has_post_addr').val() != 0 ) {
					if ( $('#post_address').val().replace( ' ', '' ) == '' ) {
						markErroredField( 'post_address' );
						alert( 'Du måste ange en postadress för församlingen.' +
								"\n(Eller välja att ta bort den adressen, då kommer besöksadressen att användas istället)." );
						return false;
					} else if ( ( $('#post_zipcode').val().replace( ' ', '' ) == '' ) ||
								( $('#post_city').val().replace( ' ', '' ) == '' ) ) {
						alert( 'Du måste ange en postsadress (inkl. postnr. & ort) för församlingen.' +
								"\n(Eller välja att ta bort den adressen, då kommer besöksadressen att användas istället)." );
						return false;
					}
				}
				if ( $('#has_billing_addr').val() != 0 ) {
					addr = $('#has_post_addr').val() ? "besöks" : "post";
					if ( $('#billing_address').val().replace( ' ', '' ) == '' ) {
						markErroredField( 'billing_address' );
						alert( 'Du måste ange en faktureringsadress för församlingen.' +
								"\n(Eller välja att ta bort den adressen, då kommer " + addr + "adressen att användas istället)." );
						return false;
					} else if ( ( $('#billing_zipcode').val().replace( ' ', '' ) == '' ) ||
								( $('#billing_city').val().replace( ' ', '' ) == '' ) ) {
						alert( 'Du måste ange en faktureringssadress (inkl. postnr. & ort) för församlingen.' +
								"\n(Eller välja att ta bort den adressen, då kommer " + addr + "adressen att användas istället)." );
						return false;
					}
				}

				return true;
			} );

			$('.add_address').click( function() {
				field = $(this).attr('field');
				$('#' + field + 'Table').show();
				$('#has_' + field + '_addr').val( 1 );
				$(this).hide();
				return false;
			} );
			$('.rem_address').click( function() {
				field = $(this).attr('field');
				$('#' + field + 'Table').hide();
				$('#has_' + field + '_addr').val( 0 );
				$('#add_' + field + '_address').show();
				return false;
			} );

			$('.cancelBtn').click( function( ) {
				fancy_close();
				return false;
			} );
			$('#hideSum').click( function() {
				if ($(this).val() == 'Visa') {
					$('#summary').slideDown();
					$(this).val( 'Dölj' );
				} else {
					$('#summary').slideUp();
					$(this).val( 'Visa' );
				}
				return false;
			} );
			$('#continue_reg').click( function() {
			//alert( 'Vi jobbar med att lösa problemen!' );
				clearInterval( countdown_int );
				try {
					if ( typeof( collect_callback ) == 'function' ) {//alert( 'Collect_CB' );
						collect_callback( collected_data );
					}
					fancy_close();
				} catch ( e ) { }
				return false;
			} );
		},
		callbackOnClose: function() {
			ajaxUp.enable();
		}
	} );

	$('.city').suggest( $('#city_url').html(), {
		minchars:   1,
		onSelect:	function( sel ) {
						$('#city').val( this.value );
					}
	} );
	$('.congregation').suggest( $('#cong_url').text(), {
		minchars:   1,
		onSelect:	function( sel ) {
						$('#congregation').val( this.value );
					}
	} ).css( { 'clear': 'both', 'display': 'block' } );
	$('#start').datepicker( {
			showOn: 'both',
			showButtonPanel: true,
			buttonImageOnly: true,
			onSelect: startSelected
		} ).
		hide().css( { position: 'absolute' } );
	$('#stop').datepicker( {
			showOn: 'both',
			showButtonPanel: true,
			buttonImageOnly: true,
			onSelect: function( txt, inst ) {
				$('.stop').val( txt );
			}
		} ).
		hide().css( { position: 'absolute' } );
	$('.start').focus( function() {
		focused = true;
		var date = new Date( $('.start').val().replace(/-/g,' ') );
		$('#start').datepicker('setDate', date );
		$('#start').slideDown();
	} );
	$('.stop').focus( function() {
		stop_focused = true;
		var date = new Date( $('.stop').val().replace(/-/g,' ') );
		$('#stop').datepicker('setDate', date);
		$('#stop').slideDown();
	} );
	$('#start').click( function() {
	//	console.log( 'startClick:' + focused );
		focused = false;
		return false;
	} );
	$('.start').blur( function() {
		startSelected( $(this).val() );
		return false;
	} );
	$('#stop').click( function() {
		stop_focused = false;
		return false;
	} );
	$('.coursestart,#leader,#url,#via_alpha,#submitBtn,.congregation,.city').focus( function() {
		stop_focused = focused = false;
		$('#start,#stop').slideUp();
	} );
	$('#body').click( function() {
		if (!focused) {
			$('#start').slideUp();
		}
		if (!stop_focused) {
			$('#stop').slideUp();
		}
		stop_focused = focused = false;
	} );

	$('#course_id').change( function() {
		$.getJSON( $('#course_url').text() + '/' + $(this).val(), function( data ) {
			if ( data.success ) {
				$('#nat_date').text( data.course['start'] );
				def_stop_date = data.course['stop_6m'];
				if ( $('.start').val() == ':null' ) {
					$('#def_stop_date').text( def_stop_date );
				}
			}
		} );
	} );

	$('#custom_start_link').click( function() {
		$('#nat_start').slideUp();
		$('#custom_start').slideDown();

		if ( (custom_start != ':null') && (custom_start != '') ) {
			$('.start').val( custom_start );
			$('#def_stop_date').text( kLib.strtotime_format( '+6 months', custom_start ) );
		} else {
			$('.start').val( '' );
			$('#def_stop_date').html( '<em>Ange ett starttdatum</em>' );
		}
		/*if ( custom_start != ':null' ) {
			$('.start').val( custom_start );
		} else {
			$('.start').val( '' );
		}*/
		return false;
	} );
	$('#nat_start_link').click( function() {
		$('#nat_start').slideDown();
		$('#custom_start').slideUp();

		if ( $('.start').val() != ':null' ) {
			custom_start = $('.start').val();
			$('.start').val( ':null' );
		}
		$('#def_stop_date').text( def_stop_date );

		return false;
	} );
	$('#custom_stop_link').click( function() {
		$('#def_stop').slideUp();
		$('#custom_stop').slideDown();

		if ( (custom_stop != ':null') && (custom_stop != '') ) {
			$('.stop').val( custom_stop );
		} else {
			$('.stop').val( def_stop_date );
		}
	} );
	$('#def_stop_link').click( function() {
		$('#custom_stop').slideUp();
		$('#def_stop').slideDown();

		if ( $('.stop').val() != ':null' ) {
			custom_stop = $('.stop').val();
		}
		$('.stop').val( ':null' );
	} );
	if ( $('.stop').val() != ':null' ) {
		custom_stop = $('.stop').val();
		$('#custom_stop_link').click();
	}

	var ajaxUp = new AjaxUpload( button, {
		action: $('#leader_photo_url').html(),
		autoSubmit: true,
		responseType: 'json',
		onSubmit: function( file, ext ) {
			if (! ( ext && /^(jpg|png|jpeg|gif)$/i.test(ext) ) ) {
				// extension is not allowed
				alert('Endast bilder tillåts!');
				// cancel upload
				return false;
			}

			button.text( 'Laddar upp' );
			// allow only 1 upload
			this.disable();

			// Uploding -> Uploading. -> Uploading...
			interval = window.setInterval(function(){
				var text  = button.text();
				if (text.length < 13){
					button.text(text + '.');
				} else {
					button.text( 'Laddar upp' );
				}
			}, 200);

		},
		onComplete: function(file, response){
			button.hide();
			window.clearInterval(interval);
			button.text( 'Ladda upp bild' );

			if ( response.success ) {
				leader_photo_def_src = $('#leader_photo_img').attr( 'src' );
				$('#filename').text( response.file );
				$('#leader_photo_field').val( response.file_ );
				$('#leader_photo_img').attr( 'src', response.file_path );
				$('#leader_photo_show').show();
			} else {
				alert( response.error.message );
				// enable upload button
				this.enable();
			}
		}
	} );
	$('#remove_photo').click( function() {
		$('#leader_photo_show').hide();
		$('#filename').text( 'Fil' );
		$('#leader_photo_img').attr( 'src', leader_photo_def_src );

		$.getJSON( $('#leader_photo_remove_url').text()/* + $('#leader_photo_field').val()*/,
					function( data ) {

					} );

		$('#leader_photo_field').val( '' );
		ajaxUp.enable();
		button.show();
	} );
	button.click( function() {
		console.log( 'click' );
		$('#userfile').change();
		return false;
	} );
/*	$('#city').change( function() {
		var course	= $('#course').val();
		var sel		= $('#city option:selected').html();

		if ($(this).disabled() || ($(this).val() == 0)) {
			return true;
		}

		var url = host + $('#loadCongregations_url').html().replace( ':_', course ).replace( '##', sel ) + '?ajax';

		$.getJSON( url, null, function( data ) {
			$('#congregation option + option').remove();
			var enable = false;

			$.each( data, function( i, item ) {
				$('<option/>').attr("value", item.id).html( item.name ).appendTo('#congregation');
				enable = true;
			} );

			if (enable) {
				$('#congregation_label').enable();
				$('#congregation').selectbox( null, true );
				$('#congregation').enable();
			}
		} );
	} );*/

	$('#congregation').change( function() {
		$('#submitBtn').hide();

		if ( $(this).val() > 0 ) {
			$('#submitBtn').show();
		}
	} );
	$('#course_time').blur( function() {
		$('#course_time').val( $('#course_time').val().replace( '.', ':' ) );
	} );

	$('#reg_form').ajaxSubmit( null, function( data ) {
		console.log( 'RegSubmit' );
		if ( ! data.success ) {
			alert( 'Kunde inte spara kursen!' );
			return false;
		}

		$.get( data.redirect + '?ajax', function( ty_data ) {
			$('#regH').hide();
			$('<div />')
				.hide()
				.attr('id', 'thanksdiv')
				.html( ty_data )
				.insertBefore( '#hittaform' )
				.slideDown('slow');
			//$('#thanksdiv').slideDown('slow');
			$('#hittaform').slideUp('slow');
		} );
		return true;
	}, function() {
 		console.log( 'RegSubmitTest' );
		if ( skip_submit_check ) {
			skip_submit_check = false;
			return true;
		}

		if ( $('#course_id').val() <= 0 ) {
			alert( 'Du måste välja en kurstyp.' );
			return false;
		}
		if ( $('.city').val().replace( ' ', '' ) == '' ) {
			alert( 'Du måste ange en stad.' );
			return false;
		}
		if ( $('.congregation').val().replace( ' ', '' ) == '' ) {
			alert( 'Du måste ange en församling.' );
			return false;
		}
		if ( $('.start').val().replace( ' ', '' ) == '' ) {
			alert( 'Du måste ange ett startdatum.' );
			return false;
		} else if ( $('.start').val() == ':null' ) {
		} else if ( ! /^\d{4}-[0-1][0-9]-[0-3][0-9]$/.test( $('.start').val() ) ) {
			alert( 'Startdatumet du har angett verkar inte vara ett datum.' + "\n" +
					' Vänligen ange datum enligt åååå-mm-dd, t.ex. 2009-03-30.' );
			return false;
		}
		if ( $('#course_time').val().replace( ' ', '' ) == '' ) {
			alert( 'Du måste ange en tid för kursen.' );
			return false;
		} else if ( ! /^[0-2][0-9]:[0-5][0-9]$/.test( $('#course_time').val() ) ) {
			alert( 'Tiden du har angett för kursen verkar inte vara giltig (Tiden ska anges som t.ex. 19:00 eller 09.30).' );
			return false;
		}

		if ( $('#leader_name').val().replace( ' ', '' ) == '' ) {
			alert( 'Du måste ange ett namn för kursledaren.' );
			return false;
		} else if ( $('#leader_name').val().indexOf( ' ' ) < 0 ) {
			alert( 'Du måste ange både förnamn och efternamn för kursledaren.' );
			return false;
		}
		if ( $('#leader_phone').val().replace( ' ', '' ) == '' ) {
			alert( 'Du måste ange ett telefonnummer för kursledaren.' );
			return false;
		}
		if ( $('#leader_email').val().replace( ' ', '' ) == '' ) {
			alert( 'Du måste ange en e-postadress för kursledaren.' );
			return false;
		} else if ( ! /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test( $('#leader_email').val() ) ) {
			alert( 'E-postadressen du har angett för kursledaren verkar inte vara giltig.' );
			return false;
		}
		/*if ( $('#leader_photo_field').val().replace( ' ', '' ) == '' ) {
			alert( 'Du måste ladda upp en bild för kursledaren.' );
			return false;
		}*/

		checkLeader( function() {
 	console.log( 'CheckLeader_CB' );
			checkCongregation( function() {
 	console.log( 'CheckCong_CB' );
				$('#userfile').remove();

				skip_submit_check = true;
				$('#reg_form').submit();
			} );
		} );

		return false;
	} );
} );

function checkLeader( callback )
{
 	console.log( 'CheckLeader' );
	$.getJSON( $('#person_check_url').text(), { email: $('#leader_email').val(), name: $('#leader_name').val() },
		function( data ) {
			if ( data.not_found ) {
				if ( typeof(callback) == 'function' ) {
					callback();
				}
			} else {
				person_data = data;
				person_callback = function( data ) {
					if ( typeof(callback) == 'function' ) {
						callback();
					}
					person_callback = null;
				};
				$('#collect_leader_info').click();
			}
		} );
}

function checkCongregation( callback )
{
 	console.log( 'CheckCong' );
	$.getJSON( $('#check_cong_url').text(), { cong: $('.congregation').val() },
		function( data ) {
			if ( data.has_cong ) {
				$('#congregation_cid').val( data.cong_cid );
				if ( typeof(callback) == 'function' ) {
					callback();
				}
			} else if ( data.found_similar ) {
			} else {
				collect_callback = function( data ) {
				//alert( 'Collect!' );
					$('#congregation_cid').val( data.cong_cid );
					if ( typeof(callback) == 'function' ) {
						callback();
					}
					collect_callback	= null;
				};
				$('#collect_cong_info').click();
			}
		} );
}

function _showCongColl()
{
	collect_callback = function( data ) {
	//alert( 'Collect!' );
		$('#congregation_cid').val( data.cong_cid );
		if ( typeof(callback) == 'function' ) {
			callback();
		}
		collect_callback	= null;
	};
	$('#collect_cong_info').click();

	return void(false);
}

function contact_form_submit()
{
	action		= $(this).attr('action') + '?ajax';
	contact_id	= $('#contact_id').val();
	//alert( action + ';#' + contact_id + ';;' + $('#message').val() + '!' + $('#message').html());

	post_data	= {
		contact_id:	contact_id,
		name:		$('#name').val(),
		email:		$('#emailaddress').val(),
		telephone:	$('#telephone').val(),
		subject:	$('#subject').val(),
		message:	$('#message').val()
	};

	$.post( action, post_data, function( data ) {
		loadIntoFancy( data );
		$('#back_link').click( function() {
			fancy_close();
		/*	$.get( $(this).attr('href'), null, function( data ) {
				loadIntoFancy( data );
			} );*/
			return false;
		} );
	}, 'html' );

	return false;
}

function startSelected( txt, inst ) {
	$('.start').val( txt );
	$('#def_stop_date').text( kLib.strtotime_format( '+6 months', txt ) );
}