jQuery(document).ready(function($) {

	/* Facebook LIKE button */
	
	(function(d, s, id) {
	var js, fjs = d.getElementsByTagName(s)[0];
	if (d.getElementById(id)) return;
	js = d.createElement(s); js.id = id;
	js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
	fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));
	
	/* Twitter Follow button */
	!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
	
	/* Google+ Button */
	window.___gcfg = {lang: 'en'};
	(function() 
	{var po = document.createElement("script");
	po.type = "text/javascript"; po.async = true;po.src = "https://apis.google.com/js/plusone.js";
	var s = document.getElementsByTagName("script")[0];
	s.parentNode.insertBefore(po, s);
	})();
	
	function test() {
	}
	
	
	$('#x').click(function() {
		$('#memdevcp').slideToggle();
	})
	
	if($("acronym[title],abbr[title], a.tip").length) {
		$("acronym[title],abbr[title]").tooltip({
			 extraClass : 'accr',
			 top: 14
		});
	}
	
	if($("a.tip").length) {
		$("acronym[title],abbr[title], a.tip").tooltip({
			 showURL: false
		});
	}
	
	/*
	if($("acronym[title],abbr[title], a.tip").length) {
		$("acronym[title],abbr[title], a.tip").tooltip({
			position: 'bottom',
			relative: false
			//offset: [0 , 120]
		});
	}*/
	
	if($('#suggest').length) {
		var suggest = $('input[id="suggest"]').suggest({
			className: 'simple',
			url: '/includes/js/response.php?request=suggest'
		});
	}
	
	// Side Menu
	$('#side-menu ul li ul').hide();
	$('#side-menu ul li a').hover(function() {
		$(this).parent().children('ul').slideDown('normal');
	});
	
	$('#homepage-search, #sidebar-search, #adv-search').submit( function(e) {
		var searchInput = $('#suggest');
		if((searchInput.val() == 'Enter your postcode, town or county'
			|| searchInput.val() == 'Enter postcode, town or county'
			|| searchInput.val().length === 0
			) && $('[name="session_type"]').val() != 'online'
		) {
			alert('Please enter your postcode, town or county.');
			e.preventDefault();
		}
	});
	
	$('#sidebar-search.advanced').submit(function(e) {
		if(!$('#suggest').val().length && !$('[name=service]').val().length && !$('[name=approach]').val().length && (!$('[name=keyword]').val().length || $('[name=keyword]').val() == 'Enter keyword') && $('[name=session_type]').val() == 'online'
			) {
			alert('Please select at least one further search option.');
		}
		e.preventDefault();
	});
	
	$('#search-form').submit( function(e) {
		var searchInput = $('#search-input');
		if(searchInput.val().length === 0 || searchInput.val() == 'Search entire site') {
			alert('Please enter something in the search box.');
			e.preventDefault();
		}
	});
	
	$(".submit-confirm").click(function(e) {
		if(confirm('Are you sure?') != true) {
			e.preventDefault();
		}
	});
	
	// Registration Form - Allow navigation away from page on Continue button
	$('.registration-continue').click(function() {
		needtoconfirm = false;
	});
	$('.complete-app').click(function() {
		needtoconfirm = false;
	});
	$('.preview-profile-trigger').click(function(e) {
		e.preventDefault();
		var url = $(this).attr('href');
		previewprofile(url);
	});
	
	var tinymce_settings_global = {
		script_url : '/includes/js/tiny_mce/tiny_mce.js',
		width: 675,
		theme : "advanced",
		cleanup_on_startup : true,
		button_tile_map : true,	
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "none",
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,sup,|,justifyleft,justifycenter,justifyright,justifyfull,|,removeformat,styleselect,formatselect",
		theme_advanced_buttons3: '',
		theme_advanced_path : true,
		plugins : "paste",
		gecko_spellcheck : true,
		remove_trailing_nbsp : true,
		paste_auto_cleanup_on_paste : true,
		convert_urls: false
	};
	
	if( $('textarea.tinymce-admin').length) {	
		wysiwyg = $('textarea.tinymce-admin').tinymce(tinymce_settings_global);
	}
	
	var tinymce_settings_blog = {
		script_url : '/includes/js/tiny_mce/tiny_mce.js',
		width: 675,
		theme : "advanced",
		cleanup_on_startup : true,
		button_tile_map : true,	
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "none",
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,sup,|,justifyleft,justifycenter,justifyright,justifyfull,|,removeformat,styleselect,formatselect",
		theme_advanced_buttons3: "tablecontrols,|,preview",
		theme_advanced_path : true,
		plugins : "paste,table,preview,advlink",
		gecko_spellcheck : true,
		remove_trailing_nbsp : true,
		paste_auto_cleanup_on_paste : true,
		convert_urls: false,
		content_css : "/includes/css/tinymce_custom.css",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,
		
		//Tinyupload stuff
		relative_urls : false, //Tiny upload returns absolute urls, we dont want tinymce changing them to relative.
		file_browser_callback:tinyupload //Hookup tinyupload the the filebrowser call back.
	};
	
	if( $('textarea.tinymce-blog').length) {	
		wysiwyg = $('textarea.tinymce-blog').tinymce(tinymce_settings_blog);
	}
	
	$('#eventscal').dialog({
		autoOpen: false,
		resizable: false,
		draggable: false,
		width: 860,
		modal: true
	});
	$('.eventscal-trigger').click( function(event) {
		event.preventDefault();
		event.stopImmediatePropagation();
		
		$('#eventscal').dialog('open');
	});
	
	/* Registration Functions */
	
	$('input.exception').each(function() {
		$(this).parent('div').hide();
	});	
	
	$('input.hasException').change( function() {
		if($(this).is(':checked')){
			var checkbox = $(this);
			var serviceId = $(this).val();
			var confirm = false;
			$.get('/ajax.php', { action: 'get_service_confirmation', service_id: serviceId }, function(data){
				if(data) {
					$('.dialog').html(data);
					$('.dialog').dialog({
						title: 'Confirm Registration',
						modal: true,
						resizable: false,
						draggable: false,
						width: 600,
						buttons: {
							Cancel: function() {
								$(this).dialog('close');
							},
							Confirm: function() {
								confirm = $('#exceptionButton').is(':checked');
								if(confirm) {
									$(this).dialog('close');
								}
							}
						},
						beforeClose: function() {
							checkbox.attr('checked', confirm);
							$('#exception'+serviceId).attr('checked', confirm);
						}
					});
				}
			});
		}
	});
	
	$('.verification-section').live('each', function(){	
		if(!$(this).is(':checked')){
			$(this).parent().next().hide();
		}
	});
	
	$('.verification-section').live('change', function() {
		var slider = $(this).attr('id');
		$('.verification-section').each( function() {
			if($(this).attr('id')==slider){
				$(this).parent().next().css('width', 585).slideDown(500, function(){
/* 					$('html,body').animate({scrollTop: $('.numberCircleGrey').offset().top}); */
				}).css('width', 'auto');
				$(this).prev('label').addClass('checked');			
			} else {
				$(this).parent().next().css('width', 585).slideUp(500).css('width', 'auto');
				$(this).prev('label').removeClass('checked');
			}
		});	
	});
	
	$('.bodyproof').change( function() {
		if($(this).is(':checked')){
			var body = $(this).val();	
			var nextdiv = $(this).next().next('.bodyproofcat').html();
			if(!nextdiv){
				$(this).next('label').after('<div class="bodyproofcat" style="display: none;"></div>');
			}
			var bodyproofcat = $(this).next().next('.bodyproofcat');
			$.get('/ajax.php', { action: 'get_body_categories', body: body }, function(data){
				if(data){
					var list = '<ul style="list-style: none; margin: 0 0 0 5px;">';
					$.each( data, function(i) {
						var category = String(this);
						if(category){
							list += '<li style="clear:left;"><input type="checkbox" style="float: left;" name="proof['+body+']['+i+']" /><span style="padding-left: 2px; float: left; width: 140px; font-size: 12px;">'+category+'</span></li>';
						}
					});
					list += '</ul>';
					bodyproofcat.append(list);
					bodyproofcat.slideToggle();
				}
			});
		} else {
			var nextdiv = $(this).next().next('.bodyproofcat');
			if(nextdiv.html()){
				$(nextdiv).slideToggle(function(){
					$(nextdiv).remove();
				});
			}
		}
	});
	
	/* Alternative Registration Form Functions */
	
	function verification_dialog(thiscat, category, memberId, edit) {
		category = category.replace('cat[','');
		category = category.replace(']','');
		$.get('/ajax.php', { action: 'get_category_verification', category: category, memberId: memberId}, function(data) {
			if(data) {
				var done=false;
				$('#verification').html(data);
				$('#verification').dialog({
					modal: true,
					draggable: false,
					resizable: false,
					width: 750,
					position: 'top',
					close: function() {						
						if(!edit && !done) {
							thiscat.attr('checked', false);
						}
					},
					buttons: {
						'Cancel': function() {
							if(!edit) {
								thiscat.attr('checked', false);
							}
							$(this).dialog('close');
						},
						'Done': function() {
							var dialog = $(this);
							// update information
							var form = $('#verificationForm').serialize();
							$.post('registration-verification.php', form, function(data) {
								$('.error').remove();
								// verify form data
								if(data.length>0) {
									var errors = '<div class="error messages" style="font-family: Arial; font-size: 14px;"><p>The following errors have occured:</p><ul>';
									$.each(data, function() {
										errors += '<li>'+this+'</li>';
									});
									errors += '</ul></div>';
									$('#verification').prepend(errors);
								} else {
									// insert information
									thiscat.parent().find('.catinfo').remove();
									var info = '<div class="catinfo">';
									if($('input[name=verification-section]:checked').val()== 2) {
										info += 'Qualifications & Insurance';
									} else {
										$('input.body:checkbox:checked').each(function() {
											var thisbody = $(this).next().text();
											var ul = $(this).parent().children('ul');
										   	$(ul).children('li').children('input:checkbox:checked').each(function() {
												var thissubcat = $(this).next().text();
												info += thisbody + ' ' + thissubcat + '<br />';
										   	});
										});
									}
									info += ' <a href="" class="editVer"><u>edit</u></a></div>';
									thiscat.parent().append(info);
									done=true;
									dialog.dialog('close');
								}
							});
						}
					}
				});				
			}	
		});
	}
	
	$('.areacategory').change( function () {
		var thiscat = $(this);
		if($(this).is(':checked')){
			var category = thiscat.attr('name');
			var memberId = $('input[name="member_id"]').val();
			verification_dialog(thiscat, category, memberId, false);
		}
	});
	
	$('a.editVer').live('click', function() {
		var thiscat = $(this).parent().prev().prev();
		var category = thiscat.attr('name');
		var memberId = $('input[name="member_id"]').val();
		
		verification_dialog(thiscat, category, memberId, true);
		return false;
	});
	
	
	
	$('.altRegBody input').live('change', function() {
		var thisbody = $(this);
		var ischecked = (thisbody.is(':checked'));
		var thislist = $(this).parent().children('ul');
		var haschildren = false;
		var children = thislist.children('li').children('input');
		
		// if only children are blank bodies, don't show but automatically tick
		children.each(function() {
			if($(this).next('label').text().length == 0){
				$(this).attr('checked', thisbody.attr('checked'));
			} else {
				haschildren = true;
			}
		});
		
		if(haschildren) {		
			thislist.slideToggle();
		}
		if(!ischecked) {
			children.attr('checked', false);
		}
				
		
	});
	
	$('label').disableSelection();
		
	/* Calendar Functions */
	$('#calendar .month').live('change', function() {
		$('#calendar-outer').load('/eventscalendar.html?' + $(this).serialize(), ' #calendar');
	});
	
	$('#calendar .month a').live('click', function(e) {
		e.preventDefault();
		$('#calendar-outer').load($(this).attr('href') + '&' + $('form.month input[name="type"]').serialize(), '#calendar');
	});	
	
	
	if($('form.once_only').length > 0){
		$('form.once_only').submit(function(){
			$('form.once_only .submit_once').attr('disabled','disabled');
			$('form.once_only .submit_once').attr('value', 'Sending Message...');
			return true;
		});
	}
	
});


function previewprofile(url){
	$("body").css("overflow", "hidden");
	var $preview = $('#preview');
	$preview.dialog('destroy');
	var $curwidth = $(window).width()-20;
	if($curwidth > 1100){
		$curwidth = 1080;
	}
	var $curheight = $(window).height()-20;	
	if($curheight > 600){
		$curheight = 580;
	}	
	$preview.dialog({
		width: $curwidth,
		height: $curheight,
		draggable: false,
		title: 'Preview of your Profile',
		modal: true,
		resizable: false,
		create: function() {
			$("body").css("overflow", "hidden"); 
			$("#wrapper").css("height", "120px");
			$("#wrapper").css("width", "200px");
			$("#wrapper").css("overflow", "hidden");
			$("#footer").css("height", "100px");	
			$("#footer").css("width", "200px");	
			$("#footer").css("overflow", "hidden");	
		},
		open: function() { 
/*	
			// Detect ie6, and add special preview warning
			if($.browser.msie && $.browser.version=="6.0"){
				$preview.html('<iframe src="' + url + '" frameborder=0 width="' + ($curwidth-30) +'" height="' + ($curheight-90) + '" marginheight="0" marginwidth="0" scrolling="0"></iframe></div>');
				$preview.prepend('<div class="preview-bar"><strong>This is a Preview - This profile is Not Live</strong></div>');
			}
			else{
				$preview.html('<iframe src="' + url + '" frameborder=0 width="' + ($curwidth-30) +'" height="' + ($curheight-90) + '" marginheight="0" marginwidth="0" scrolling="0" style="margin-bottom: 12px;"></iframe><br /><div style="float: right"><a class="btn-regcomplete back-primary" style="color: #fff;" href="#">Continue Registration</a></div></div>');
				$preview.prepend('<div class="preview-bar" style="width: '+($curwidth-50)+'px"><strong>This is a Preview - This profile is Not Live</strong></div>');
			}
*/
			if($.browser.msie && $.browser.version=="6.0"){
			//	$curheight = $curheight - 30;
			}
			var check = new String(window.location);
			var addComplete = '';
			if(check.indexOf("register.php") > 0 ){
				$curheight = $curheight - 20;
				addComplete = '<div style="float: right"><a class="btn-regcomplete back-primary" style="color: #fff;" href="#">Continue Registration</a></div>';
			}
			$preview.html('<iframe src="' + url + '" frameborder=0 width="' + ($curwidth-30) +'" height="' + ($curheight-100) + '" marginheight="0" marginwidth="0" scrolling="0" style="margin-bottom: 12px;"></iframe><br />'+addComplete+'</div>');
			$preview.prepend('<div class="preview-bar" style="width: '+($curwidth-30)+'px; position:relative;"><strong>This is a Preview - This profile is Not Live</strong></div>');
			
			//
			$('.ui-widget-overlay').bind('click', function(){ $preview.dialog('close'); });
			$('a.btn-regcomplete').bind('click', function(){ $preview.dialog('close'); });

		},
		beforeClose: function() { 
			$("body").css("overflow", "visible"); 
			$("#wrapper").css("height", "100%");
			$("#wrapper").css("width", "992px");
			$("#wrapper").css("overflow", "visible");
			$("#footer").css("height", "100%");
			$("#footer").css("width", "980px");
			$("#footer").css("overflow", "visible");
		}
	});

}

/* Old functions */
function checkForOther(obj) { 
	if (!document.layers) { 
		var txt = document.getElementById("otherTitle"); 
		if (obj.value == "awaiting_go_ahead") { 
			txt.style.display = "inline"; 
			// gives the text field the name of the drop-down, for easy processing
		} else { 
			txt.style.display = "none"; 
			txt.name = ""; 
		} 
	} 
}

function checkForm(form) {
    // check form input values

    form.javButton.disabled = true;
    form.javButton.value = "Please wait...";
    return true;    
}

