function is_ie6() {
	if(typeof document.body.style.maxHeight === "undefined") {
       	return true;
	}
}



function my_account_menu() {
	$('#my-account').addClass('my-account-js');
	$('#my-account-link').append('<div class="down-arrow"></div>');
	
	$('#my-account-menu').css('display', 'none');
	$('#my-account-menu li:first').css('border-top', 'dotted 0px #fff');
	
	$('#login').css('overflow', 'visible');
	
	$('#my-account-link .down-arrow').live("click", function() {
		$('#my-account-menu').toggle();
	});
}



function random_header_image() {
	var header_images = new Array(
		"header1.jpg",
		"header2.jpg",
		"header3.jpg",
		"header4.jpg",
		"header5.jpg",
		"header6.jpg",
		"header7.jpg"
	);
	var random_image = Math.floor(Math.random()*header_images.length);
	$('#header-image').css('background-image', 'url(/media/header_images/'+header_images[random_image]+')');
}



function submenu(theid) {
	$(theid).corner('10px');
	$(theid).each( function() {
		$(this).children('li:last').css('border-bottom', 'solid 1px #fff');
	});
}



function corners() {
	$(".boxout").corner('10px');
	$("#corporate-highlight").corner('10px');
}


function equal_heights(theid, cols) {
	if ( $(theid).length > 0 ) {
		var items = $(theid).children().size();
		var looper = 0;
		while (looper < items+cols+3) {
			end_slice = looper+cols;
			$(theid+' div').slice(looper,end_slice).wrapAll('<div class="row-js"></div>');
			looper = looper+cols+1;
		}
	}
}


function tidy_book_buttons() {
	$('.book-button').each( function() {
		$(this).css({'width': $(this).width()+'px', 'display': 'block'});
	});
	$(".book-button").corner('10px');
	$("td .book-button").corner('5px');
	
	$('.listing-grid .book-button').css({'float': 'left', 'margin-right': '10px'});
}



function form_dyn_show(toggleid, theid, extra) {
	
/* -----------------------------------------------------------------------------
 * USAGE
 *
 * selects       = form_dyn_show('ID of other text field', 'ID of select', 'value of option to show text field');
 * checkboxes    = form_dyn_show('ID of other text field','ID of checkbox');
 * radio buttons = form_dyn_show('ID of other text field','ID of radio button','name of radio button group');
 * -----------------------------------------------------------------------------
 */
	$('#'+toggleid).prev().addClass('other-detail');
		
	if ( !is_ie6() ) {
	
		function toggle_fields(thesum, toggleid) {			// This is what toggles the 'if other' fields.
			if (thesum) {
				$('#'+toggleid).parent().show();
			} else {
				$('#'+toggleid).parent().hide();
				$('#'+toggleid).val('');			// Wipe the field value to stop accidental submission.
			}
		}
	
		// SELECTS.
		if ( $('#'+theid).attr('tagName').toLowerCase() == 'select' ) {
			toggle_fields( $('#'+theid+' option:selected[value='+extra+']').val() == extra, toggleid );
	
			var change_select = function() {
				$('#debug').append( $('#'+theid+' option:selected').text()+' ' );
				// Does a selected option match the 'other'?
				toggle_fields( $('#'+theid+' option:selected[value='+extra+']').val() == extra, toggleid );
			}
			$('#'+theid).click(change_select).keyup(change_select);
		
		} else {
		
			// RADIO BUTTONS.
			if ( $('#'+theid).attr('type') == 'radio' ) {
				toggle_fields( $('#'+theid).attr('checked'), toggleid );
			
				$('input[name='+extra+']').change( function() {
					toggle_fields( $(this).attr('id') == theid, toggleid );	// Is 'other' ID selected?
				});
		
			// CHECKBOXES.
			} else {
				toggle_fields( $('#'+theid).attr('checked'), toggleid );
		
				$('#'+theid).click( function() {
					$('#debug').append('click ');
					toggle_fields( $('#'+theid).attr('checked'), toggleid );	// Is 'other' ID selected?
				});
			}
		}
		
	// } else {	// If IE6.
		// $('#'+toggleid).prev().addClass('other-detail');
	}
}


function move_labels_init() {
	
/* -----------------------------------------------------------------------------
 * USAGE
 *
 * Automate the form trickery.
 * -----------------------------------------------------------------------------
 */
	if ( $('#content form').length > 0 ) {
		// $('body').prepend('<div id="debug"></div>');
		// Automate moving label text into input vals.
		$(
			'#content form .move-labels input[type=text], '+
			'#content form .move-labels textarea, '+
			'#content form .move-labels select'
		).each( function() {
			move_labels( $(this).attr('id') );
		});
	
		// Switch on any dynamic groups of inputs.
		dyn_form_rows();
	
		if ( $('.catch-before-submit').length > 0 ) {
			catch_before_submit_init();
		}
	}
}



function move_labels(thetextid) {
	
/* -----------------------------------------------------------------------------
 * USAGE
 *
 * Moves the label text into the input val and hides the label.
 * e.g.  move_labels('id');
 *       move_labels(['id1', 'id2', 'id3']);
 * -----------------------------------------------------------------------------
 */
	
	function move_it(theid) {
	
		function __label_text(theid) {
			
			if ( $('#'+theid).hasClass('datepicker') ) {						// Special case for date dropdowns.
				// if ( $('#'+theid+' option:last').text().length == 4 ) {			// Year.
				// 	return 'Year';
				// } else if ( $('#'+theid+' option:last').text().length == 3 ) {	// Month.
				// 	return 'Month';
				// } else {														// Day.
				// 	return 'Day';
				// }
				return '';
			}
			return $('#'+theid).prev().text().replace(' *', '');		// Remove 'required' * from label before sending back.
		}
		
		// Set val to label text.
		if ( $('#'+theid)[0].nodeName == "SELECT" ) {							// A select box.
			if ( $('#'+theid+' option:first').text().substr(0, 3) == '---' ) {	// Check the first item isn't something meaningful.
			// if ( !$('#'+theid+' option:first').val() ) {						// Check the first option has no value.
				$('#'+theid+' option:first').text( __label_text(theid) );		// Set first option text to label text.
			}
		} else {																// For inputs and textareas.
			if ( $('#'+theid).val() == '' ) {
				$('#'+theid).val( __label_text(theid) );
			}
		}
		$('#'+theid).parents('form').addClass('catch-before-submit');
		
		
		$('#'+theid).addClass('moved-label-js');
		$('#'+theid).prev().hide();
		$('#'+theid).parent('li').parent('ul').addClass('move-labels-js');
	
		$('#'+theid).focus( function() {
			if ( $('#'+theid).val() == __label_text(theid) ) {
				$('#'+theid).val('');
			}
		});
		$('#'+theid).blur( function() {
			if ( $('#'+theid).val() == '' ) {
				$('#'+theid).val( __label_text(theid) );
			}
		});
	}
	
	if ( $.isArray(thetextid) ) {			// Array.
		$.each(thetextid, function() {		// Loop through.
			move_it(this);
		});
	} else {								// Single ID.
		move_it(thetextid);
	}
}


function catch_before_submit_init() {
	$('.catch-before-submit').submit( function() {	// If form submitted.
		
		$(this).addClass('form-to-clear');
		
		var things_to_clear = $(
			'#content form.form-to-clear .move-labels input[type=text], '+
			'#content form.form-to-clear .move-labels textarea, '+
			'#content form.form-to-clear .move-labels select'
		)
		var things_to_clear_count = things_to_clear.length-1;
		
		$(things_to_clear).each( function(i) {
			catch_before_submit( $(this).attr('id') );
		});
	});
}

function catch_before_submit(thetextid) {
	
	function remove_it(theid) {
		
		function __label_text(theid) {
			
			if ( $('#'+theid).hasClass('datebox') ) { return ''; }		// Special case for date dropdowns.
			return $('#'+theid).prev().text().replace(' *', '');		// Remove 'required' * from label before sending back.
		}

		// Set val to label text.
		if ( $('#'+theid)[0].nodeName != "SELECT" ) {					// Not a select box.
			if ( $('#'+theid).val() == __label_text(theid) ) {
				$('#'+theid).val( '' );
			}
		}
	}
	
	if ( $.isArray(thetextid) ) {			// Array.
		$.each(thetextid, function() {		// Loop through.
			remove_it(this);
		});
	} else {								// Single ID.
		remove_it(thetextid);
	}
}



function popup_date_init() {
	var datepickernum = 1;
	$('.datepicker').parent('li').parent('ul').parent('div').each( function() {
		$(this).attr('id', 'datepicker'+datepickernum);
		popup_date('#datepicker'+datepickernum);
		datepickernum++;
	});
}
function popup_date(theid) {
	
/* -----------------------------------------------------------------------------
 * USAGE
 *
 * Uses jQuery UI to add a date picker for individual date elements.
 * e.g.  popup_date('id');
 *       popup_date(['id1', 'id2', 'id3']);
 * -----------------------------------------------------------------------------
 */
	
	function __popup_date(theid) {
		$(theid+' select').each( function() {						// Swap the selects to inputs.
			$(this).after(
				'<input type="text" name="'+$(this).attr('name')+'" '
				+'id="'+$(this).attr('id')+'" '
				+'class="datebox" '
				+'value="'+$(this).children('option:not(:first):selected').text()+'" />'
			);
			$(this).remove();
		});
		$(theid+' input:last').datepicker({							// Add the datepicker.
			showOn: 'button', 
			buttonText: 'Choose date', 
			dateFormat: 'dd-M-yy', 
			inline: true,
			onSelect: function(dateStr) {							// When a date is selected.
				var date = dateStr.split("-");						// Split selected date.
				for ( var i in date ) {
					$(theid+' input:eq('+i+')').val( date[i] );		// Put date bits into text inputs.
				} 
			}
		});
	}
	if ( $.isArray(theid) ) {			// Array.
		$.each(theid, function() {		// Loop through.
			__popup_date(this);
		});
	} else {							// Single ID.
		__popup_date(theid);
	}
}



function dyn_form_rows() {
		
	// Add button.
	var add_button = 
		'<div>'+
			'<label for="add-rows1" style="visibility: hidden">Add another person</label>'+
			'<input type="button" id="add-rows1" class="button-js add-row-button" value="Add another person" />'+
		'</div>';
	
	// Loop through each .repeater group.
	$('form').children('.repeater').each( function() {
		
		$(this).children('fieldset:gt(0)').hide();
		
		// Remove button.
		$(this).children('fieldset:gt(0)').append(
			'<div>'+
				'<label>&nbsp;</label>'+
				'<input type="button" class="button-js remove-row-button" value="Remove this person" />'+
			'<div>'
		);
		$(this).append(add_button);
	});
	
	// If add button clicked on...
	$('.add-row-button').live("click", function() {
		
		// Check for any moved labels and reinitiate them.
		if ( $(this).parent().parent().children('fieldset:hidden:first').find('.move-labels-js').length > 0 ) {
			$(this).parent().parent().children('fieldset:hidden:first').find('.moved-label-js').each( function() {
				move_labels( $(this).attr('id') );
			});
		}
		
		$(this).parent().parent().children('fieldset:hidden:first').show();
		
		if ( $(this).parent().parent().children('fieldset:hidden:first').index() == -1 ) {
			$(this).parent().remove();
		}
	});
	
	// If remove button clicked on...
	$('.remove-row-button').live("click", function() {
		
		if ( $(this).parent().parent().parent().children('fieldset:hidden:first').index() == -1 ) {
			$(this).parent().parent().parent().append(add_button);
		}
		$(this).parent().parent('fieldset').hide();
		
		// Unset all the form element values.
		$(this).parent().parent('fieldset').find('input[type=text], textarea, select').val('');
		$(this).parent().parent('fieldset').find('input:checkbox, input:radio').attr('checked', false);
	});
}



function toggle_init() {
	$('.toggle').each( function() {
		$(this).children('h2:first').append('<span class="toggle-arrow down">&nbsp;</span>');
	});
	$('.listing-grid p:not(.link)').hide();
	
	$('.toggle-arrow').toggle(
		function() {
			$(this).parent().siblings('.listing-grid p:not(.link)').toggle();
			$(this).removeClass('down');
		},
		function() {
			$(this).parent().siblings('.listing-grid p:not(.link)').toggle();
			$(this).addClass('down');
		}
	);
}



function fix_selects(thewidth) {
	$('#content select').each( function() {
		if ( !$(this).hasClass('wide-set') ) {
			if ( $(this).width() > thewidth ) {
				$(this).wrap('<div class="wide-select" />');
				$(this).css('width', thewidth+'px');
				$(this).addClass('wide-set');
			}
		}
	});
	var wide_select_tracker = 0;
	
	$('.wide-select select').hover( function() {
		$(this).css('width', 'auto');
	},function() {
		if ( wide_select_tracker == 0 ) {
			$(this).css('width', thewidth+'px');
		}
	});
	$('.wide-select select').focus( function() {
		$(this).css('width', 'auto');
		wide_select_tracker = 1;
	});
	$('.wide-select select').blur( function() {
		$(this).css('width', thewidth+'px');
		wide_select_tracker = 0;
	});
	$('.wide-select select').change( function() {
		$(this).css('width', thewidth+'px');
		wide_select_tracker = 0;
	});
}



function extra_wide_form(theclass) {
	$('form .toggle-extra').html('<span class="toggle-extrainfo">Core info</span> <span class="toggle-progress">Progress</span>');
	$('form .toggle-progress-data, form .toggle-extra-data').hide();
	
	$('.toggle-progress').click( function() {
		$(this).parent().parent().parent().next('.toggle-progress-data').slideToggle();
	});
	
	$('.toggle-extrainfo').click( function() {
		$(this).parent().parent().parent().next().next('.toggle-extra-data').slideToggle();
	});
}



$(document).ready( function() {
	my_account_menu();
	random_header_image();
	submenu('.submenu');
	popup_date_init();
	move_labels_init();
	fix_selects(386);
	corners();
	equal_heights('#listing-grid2', 2);
	equal_heights('#listing-grid3', 3);
	toggle_init();
	tidy_book_buttons();
});
