//##################################################################################

	// Begin OBE order form

//##################################################################################

// Define vars
var selected_service;
var selected_level;
var selected_type;
var sections = ['services', 'levels', 'types', 'subjects', 'words'];

// Begin main functionality
$(document).ready(function() {

	// Listen for option clicks
	$('.box').click(function () {
			
		// Services
		if ($(this).hasClass('service-opt')) {
			// Close subject suggest
			$('#subject-cost').val('');
			$('#subject-suggest').hide();
			// Display selected value and edit
			$('#services-selection').html('');
			selected_service = $(this).children('span').text();
			// Check defined
			$(this).children('input[type=radio]').attr('checked', true);
			// Clear dependant
			$('#levels-selection').html('');
			$('input[name=level]').attr('checked',false);
			$('#edit-levels').hide();
			$('#types-selection').html('');
			$('input[name=type]').attr('checked',false);
			$('#edit-types').hide();
			$('#subjects-selection').html('');
			$('input[name=subject]').val('');
			$('#edit-subjects').hide();
			//$('#subjects').slideUp('slow');
			slideToggle('#subjects',false);
			// Mark next steps as incomplete
			$('#levels-title').attr('class', 'row-title-disabled');
			$('#types-title').attr('class', 'row-title-disabled');
			$('#subjects-title').attr('class', 'row-title-disabled');
			$('#open-types a').removeClass('active');
			$('#open-subjects a').removeClass('active');
			// Display next button
			$('#open-levels a').addClass('active');
			// Set price row to incomplete
			$('#price-title').attr('class', 'row-title-disabled');
			$('#bottom-price').html('');
			//$('#standards').slideUp('slow');
			slideToggle('#standards',false);
			// Clear standard
			$('input[name=standard]').attr('checked',false);
			$('.standard-opt-set').each(function() {
				$(this).attr('class','box standard-opt');				 
			});
			$('#dummy-start').fadeOut();
		// Levels
		} else if ($(this).hasClass('level-opt')) {
			// Display selected value and edit
			$('#levels-selection').html('');
			selected_level = $(this).children('span').text();
			// Check defined
			$(this).children('input[type=radio]').attr('checked', true);
			// Clear type selection
			$('#types-selection').html('');
			$('input[name=type]').attr('checked',false);
			$('#edit-types').hide();
			// Mark next steps as incomplete
			$('#types-title').attr('class', 'row-title-disabled');
			$('#open-subjects a').removeClass('active');
			// Display next button
			$('#open-types a').addClass('active');
			// Set price row to incomplete
			$('#price-title').attr('class', 'row-title-disabled');
			$('#bottom-price').html('');
			$('#next').attr('disabled',true);
			//$('#standards').slideUp('slow');
			slideToggle('#standards',false);
			// Clear standard
			$('input[name=standard]').attr('checked',false);
			$('.standard-opt-set').each(function() {
				$(this).attr('class','box standard-opt');				 
			});
		// Standards
		} else if ($(this).hasClass('type-opt')) {
			// Display type value and edit
			$('#types-selection').html('');
			selected_type = $(this).children('span').text();
			// Check defined
			$(this).children('input[type=radio]').attr('checked', true);
			// Display next button
			$('#open-subjects a').addClass('active');
			// Set price row to incomplete
			$('#price-title').attr('class', 'row-title-disabled');
			$('#bottom-price').html('');
			$('#next').attr('disabled',true);
			// Clear standard
			$('input[name=standard]').attr('checked',false);
			$('.standard-opt-set').each(function() {
				$(this).attr('class','box standard-opt');				 
			});
		}
	});
	
	$('.standard-opt').click(function() {
		// Check defined
		$(this).children('input[type=radio]').attr('checked', true);
		// Mark row as complete
		$('#delivery-title').attr('class', 'row-title-complete');
		$('#price-title').attr('class', 'row-title-focus');
		$('#words-title').attr('class', 'row-title-complete');
		$('#standards-title').attr('class', 'row-title-complete-edit');
		$('#deliveries').css('background-image','url(../style/images/order/step-bg.gif)');
		$('#words').css('background-image','url(../style/images/order/step-bg.gif)');
		// Define class
		$('.standard-opt-set').attr('class','box standard-opt');
		$(this).attr('class','box standard-opt-set');
		// Activate next
		calculateCost();
	});
	
	// Listen for continue
	$('.next-step').click(function() {
		// Only allow continue when button is active
		if ($(this).children('a').hasClass('active')) {
			// Hide next step buttons
			if ($(this).attr('id') == 'open-levels') {
				var val = $('input[name=service]:checked').val();
				// Check if value is set
				if (!empty(val)) {
					$(this).hide();
					if(!$('input[name=level]').is(':checked') || empty($('#levels-selection').html())) {
						$('#services-selection').html(val).removeAttr('style');
						$('#open-types').show();
					} else if(!$('input[name=type]').is(':checked') || empty($('#types-selection').html())) {
						$('#services-selection').html(val).removeAttr('style');
						$('#open-subjects').show();
					} else if(empty($('input[name=subject]').val()) || empty($('#subjects-selection').html())) {
						$('#services-selection').html(val).removeAttr('style');
						$('#open-words').show();
					} else if(empty($('input[name=word]').val()) || empty($('#words-selection').html()) || !isNumeric($('input[name=word]').val().replace(',',''))) {
						$('#services-selection').html(val).removeAttr('style');
						$('#open-deliveries').show();
					} else {
						//$('#words').slideDown('slow');
						slideToggle('#words',true);
						//$('#deliveries').slideDown('slow');
						slideToggle('#deliveries',true);
						//$('#standards').slideDown('slow');
						slideToggle('#standards',true);
						// Is standard selected
						if(!$('input[name=standard]').is(':checked')) {
							$('#price-title').attr('class', 'row-title-focus');
						}
					}
				}
			} else if ($(this).attr('id') == 'open-types') {
				var val = $('input[name=level]:checked').val();
				// Check if value is set
				if (!empty(val)) {
					$(this).hide();
					if(!$('input[name=type]').is(':checked') || empty($('#types-selection').html())) {
						$('#levels-selection').html(val).removeAttr('style');
						$('#open-subjects').show();
					} else if(empty($('input[name=subject]').val()) || empty($('#subjects-selection').html())) {
						$('#levels-selection').html(val).removeAttr('style');
						$('#open-words').show();
					} else if(empty($('input[name=word]').val()) || empty($('#words-selection').html()) || !isNumeric($('input[name=word]').val().replace(',',''))) {
						$('#levels-selection').html(val).removeAttr('style');
						$('#open-deliveries').show();
					} else {
						//$('#words').slideDown('slow');
						slideToggle('#words',true);
						//$('#deliveries').slideDown('slow');
						slideToggle('#deliveries',true);
						//$('#standards').slideDown('slow');
						slideToggle('#standards',true);
						// Is standard selected
						if(!$('input[name=standard]').is(':checked')) {
							$('#price-title').attr('class', 'row-title-focus');
						}
					}
				}
			} else if ($(this).attr('id') == 'open-subjects') {
				var val = $('input[name=type]:checked').val();
				// Check if value is set
				if (!empty(val)) {
					$(this).hide();
					$('#types-selection').html(val).removeAttr('style');
					if (!$('#subjects-title').hasClass('row-title-complete')) {
						$('#open-words').show();
					} else {
						// Skip to word count if subject is done and words needs doing
						if (empty($('input[name=word]').val()) || empty($('#words-selection').html()) || !isNumeric($('input[name=word]').val().replace(',',''))) {
							//$('#words').slideDown('slow');
							slideToggle('#words',true);
							$('#open-deliveries').show();
							$('#word-error').hide();
						} else {
							//$('#words').slideDown('slow');
							slideToggle('#words',true);
							//$('#deliveries').slideDown('slow');
							slideToggle('#deliveries',true);
							//$('#standards').slideDown('slow');
							slideToggle('#standards',true);
							// Is standard selected
							if(!$('input[name=standard]').is(':checked')) {
								$('#price-title').attr('class', 'row-title-focus');
							}
						}
					}
				}
			} else if ($(this).attr('id') == 'open-words') {
				var val = $('#subject').val();
				// Check if value is set
				if (!empty(val)) {
					$(this).hide();
					// Check if words are empty
					if(empty($('input[name=word]').val()) || empty($('#words-selection').html()) || !isNumeric($('input[name=word]').val().replace(',',''))) {
						$('#open-deliveries').show();
					} else {
						$('#open-deliveries').hide();
						//$('#words').slideDown('slow');
						slideToggle('#words',true);
						//$('#deliveries').slideDown('slow');
						slideToggle('#deliveries',true);
						//$('#standards').slideDown('slow');
						slideToggle('#standards',true);
					}
					// Check subject against cost array
					for(key in subject_costs) {
						// Define service
						if(parseInt($('#service:checked').val()) == 1) {
							var serv = 'academic';	
						} else {
							var serv = 'law';	
						}
						if(key.toLowerCase() == serv + '-' + val.toLowerCase()) {
							// Set subject cost
							$('#subject-cost').val(subject_costs[key]);
						}
					}
				}
			} else if ($(this).attr('id') == 'open-deliveries') {
				var val = $('input[name=word]').val().replace(',','');
				// Check if value is set
				if (!empty(val) && !isNumeric(val)) {
					// Output error
					$('#word-error').html('Please enter a numeric value. e.g a whole number').show();
				} else {
					// Hide error
					$(this).hide();	
					$('#word-error').hide();
					// Slide words up
					//$('#words').slideUp('slow');
				}
			}
			// Close open sections
			$('.row-main').each(function () {
				if ($(this).is(':visible')) {
					// Close
					if ($(this).attr('id') == 'services') {
						var val = $('input[name=service]:checked').val();
						// Check if value is set
						if (!empty(val)) {
							//$(this).slideUp('slow');
							slideToggle(this,false);
						}
					} else if ($(this).attr('id') == 'subjects') {
						// Check if value is set
						if (empty($('#subject').val())) {
							// Output error
							$('#subject-error').show();
						} else {
							// Hide error
							$('#subject-error').hide();
							//$(this).slideUp('slow');
							slideToggle(this,false);
							$('#subjects-title').removeClass();
							$('#subjects-title').addClass('row-title-complete');
						}
					} else if ($(this).attr('id') == 'words') {
						// Check if value is set
						if ($('input[name=word]').val() == '') {
							// Output error
							$('#word-error').html('Cannot be empty');
							$('#word-error').show();
						} else if (isNumeric($('input[name=word]').val().replace(',','')) == false) {
							// Output error
							$('#word-error').html('Must be numeric');
							$('#word-error').show();
						} else {
							// Hide error
							$('#word-error').hide();
							// Selection empty?
							if(!empty($('#words-selection').html())) {
								//$(this).slideUp('slow');
							}
							$('#words-title').removeClass();
							$('#words-title').addClass('row-title-complete');
						}
					} else if ($(this).attr('id') !== 'standards' && $(this).attr('id') !== 'deliveries' && $(this).attr('id') !== 'words') {
						//$(this).slideUp('slow');
						slideToggle(this,false);
					}
					// Restore edit style
					$('.edit-button-disabled').each(function () {
						$(this).removeClass('edit-button-disabled').addClass('edit-button');									  
					});
					// Set edit text
					$('.edit-button').each(function () {
						$(this).children('a').html('edit');
					});
				}
			});
			// Open next
			var id = $(this).attr('id').split('-');
			$('.row-main').each(function () {
				if ($(this).attr('id') == id[1]) {
					// Display dependant levels
					if (id[1] == 'levels') {
						var val = $('input[name=service]:checked').val();
						// Check if value is set
						if (!empty(val)) {
							// Swap class for title
							$('#services-title').removeClass();
							$('#services-title').addClass('row-title-complete');
							// Display levels
							var value = $('input[name=service]:checked').val();
							$('.level-block').each(function() {
								if ($(this).attr('id') == 'level_' + value) {
									$(this).show();	
								} else {
									$(this).hide();	
								}
							});
							// Clear level selection text and edit button
							$('#edit-services').show();
							// Change edit text and display selection
							$('#services-selection').html(selected_service);
							$('#edit-services').children('a').html('edit');
							// Open next if level not set
							if(!$('input[name=level]').is(':checked') || empty($('#levels-selection').html())) {
								$('#levels-title').removeClass();
								$('#levels-title').addClass('row-title-focus');
								$('#levels-selection').html('');
								//$(this).slideDown('slow');
								slideToggle(this,true);
							} else if(!$('input[name=type]').is(':checked') || empty($('#types-selection').html())) {
								$('#types-title').removeClass();
								$('#types-title').addClass('row-title-focus');
								$('#types-selection').html('');		
								//$('#types').slideDown('slow');
								slideToggle('#types',true);
							} else if(empty($('input[name=subject]').val()) || empty($('#subjects-selection').html())) {
								$('#subjects-title').removeClass();
								$('#subjects-title').addClass('row-title-focus');
								$('#subjects-selection').html('');		
								//$('#subjects').slideDown('slow');
								slideToggle('#subjects',true);
							} else if(empty($('input[name=word]').val()) || empty($('#words-selection').html()) || !isNumeric($('input[name=word]').val().replace(',',''))) {
								$('#words-title').removeClass();
								$('#words-title').addClass('row-title-focus');
								$('#words-selection').html('');		
								//$('#words').slideDown('slow');
								slideToggle('#words',true);
							}
							
						}
					} else if (id[1] == 'types') {
						// Swap class for title
						$('#levels-title').removeClass();
						$('#levels-title').addClass('row-title-complete');
						// Display types
						var value = $('input[name=level]:checked').val();
						$('.type-block').each(function() {
							if ($(this).attr('id') == 'type_' + value) {
								$(this).show();	
							} else {
								$(this).hide();	
							}
						});
						// Display standards
						$('.standard-block').each(function() {
							if ($(this).attr('id') == 'standard_' + value) {
								$(this).show();	
							} else {
								$(this).hide();	
							}
						});
						// Clear level selection text
						$('#edit-levels').show();
						// Change edit text and display selection
						$('#levels-selection').html(selected_level);
						$('#edit-levels').children('a').html('edit');
						// Open next if value not set
						if(!$('input[name=type]').is(':checked') || empty($('#types-selection').html())) {
							$('#types-title').removeClass();
							$('#types-title').addClass('row-title-focus');
							$('#types-selection').html('');
							//$(this).slideDown('slow');
							slideToggle(this,true);
						} else if(empty($('input[name=subject]').val()) || empty($('#subjects-selection').html())) {
							$('#subjects-title').removeClass();
							$('#subjects-title').addClass('row-title-focus');
							$('#subjects-selection').html('');
							//$('#subjects').slideDown('slow');
							slideToggle('#subjects',true);
						} else if(empty($('input[name=word]').val()) || empty($('#words-selection').html()) || !isNumeric($('input[name=word]').val().replace(',',''))) {
							$('#words-title').removeClass();
							$('#words-title').addClass('row-title-focus');
							$('#words-selection').html('');		
							//$('#words').slideDown('slow');
							slideToggle('#words',true);
						}
					} else if (id[1] == 'subjects') {
						// Swap class for title
						$('#types-title').removeClass();
						$('#types-title').addClass('row-title-complete');
						// Display subject next button if no value
						if(empty($('input[name=subject]').val()) || empty($('#subjects-selection').html())) {
							$('#subjects-title').removeClass();
							$('#subjects-title').addClass('row-title-focus');
							// Clear level selection text
							$('#subjects-selection').html('');
							// Open next
							//$(this).slideDown('slow');
							slideToggle(this,true);
						} else if(empty($('input[name=word]').val()) || empty($('#words-selection').html()) || !isNumeric($('input[name=word]').val().replace(',',''))) {
							$('#words-title').removeClass();
							$('#words-title').addClass('row-title-focus');
							$('#words-selection').html('');		
							//$('#words').slideDown('slow');
							slideToggle('#words',true);
						}
						// Change edit text and display selected
						$('#types-selection').html(selected_type);
						$('#edit-types').show();
						$('#edit-types').children('a').html('edit');
					} else if (id[1] == 'words') {
						var val = $('#subject').val();
						// Check that subject is set
						if(!empty(val)) {
							// Swap class for title
							$('#subjects-title').removeClass();
							$('#subjects-title').addClass('row-title-complete');
							// Display subjects value
							$('#subjects-selection').html(val);
							$('#edit-subjects').show();
							// Display words next button if no value
							if (empty($('input[name=word]').val()) || empty($('#words-selection').html()) || !isNumeric($('input[name=word]').val().replace(',',''))) {
								$('#words-title').removeClass();
								$('#words-title').addClass('row-title-focus');
								// Open next
								//$(this).slideDown('slow');
								slideToggle(this,true);
							}
							// Change edit text
							$('#edit-subjects').children('a').html('edit');
						}
					} else if (id[1] == 'deliveries') {
						var val = $('input[name=word]').val();
						// Check if value is set
						if (empty(val)) {
							// Output error
							$('#word-error').html('Cannot be empty');
							$('#word-error').show();
						} else if (isNumeric(val.replace(',','')) == false) {
							// Output error
							$('#word-error').html('Must be numeric');
							$('#word-error').show();
						} else {
							// Swap class for title
							$('#words-title').removeClass('row-title-focus');
							$('#words-title').addClass('row-title-complete');
							$('#delivery-title').removeClass('row-title-disabled');
							$('#delivery-title').addClass('row-title-focus');
							// Display subjects value
							$('#words-selection').html(val);
							$('#edit-words').show();
							// Display standards
							//$('#standards').slideDown('slow');
							slideToggle('#standards',true);
							// Change edit text
							$('#edit-words').children('a').html('edit');
							// Open next
							//$(this).slideDown('slow');
							slideToggle(this,true);
						}
					}
				}
			});
		}
	});
	
	// Listen for subject
	var totalitems = 0;
	var keycounter = 0;
	$("#subject").keyup(function (e) {
		// Clear standard
		$('input[name=standard]').attr('checked',false);
		$('.standard-opt-set').each(function() {
			$(this).attr('class','box standard-opt');				 
		});
		// Clear selection
		$('#subjects-selection').html('');
		$('#subjects-title').attr('class','row-title-focus');
		if(empty($('#word').val())) {
			$('#delivery-title').attr('class','row-title-disabled');
		}
		$('#edit-subjects').hide();
		// Check that arrow keys are not pressed
		if (e.keyCode !== 40 && e.keyCode !== 38 && e.keyCode !== 13) {
			// Reset counter
			keycounter = 0;
			// Get subject value
			var value = $(this).val();
			var nextStep = $(this).parent().parent().siblings('.next-step').find('a');
			// Check if value is set and minimum is met
			if (value.length < 2) {
				// Minimum not met
				$('#subject-cost').val('');
				$('#subject-suggest').hide();
				$('#open-words').removeClass('active');
				// Deactivate continue button
				nextStep.removeClass('active');
				// Clear cost
				$('#price-val').val('');
				$('#bottom-price').html('');
			} else {
				// Activate continue button
				nextStep.addClass('active');
				// Display open words (next step)
				$('#edit-subjects').hide();
				$('#open-words a').addClass('active');
				// Convert service ID to text
				var service = $('#service:checked').val();
				if (service == 1) {
					service = 'academic';	
				} else {
					service = 'law';	
				}
				// Find subjects
				$.get('subjects.php?q=' + value + '&type=' + service, function(data) {
					// Found suggestions?
					if (data !== 'false') {
						// Show suggestion box
						$('#subject-suggest').show();
						// Extract data
						var output = '';
						var suggestions = data.split('<>');
						totalitems = parseInt(suggestions.length - 2);
						for(i = 0; i <= suggestions.length - 2; i++) {
							// Get sub data
							var subdata = suggestions[i].split('|');
							output = output + '<div id="suggest-' + i + '"><a onclick="setSuggestion(\'' + subdata[0] + '\',' + subdata[1] + ')" id="' + subdata[0] + '|' + subdata[1] + '">' + subdata[0] + '</a></div>';
						}
						// Display suggestions
						$('#subject-suggest').html('<a id="close-suggest" onclick="closeSuggestion();">Close</a>').prepend(output);
					} else {
						// Hide suggestion box
						$('#subject-suggest').hide();
						// Unknown subject so use default value
						$('#subject-cost').val(subject_default);
					}
				});
			}
		}
	});
	
	// Assign arrow keys to subject select
	var keypressed = '';
	$(document).keydown(function(e) {
		// On down key
		if (e.keyCode == 40) {
		   $('#suggest-' + keycounter).focus();
		   // Has end of list been reached
		   if (keycounter <= totalitems) {
			   // Highlight selected
			   if (keypressed == 'down') {
					$('#suggest-' + parseInt(keycounter - 1)).removeClass('suggest-highlight');
					$('#suggest-' + keycounter).addClass('suggest-highlight');
			   } else if (keypressed == 'up') {
					keycounter++;
					$('#suggest-' + parseInt(keycounter)).removeClass('suggest-highlight');
					$('#suggest-' + parseInt(keycounter + 1)).addClass('suggest-highlight');
					keycounter++;
			   } else {
					$('#suggest-' + keycounter).addClass('suggest-highlight');
			   }
			   // Cache counters
			   keypressed = 'down';
			   keycounter++;
		   }
		// On up key
		} else if (e.keyCode == 38) {
		   $('#suggest-' + keycounter).focus();
		   // Has end of list been reached
		   if (keycounter >= 0) {
			   // Highlight selected
			   if (keypressed == 'up') {
					$('#suggest-' + parseInt(keycounter + 1)).removeClass('suggest-highlight');
					$('#suggest-' + keycounter).addClass('suggest-highlight');
			   } else if (keypressed == 'down') {
					keycounter--;
					$('#suggest-' + parseInt(keycounter)).removeClass('suggest-highlight');
					$('#suggest-' + parseInt(keycounter - 1)).addClass('suggest-highlight');
					keycounter--;
			   }
			   // Cache counters
			   keypressed = 'up';
			   keycounter--;
		   }
		// On enter key
		} else if (e.keyCode == 13) {
			var value = $('.suggest-highlight').children('a').attr('id').split('|');
			var text = value[0];
			var cost = value[1];
			$('#subject').val(text);
			$('#subject-cost').val(cost);
			// Rest counter
			keycounter = 0;
			// Close suggestions
			$('#subject-suggest').hide();
			// Return false
			return false;
		}
	});
	
	// Listen for words to remove set delivery limits
	$("input[name=word]").keyup(function (e) {
		// Clear standard
		$('input[name=standard]').attr('checked',false);
		$('.standard-opt-set').each(function() {
			$(this).attr('class','box standard-opt');				 
		});
		// Words
		var words = $(this).val().replace(',','');
		// Reset deliveries
		$('#delivery').html(delivery_rebuild);
		// Display show deliveries and close edit
		$('#bottom-price').html('');
		if (!empty(words) && isNumeric(words) && words >= 250) {
			$('#open-deliveries a').addClass('active');
			$('#word-error').hide();
			$('#words-title').attr('class', 'row-title-complete');
		} else {
			if (empty(words)) {
				$('#word-error').html('Please enter a value of at least 250').show();
			} else if(words.length < 3) {
				$('#word-error').html('Please enter a value of at least 250').show();
			} else if (!isNumeric(words)) {
				$('#word-error').html('Please enter a numeric value. e.g a whole number').show();
			}
			$('#open-deliveries a').removeClass('active');
			$('#words-title').attr('class', 'row-title-focus');
		}
		$('#edit-words').hide();
		// Remove if limit set
		for(i = 0; i <= delivery_limit.length - 1; i++) {
			// Set var
			var data = delivery_limit[i].split('|');
			if (parseInt(words) >= parseInt(data[1])) {
				// Remove delivery item from select
				$("#delivery option").each(function(i){
					if ($(this).val() == parseInt(data[0])) {
						$(this).remove();	
					}
				});
			}
		}
		// Remove old slider
		$('#deliv').children("div").remove();
		// 05/07/2010 - James (Set to 30days if level above masters or law)
		if($('#service:checked').val() == 2 || $('#level:checked').val() == 3 || $('#level:checked').val() == 4) {
			$('select#delivery').val(2);
		} else {
			$('select#delivery').val(4);	
		}
		// Reload slider
		$('select#delivery').selectToUISlider({
			labels: 8,
			tooltip: true,
			labelSrc: 'text'
		});
		$('select#delivery').next().bind('slide',function(e, ui) {
			$('#price-val').val('');						  
			$('input[name=standard]').attr('checked', false);
			$('.standard-opt-set').each(function() {
				$(this).attr('class','box standard-opt');				 
			});
			$('#words-title').attr('class', 'row-title-complete');
			$('#delivery-title').attr('class', 'row-title-complete-edit');
			$('#deliveries').css('background-image','url(../style/images/order/step-bg-active.gif)');
			$('#words').css('background-image','url(../style/images/order/step-bg.gif)');
			$('#standards-title').attr('class', 'row-title-disabled');
			$('#bottom-price').html('');
			setTimeout("calculateCost(false);",100);
		});
	});
	
	// Expand information section
	$('#expand-info').click(function () {
		// If element is hidden
		if ($('#info').is(':hidden')) {
			$(this).addClass('min');
			$("#info").slideDown("slow");
		} else {
			$(this).removeClass();
			$("#info").slideUp("slow");	
		}
	});
	
	// Expand reference section
	$('#expand-ref').click(function () {
		// If element is hidden
		if ($('#ref').is(':hidden')) {
			$(this).addClass('min');
			$("#ref").slideDown("slow");
		} else {
			$(this).removeClass();
			$("#ref").slideUp("slow");	
		}
	});
	
	// Listen for complete title
	$('#details-title').keyup(function () {
		// Check for value
		if(empty($(this).val()) || $(this).val().length < 3) {
			$('#essay-title').attr('class', 'row-title-focus');
		} else {
			$('#essay-title').attr('class', 'row-title-complete-edit');
			// Focus personal
			var details_check = 0;
			$('.details-check').each(function() {
				if ($(this).val() !== '') {
					details_check++;
				} else {
					if (details_check !== 0) {
						details_check--;
					}
				}
			});
			if(details_check == 6) {
				$('#personal-title').attr('class', 'row-title-complete');
				$('#additional-title').attr('class', 'row-title-complete');
			}
		}
	});
	
	// Listen for terms
	$('#check-terms').click(function() {
		// Is checked?
		if($('#check-terms').is(':checked')) {
			$('#summary-title').attr('class', 'row-title-complete');
			$('#terms-title').attr('class', 'row-title-complete-edit');
			$('#terms-hint').hide();
			$('#summary-next').attr('disabled',false);
			
		} else {
			$('#terms-title').attr('class', 'row-title-disabled');
			$('#terms-hint').show();
			$('#summary-next').attr('disabled',true);

		}
	});
	
	// Listen for word input click
	$('#word').click(function() {
		if(!empty($(this).val())) {
			$('#delivery-title').attr('class', 'row-title-complete');
			$('#words-title').attr('class', 'row-title-complete-edit');
			// Darken bg
			$('#deliveries').css('background-image','url(../style/images/order/step-bg.gif)');
			$('#words').css('background-image','url(../style/images/order/step-bg-active.gif)');
			$('#standards-title').attr('class', 'row-title-disabled');
		}
	});
	
	// Listen for essay title click
	$('#details-title').click(function() {
		if(!empty($(this).val())) {
			$('#essay-title').attr('class','row-title-complete-edit');
		}
		// Focus personal
		var details_check = 0;
		$('.details-check').each(function() {
			if ($(this).val() !== '') {
				details_check++;
			} else {
				if (details_check !== 0) {
					details_check--;
				}
			}
		});
		if(details_check == 6) {
			$('#personal-title').attr('class', 'row-title-complete');
			$('#additional-title').attr('class', 'row-title-complete');
		}
	});
	
	// Listen for personal click
	$('.personal-input').click(function() {
		if(!empty($('#details-title').val())) {
			$('#essay-title').attr('class','row-title-complete');
		}
		// Focus personal
		var details_check = 0;
		$('.details-check').each(function() {
			if ($(this).val() !== '') {
				details_check++;
			} else {
				if (details_check !== 0) {
					details_check--;
				}
			}
		});
		if(details_check == 6) {
			$('#personal-title').attr('class', 'row-title-complete-edit');
			$('#additional-title').attr('class', 'row-title-complete');
		}
	});
	$('.personal-input').keyup(function() {
		if(!empty($('#details-title').val())) {
			$('#essay-title').attr('class','row-title-complete');
		}
		// Focus personal
		var details_check = 0;
		$('.details-check').each(function() {
			if ($(this).val() !== '') {
				details_check++;
			} else {
				if (details_check !== 0) {
					details_check--;
				}
			}
		});
		if(details_check == 6) {
			$('#personal-title').attr('class', 'row-title-complete-edit');
			$('#additional-title').attr('class', 'row-title-complete');
		}
	});
	
	// Calculate cost
	$('.calc-cost').change(function() {
		calculateCost(false);								
	});
	$('.calc-cost').keyup(function() {
		calculateCost(false);							   
	});
	$('.calc-cost').click(function() {
		calculateCost(false);							   
	});
	
	// Disable backspace
	function shouldCancelbackspace(e) {
		var key;
		if(e){
		key = e.which? e.which : e.keyCode;
		if(key == null || ( key != 8 && key != 13)){ // return when the key is not backspace key.
		return false;
		}
		}else{
		return false;
		}
		
		if (e.srcElement) { // in IE
		tag = e.srcElement.tagName.toUpperCase();
		type = e.srcElement.type;
		readOnly =e.srcElement.readOnly;
		if( type == null){ // Type is null means the mouse focus on a non-form field. Disable backspace button
		return true;
		}else{
		type = e.srcElement.type.toUpperCase();
		}
		
		} else { // in FF
		tag = e.target.nodeName.toUpperCase();
		type = (e.target.type) ? e.target.type.toUpperCase() : "";
		}
		
		// we don't want to cancel the keypress (ever) if we are in an input/text area
		if ( tag == 'INPUT' || type == 'TEXT' || type == 'TEXTAREA') {
		if(readOnly == true ) // if the field has been dsabled, disbale the back space button
		return true;
		if( ((tag == 'INPUT' && type == 'RADIO') || (tag == 'INPUT' && type == 'CHECKBOX'))
		&& (key == 8 || key == 13) ){
		return true; // the mouse is on the radio button/checkbox, disbale the backspace button
		}
		return false;
		}
		
		// if we are not in one of the above things, then we want to cancel (true) if backspace
		return (key == 8 || key == 13);
		}
		
		// check the browser type
		function whichBrs() {
		var agt=navigator.userAgent.toLowerCase();
		if (agt.indexOf("opera") != -1) return 'Opera';
		if (agt.indexOf("staroffice") != -1) return 'Star Office';
		if (agt.indexOf("webtv") != -1) return 'WebTV';
		if (agt.indexOf("beonex") != -1) return 'Beonex';
		if (agt.indexOf("chimera") != -1) return 'Chimera';
		if (agt.indexOf("netpositive") != -1) return 'NetPositive';
		if (agt.indexOf("phoenix") != -1) return 'Phoenix';
		if (agt.indexOf("firefox") != -1) return 'Firefox';
		if (agt.indexOf("safari") != -1) return 'Safari';
		if (agt.indexOf("skipstone") != -1) return 'SkipStone';
		if (agt.indexOf("msie") != -1) return 'Internet Explorer';
		if (agt.indexOf("netscape") != -1) return 'Netscape';
		if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
		
		if (agt.indexOf('\/') != -1) {
		if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
		return navigator.userAgent.substr(0,agt.indexOf('\/'));
		}else
		return 'Netscape';
		}else if (agt.indexOf(' ') != -1)
		return navigator.userAgent.substr(0,agt.indexOf(' '));
		else
		return navigator.userAgent;
		}
		
		// Global events (every key press)
		
		var browser = whichBrs();
		if(browser == 'Internet Explorer'){
		document.onkeydown = function() { return !shouldCancelbackspace(event); }
		}else if(browser == 'Firefox'){
		document.onkeypress = function(e) { return !shouldCancelbackspace(e); }
		} 
	
});

// Set suggestions
function setSuggestion(title, cost) {
	
	// Clear standard
	$('input[name=standard]').attr('checked',false);
	$('.standard-opt-set').each(function() {
		$(this).attr('class','box standard-opt');				 
	});
	
	// Set value
	$('#subject').val(title);
	$('#subject-cost').val(cost);
	
	// Close suggestions
	$('#subject-suggest').hide();
	
	// Calculare
	calculateCost(false);
	
}

// Close suggestions
function closeSuggestion() {
	$('#subject-suggest').hide();
}

// Calculate cost
function calculateCost() {

	// If next day
	if($('#delivery').val() == 7 || $('#delivery').val() == 8) {
		$('#delivery-note').show();
		$('#delivery-info').hide();
	} else {
		$('#delivery-note').hide();	
		$('#delivery-info').show();
	}

	// Collect information
	var cost = new Array();
	cost[0] = $('input[name=level]:checked').val(); // Level
	cost[1] = $('input[name=type]:checked').val(); // Type
	cost[2] = $('#subject-cost').val(); // Subject
	cost[3] = $('input[name=word]').val().replace(',',''); // Words
	cost[4] = $('#delivery').val(); // Delivery
	
	// Loop through and check if set
	var allset = 1;
	for(i = 0; i <= cost.length - 1; i++) {
	
		if (cost[i] == '' || typeof cost[i] === 'undefined') {
			allset = 0;
			// Clear cost
			$('#price-val').val('');
			// Disable next button
			$('#next').attr('disabled',true);
		}
	
	}
	// Last check for word string length
	if (cost[3].length < 3 || cost[3] < 250 || !isNumeric(cost[3].replace(',',''))) {
		allset = 0;
		// Clear cost
		$('.standard-cost').each(function() {
			$(this).html('');								  
		});
		$('#price-val').val('');
		// Disable next button
		$('#next').attr('disabled',true);
	}
	
	// if all are set
	if (allset == 1) {
		
		// Set final cost var
		var final = 0;
		
		// Gather cost values
		var level = eval('level_' + cost[0]);
		var type = eval('type_' + cost[1]);
		var subject = cost[2];
		var words = cost[3] / 1000;
		var delivery = eval('delivery_' + cost[4]);
		
		// If Masters order, add extra 5% discount
		discount = (cost[0] == 4 || cost[0] == 99) ? 0.75 : 0.8;			
		
		// Calculate
		var final = level;
		final = final * type;
		final = final * subject;
		final = final * words;
		final = final * delivery;
		
		// Check for cost increase
		var increase = 0;
		for(i = 0; i <= delivery_increase.length - 1; i++) {
			// Retrieve data
			var data = delivery_increase[i].split('|');
			// Check if defined limit is set
			if (parseInt(cost[4]) == parseInt(data[0])) {
				// Check if word limit has been reached
				if (parseInt(cost[3]) >= parseInt(data[1])) {
					// Increase cost
					increase = data[2];
				}
			}
		
		}
		// If increase set
		if (increase !== 0) {
			final = final * increase;
		}
		
		// Calculate cost for standards
		$('.standard-block').each(function() {
			if($(this).is(':visible')) {
				$(this).children('.box').each(function() {
					// Calculate defined cost
					var value = $(this).children('input[type=radio]').attr('value');
					var cost = final * eval('standard_' + value);
					// Round up to nearest 5
					cost = Math.ceil(cost/5) * 5;
					// Check if value below minimum
					if(cost < minimum_price) {
						cost = minimum_price;	
					}
					
					// Calculate 20% discount
					cost_discount = Math.ceil((cost * discount)/5) * 5;
					
					// Output standard cost
					$('#standard-' + value + '-cost').attr('title',cost);
					cost = (isNaN(cost) ? '' : '&pound;' + cost);
					$('#standard-' + value + '-cost').html(addCommas(cost));
					// Output standard discount cost
					$('#standard-' + value + '-cost-discount').attr('title',cost_discount);
					cost_discount = (isNaN(cost_discount) ? '' : '&pound;' + cost_discount);
					$('#standard-' + value + '-cost-discount').html(addCommas(cost_discount));
				});
			}
		});
		
		// Sort standards (exclude 2:2/2:1/etc)
		//$(".standard-block>.box").tsort(".standard-cost",{order:"asc",attr:"title"}); 
		
		// Group similar standard
		var group = false;
		$('#standard_' + cost[0]).children('.box').each(function() {
			//alert($(this).attr('lang'));														 
		});
		
		// Enable/Disable next button
		if(empty($('input[name=standard]:checked').val())) {
			$('#next').attr('disabled',true);
		} else {
			$('#next').attr('disabled',false);	
		}
		
		// Bottom price
		var rrp = $('#standard-' + $('input[name=standard]:checked').val() + '-cost').html().substr(1);
		var price = $('#standard-' + $('input[name=standard]:checked').val() + '-cost-discount').html().substr(1);
		$('#bottom-price').html('&pound;' + $('#standard-' + $('input[name=standard]:checked').val() + '-cost-discount').html().substr(1));
		// Set rrp value
		$('#price-rrp').val(rrp);
		// Set price value
		$('#price-val').val(price);
	}

}

// Edit section
function editSection(section) {
	var s;
	// Hide all other sections
	for (var i = 0; i < sections.length; i++) {
		if (sections[i] != section) {
			s = $('#' + sections[i]);
			if (s.is(':visible')) {
				//s.slideUp('slow');
				slideToggle(s,false);
				s.siblings('.next-step').hide();
				if (s.siblings('.row-title-focus')) {
					s.siblings('.row-title-focus').attr('class', 'row-title-disabled');
				}
			}
		}
	}
	// Set subject if continue was not pressed
	if(!empty($('#subject').val())) {
		$('#subjects-title').attr('class','row-title-complete');
		$('#subjects-selection').html($('#subject').val());
		$('#edit-subjects').show();
		// Check if subject cost is set
		if(empty($('#subject-cost').val())) {
			$('#subject-cost').val(subject_default);	
		}
	}
	// Reset style
	$('.row-title-complete-edit').each(function () {
		$(this).attr('class', 'row-title-complete');
	});
	$('.row-title-focus').each(function () {
		$(this).attr('class', 'row-title-disabled');
	});
	// Restore edit style
	$('.edit-button-disabled').each(function () {
		$(this).removeClass('edit-button-disabled').addClass('edit-button');									  
	});
	// Fade set edit
	$('#edit-' + section).addClass('edit-button-disabled');
	// Set words to complete if set
	if(!empty($('#words').val())) {
		$('#words-title').attr('class', 'row-title-complete');
	}
	//$('#deliveries').slideUp('slow');
	slideToggle('#deliveries',false);
	//$('#standards').slideUp('slow');
	slideToggle('#standards',false);
	s = $('#' + section);
	// Swap class
	$('#' + section + '-title').removeClass().addClass('row-title-complete-edit');
	// Re-open section
	//s.slideDown('slow');
	slideToggle(s,true);
	// Show next step button
	s.siblings('.next-step').show();
	// Hide edit button and title
}

// Check subject
function checkSubject() {
	if(empty($('#subject-cost').val())) {
		var value = $('#subject').val();
		var nextStep = $(this).parent().parent().siblings('.next-step').find('a');
		if (value.length < 2) {
			// Minimum not met
			$('#subject-cost').val('');
			$('#subject-suggest').hide();
			$('#open-words').removeClass('active');
			// Deactivate continue button
			nextStep.removeClass('active');
		} else {
			// Activate continue button
			nextStep.addClass('active');
			// Display open words (next step)
			$('#open-words a').addClass('active');
			$('#subject-cost').val(subject_default);
		}
	}
}

// Validate details
function validateDetails() {
	var details_check = 0;
	$('.details-check').each(function() {
		if ($(this).val() !== '') {
			details_check++;
		} else {
			if (details_check !== 0) {
				details_check--;
			}
		}
	});
	// Check if ok
	if (details_check == 6) {
		$('#details-next').attr('disabled',false);
	} else if($('#personal-title').attr('class', 'row-title-disabled')) {
		// Check if title is complete
		if($('#details-title').val().length < 3) {
			$('#personal-title').attr('class', 'row-title-disabled');
		} else {
			$('#personal-title').attr('class', 'row-title-focus');
		}
	} else if($('#personal-title').attr('class', 'row-title-focus')) {
		// Check if title is complete
		if($('#details-title').val().length < 3) {
			$('#personal-title').attr('class', 'row-title-disabled');
		} else {
			$('#personal-title').attr('class', 'row-title-focus');
		}
	} else {
		$('#personal-title').attr('class', 'row-title-disabled');
	}
}

// Make cheaper (move slider right)
function makeCheaper() {
	// Clear standard
	$('input[name=standard]').attr('checked',false);
	$('.standard-opt-set').each(function() {
		$(this).attr('class','box standard-opt');				 
	});
	// Focus row
	$('#delivery-title').attr('class', 'row-title-complete-edit');
	$('#standards-title').attr('class', 'row-title-disabled');
	$('#words-title').attr('class', 'row-title-complete');
	$('#deliveries').css('background-image','url(../style/images/order/step-bg-active.gif)');
	$('#words').css('background-image','url(../style/images/order/step-bg.gif)');
	$('#bottom-price').html('');
	// Set selection
	var selection = $('#delivery').val();
	// Check if end is reached
	if(selection > 1) {
		selection--;
	}
	$('#delivery').val(selection);
	// Remove old slider
	$('#deliv').children("div").remove();
	// Reload slider
	$('select#delivery').selectToUISlider({
		labels: 8,
		tooltip: true,
		labelSrc: 'text'
	});
	$('select#delivery').next().bind('slide',function(e, ui) {
		$('#price-val').val('');						  
		// Clear standard
		$('input[name=standard]').attr('checked',false);
		$('.standard-opt-set').each(function() {
			$(this).attr('class','box standard-opt');				 
		});
		$('#delivery-title').attr('class', 'row-title-complete-edit');
		$('#standards-title').attr('class', 'row-title-disabled');
		$('#deliveries').css('background-image','url(../style/images/order/step-bg-active.gif)');
		$('#words').css('background-image','url(../style/images/order/step-bg.gif)');
		$('#words-title').attr('class', 'row-title-complete');
		$('#bottom-price').html('');
		setTimeout("calculateCost(false);",100);
	});
	calculateCost(false);
}

// Make cheaper (move slider right)
function makeQuicker() {
	// Clear standard
	$('input[name=standard]').attr('checked',false);
	$('.standard-opt-set').each(function() {
		$(this).attr('class','box standard-opt');				 
	});
	// Focus row
	$('#delivery-title').attr('class', 'row-title-complete-edit');
	$('#standards-title').attr('class', 'row-title-disabled');
	$('#deliveries').css('background-image','url(../style/images/order/step-bg-active.gif)');
	$('#words').css('background-image','url(../style/images/order/step-bg.gif)');
	$('#words-title').attr('class', 'row-title-complete');
	$('#bottom-price').html('');
	// Set selection
	var selection = $('#delivery').val();
	// Check if end is reached
	if(selection < 8) {
		selection++;
	}
	$('#delivery').val(selection);
	// Remove old slider
	$('#deliv').children("div").remove();
	// Reload slider
	$('select#delivery').selectToUISlider({
		labels: 8,
		tooltip: true,
		labelSrc: 'text'
	});
	$('select#delivery').next().bind('slide',function(e, ui) {
		$('#price-val').val('');						  
		// Clear standard
		$('input[name=standard]').attr('checked',false);
		$('.standard-opt-set').each(function() {
			$(this).attr('class','box standard-opt');				 
		});
		$('#delivery-title').attr('class', 'row-title-complete-edit');
		$('#standards-title').attr('class', 'row-title-disabled');
		$('#deliveries').css('background-image','url(../style/images/order/step-bg-active.gif)');
		$('#words').css('background-image','url(../style/images/order/step-bg.gif)');
		$('#words-title').attr('class', 'row-title-complete');
		$('#bottom-price').html('');
		setTimeout("calculateCost(false);",100);
	});
	calculateCost(false);
}

// Show full summary
function fullSummary() {
	// Swap text
	if($('#full-summary').is(':visible')) {
		$('#show-full-summary').children('a').html('View full order');	
	} else {
		$('#show-full-summary').children('a').html('Hide full order');	
	}
	$('#full-summary').slideToggle();
}

// Hide quicker/cheaper
function hideQC() {
	// Hide quicker
	if($('#delivery option[value=8]').length > 0) {
		if($('#delivery').val() == 8) {
			$('#make-quicker').fadeOut();
		} else {
			$('#make-quicker').fadeIn();	
		}
	} else if($('#delivery option[value=7]').length > 0) {
		if($('#delivery').val() == 7) {
			$('#make-quicker').fadeOut();
		} else {
			$('#make-quicker').fadeIn();
		}
	} else if($('#delivery option[value=6]').length > 0) {
		if($('#delivery').val() == 6) {
			$('#make-quicker').fadeOut();
		} else {
			$('#make-quicker').fadeIn();
		}
	} else {
		if($('#delivery').val() == 5) {
			$('#make-quicker').fadeOut();
		} else {
			$('#make-quicker').fadeIn();
		}
	}
	
	// Hide cheaper
	if($('#delivery').val() == 1) {
		$('#make-cheaper').fadeOut();
	} else {
		$('#make-cheaper').fadeIn();
	}	
}
setInterval("hideQC();",250);

// Validate numeric
function isNumeric(value) {
	var anum = /^\d+(\.\d+)?$/;
	return anum.test(value);
}

// Check that a string is defined
function empty(value) {
	return (value == '' || typeof value === 'undefined');
}

// Slide up/down IE fix
function slideToggle(el, bShow){
  var $el = $(el), height = $el.data("originalHeight"), visible = $el.is(":visible");
  // if the bShow isn't present, get the current visibility and reverse it
  if( arguments.length == 1 ) bShow = !visible;
  // if the current visiblilty is the same as the requested state, cancel
  if( bShow == visible ) return false;
  // get the original height
  if( !height ){
    // get original height
    height = $el.show().height();
    // update the height
    $el.data("originalHeight", height);
    // if the element was hidden, hide it again
    if( !visible ) $el.hide().css({height: 0});
  }
  // expand the knowledge (instead of slideDown/Up, use custom animation which applies fix)
  if( bShow ){
    $el.show().animate({height: height}, {duration: 250});
  } else {
    $el.animate({height: 0}, {duration: 250, complete:function (){
        $el.hide();
      }
    });
  }
  // Update right coloumn height
  setTimeout("$('.col-right').animate({height: $('.col-left').height()}, {duration: 250});",180);
}

// Format prices, e.g 2,000
function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}