var HB = {

	/*
	 * Harrington Brooks starts here...
	 */
	init: function() {
		this.homepageHero.init();
		this.clearAndRestore.init();
		this.sliders.init();
		this.randomQuotes.init();
		this.solutionFinders.init();
		this.contactForm.init();
		this.phoneNumberValidation.init();
		this.formErrors.init();
		this.mailtoHyperlinks.init('.mailto');
	},
	
	
	/*
	 * Cycle through each of the Homepage Hero slides
	 */
	homepageHero: {
		timer: false,
		speed: 6500,
		
		noOfSlides: 0,
		activeIndex: 0,
		
		$hero: {},
		$slides: {},
	
		// Load the slides. If we have any, start the cycle.
		// Also add events to move forward/backwards.
		init: function() {
			this.$hero = $('section.hero');
			this.$slides = this.$hero.find('.hero_slide');
			this.noOfSlides = this.$slides.length;
			
			if (this.noOfSlides > 0) {
				this.start();
			}
			
			$('.hero_nav .prev_slide').click($.proxy(this, 'prev'));
			$('.hero_nav .next_slide').click($.proxy(this, 'next'));
		},
		
		// Start or re-start the timing interval
		start: function() {
			var self = this;
			clearInterval(this.timer);
			this.timer = setInterval(function(){ self.cycle(); }, this.speed);
		},
		
		// Fade in the new slide, whilst fading out the current.
		// Reset the loop when we reach the end.
		cycle: function(slide) {
			if (slide < 0) {
				return;
			}
		
			var current = this.activeIndex;
			
			if (typeof slide != 'undefined') {
				this.activeIndex = slide;
			} else {
				this.activeIndex++;
				slide = this.activeIndex;
			}

			if (slide >= this.noOfSlides) {
				this.reset();
			}
			
			if (slide >= 0) {
				this.$slides.filter(':eq('+current+')').fadeOut();
				this.$slides.filter(':eq('+slide+')').fadeIn();
			}
		},
		
		// Go back to the beginning.
		reset: function() {
			this.activeIndex = 0;
			this.$slides.filter(':eq(0)').fadeIn();
		},
		
		// Re-start the cycle from the previous slide
		prev: function() {
			this.cycle(this.activeIndex - 1);
			this.start();
		},
		
		// Re-start the cycle from the next slide
		next: function() {
			this.cycle(this.activeIndex + 1);
			this.start();
		}
	},
	

	/*
	 * Clear a text field on focus,
	 * and restore its value on blur
	 */
	clearAndRestore: {
		init: function() {
			$('.clear-and-restore-all input[type=text]').each(this.clearAndRestore);
			$('.clear-and-restore').each(this.clearAndRestore);
		},
		
		clearAndRestore: function() {
			var $field = $(this);
			var initialValue = $field.val();
			$field.data('initial_value', initialValue);
			
			$field.bind({
				blur: function() {
					if (!$(this).val()) {
						$(this).val(initialValue);
					}
				},
				focus: function() {
					if ($(this).val() == initialValue) {
						$(this).val('');
					}
				}
			});
		}
	},
	
	
	/*
	 * Set up jQuery UI sliders.
	 */
	sliders: {
		init: function() {
			if (!$.ui) return;
		
			this.money();
			this.addGrips();
			this.initialValues();
		},
		
		// UI tweak, add a 'grip' to the handle.
		addGrips: function() {
			var $grip = $('<span/>', {className: 'grip'});
			$('.hb_slider .ui-slider-handle').append($grip);
		},
		
		// Update the visible value and the hidden
		// form input when the slider moves.
		changed: function(e, ui) {
			var $h = $(ui.handle);
			$h.parents('.hb_slider_container')
			   .next('.hb_slider_result')
			   .children('span.hb_slider_value').text( ui.value )
			   .next('input.hb_slider_value_input').val( ui.value );
		},
		
		// Trigger sliding on each slider so the inital
		// values get set in the form.
		
		
		initialValues: function() {
			$('.hb_slider').each(function() {
				var ui = {
					handle: $(this).children('.ui-slider-handle').get(0),
					value: $(this).slider('value')
				};
				HB.sliders.changed({}, ui);
			});
		},
		
	// Money sliders
		money: function() {
			var config = {
				value: 10000,
				step: 10,
				min: 0,
				max: 50000,
				slide: this.changed,
				change: this.changed
			};
			$('.hb_slider.money').each(function() {
				var matches = $(this).attr('class').match(/m([0-9]+)-([0-9]+)-([0-9]+)/);
				
				config.min = parseInt(matches[1]);
				config.value = parseInt(matches[2]);
				config.max = parseInt(matches[3]);
				
				$(this).slider(config);
			});
		},
		
		
		
		digitsonly: function() {
		
		$("#amount_of_debt").keypress(function (e)  
		{ 
	  	//if the letter is not digit then display error and don't type anything
	  	if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
	  	{
	   	 return false;
      	}	
	});
	
	
	
	
		}
	},
	
	
	

	
	
	
	/*
	 * Large & Small solution finders
	 */
	solutionFinders: {
		init: function() {
			this.large.init();
			this.small.init();
		},
	
	
		large: {
			$sf: {},
		
			init: function() {
				this.$sf = $('#solution_finder_large');
				this.$sfResults = $('#solution_finder_results_large');
				this.$sf.find('input[name=homeowner]').click($.proxy(this, 'homeowner'));
				this.$sf.find('.launch_sf_results').click($.proxy(this, 'showResults'));
			},
			
			// Show the iframe results
			showResults: function() {
				// this.$sfResults.slideDown('fast');	
				tb_show('', '#TB_inline?height=400&width=850&inlineId=solution_finder_results_large', '');
			},
			
			// Toggle visibility of homeowner-specific fields
			homeowner: function(e) {
				var $radio = $(e.currentTarget);
				var homeowner = ($radio.val() == 'yes');
				var $homeowner = this.$sf.find('.homeowner');
				
				$homeowner.toggle(homeowner);
				
				if (homeowner) {
					$homeowner.find(':input').removeAttr('disabled');
				} else {
					$homeowner.find(':input').attr('disabled', 'disabled');
				}
			}
		},
		
		/*
		 * The small solution finder has Next & Prev
		 * buttons which show/hide parts of the form.
		 */
		small: {
			$sf: {},
		
			// Add prev & next events
			init: function() {
				this.$sf = $('#solution_finder_small');
				this.$sfResults = $('#solution_finder_results_small');
				this.$sf.find('.next').live('click', $.proxy(this, 'next'));
				this.$sf.find('.prev').click($.proxy(this, 'prev'));
				this.$sf.find('.homeowner_choices input').click($.proxy(this, 'more'));
				this.$sf.find('.launch_sf_results').live('click', $.proxy(this, 'showResults'));
			},
			
			// Show the iframe results
			showResults: function() {
				// this.$sfResults.slideDown('fast');	
				tb_show('', '#TB_inline?height=400&width=850&inlineId=solution_finder_results_small', '');
			},
			
			// Show the next step in the form
			next: function(e) {
				this.reset();
				$(e.currentTarget).parents('.step').next().fadeIn('fast');
				return false;
			},

			// Show the previous step in the form
			prev: function(e) {
				this.reset();
				$(e.currentTarget).parents('.step').prev().fadeIn('fast');
				return false;
			},
			
			// Homeowners get asked more questions
			more: function(e) {
				var $choice = $(e.currentTarget);
				var $go = $choice.parents('.step').find('button');
				
				if ($choice.val() == 'no') {
					$go.text('Get Results!')
					   .addClass('launch_sf_results')
					   .removeClass('next');
				} else if ($choice.val() == 'yes') {
					$go.text('Continue')
					   .removeClass('launch_sf_results')
					   .addClass('next');
				}
			},
			
			// Hide all steps
			reset: function() {
				this.$sf.find('.step').hide();
			}
		}
	},
	
	
	/*
	 * Random Quotes in the sidebar
	 */
	randomQuotes: {
		speed: 5000,
		activeIndex: 0,
		noOfQuotes: 0,
		$quotes: {},
			init: function() {
			this.$quotes = $('.random_quotes .random_quote');
			this.noOfQuotes =  this.$quotes.length;
			this.$quotes.filter(':not(:eq(0))').hide();
			
			setInterval($.proxy(this, 'cycle'), this.speed);
		},
		
		// Fade out the current quote, then fade in the next.
		cycle: function() {
			this.$quotes.filter(':eq('+this.activeIndex+')').fadeOut($.proxy(this, 'next'));
		},
		
		// Fade in the next quote, reseting if we reach the end.
		next: function() {
			this.activeIndex++;
			this.$quotes.filter(':eq('+this.activeIndex+')').fadeIn();
			
			if (this.activeIndex >= this.noOfQuotes) {
				this.reset();
			}
		},
		
		// Go back to the beginning.
		reset: function() {
			this.activeIndex = 0;
			this.$quotes.hide().filter(':eq(0)').fadeIn();
		}
	},
	
	

	mailtoHyperlinks: {
		init: function(selector) {
			$(selector).each(this.convert);
		},
		
		convert: function() {
			var $elem = $(this);
			var email = $elem.text()
						.replace(/ at /, '@')
						.replace(/ dot /g, '.');
						
			$elem.html('<a href="mailto:'+email+'">'+email+'</a>');		
		}
	},
	
	
	/*
	 * When using the Contact Us form, show/hide certain
	 * fields depending on the chosen enquiry type.
	 */
	contactForm: {
	
		// Add an event to the enquiry type select box
		// Also add events to toggle the client reference number
		init: function() {

			this.$form = $('form[action="/contact"]');
			this.$enqType = this.$form.find('select[id$="enquiry-type"]');
			this.$CRN = $('#webform-component-client-reference-number');

			
			this.$enqType.change($.proxy(this, 'toggleFields'));
			$('#edit-submitted-client-reference-number').removeClass('required');
			$('#edit-submitted-existing-client-1').click($.proxy(this, 'showCRN'));
			$('#edit-submitted-existing-client-2').click($.proxy(this, 'hideCRN'));
		},
		
		// Depending on the enquiry type, show/hide certain fields
		toggleFields: function(e) {
			var fields = '';
			
			var type = this.$enqType.children('option:selected').text();
			

			if( type != 'IVA Client' && type != 'Debt Management Client'){
				$('#webform-component-client-reference-number').hide();
			}else{
				$('#webform-component-client-reference-number').show();
			}
		},
		
		showCRN: function() { this.$CRN.show();	},
		hideCRN: function() { this.$CRN.hide(); }
	},	

	
	phoneNumberValidation: {
		init: function() {
			$(':input[id$="phone-number"]').live('keypress', this.validate);
		},
		
		validate: function(e) {
			var alpha = (e.which !=8 && e.which !=0 && (e.which < 48 || e.which > 57));
			return !alpha;
		}
	},
	
	/*
	 * Prevent form submissions unless all fields have a value
	 */
	formErrors: {
		init: function() {
			var $forms = $('form:not([target^="solution"])');
			$forms.live('submit', this.checkAll);
			$forms.find('.required').live('keyup', this.check);
		},
		
		checkAll: function() {

			$(this).children('.error.message').remove();
			$(this).find('.required').trigger('keyup').filter('.error_field:first').focus();
			var errorMsg = '';
			var phoneLen =  $("#edit-submitted-phone-number").val().length;
			var nameLen =  $("#edit-submitted-name").val().length;

			var errorOccurred = $(this).find('.error_field').length;
			if (errorOccurred) {
				$(this).prepend($('<p/>', {text:'Please complete the highlighted fields...',className:'error message'}));
			} else {
				$(this).children('.error.message').remove();
			}

			if( nameLen < 4 ){ // Names to be at least 4 characters long
				$("#edit-submitted-name").addClass('error_field');
				errorOccurred = 1;
				errorMsg = "Enter your foremane and surname\n";
			}

			if( phoneLen <= 10 || phoneLen > 11 ){ // UK phone number is 10 or 11 characters
				$("#edit-submitted-phone-number").addClass('error_field');
				errorOccurred = 1;
				errorMsg += "Phone Numbers must be 10 or 11 Digits\n"; 
			}
/* XXXXXXXXXXXX 
			if( $("#edit-submitted-email").val() != '' && $("#edit-submitted-email").val() != 'Your E-mail Address' ){
				if( $("#edit-submitted-email").val().indexOf('@') == -1 || $("#edit-submitted-email").val().indexOf('.') == -1 ){
					$("#edit-submitted-email").addClass('error_field')
					errorOccurred = 1;
					errorMsg += "Please enter a valid email address\n";
				}
			}
*/
			if( errorMsg != '' ){
				//alert( 'Please Correct the Following Information\n\n' + errorMsg );
			}

			return !errorOccurred;
		},
		
		check: function() {

			var error = (
				( $(this).hasClass('required') && !$(this).val() ) ||
				( $(this).data('initial_value') == $(this).val() )
			);
		
			if (error) {
				$(this).addClass('error_field');
			} else {
				$(this).removeClass('error_field');
			}
		}
	}


};


$(document).ready(function() {
	$(".number_format").keydown(function(event)
	{
		if ( event.keyCode == 46 || event.keyCode == 8 ) 
		{
		} 
		else 
		{
			if (event.keyCode < 95) 
			{
				if (event.keyCode < 48 || event.keyCode > 57 )
				{
					event.preventDefault();
				}
			} 
			else
			{
				if (event.keyCode < 96 || event.keyCode > 105 ) 
				{
					event.preventDefault();
				}
			}
		}
	}); 
});


function openit() {
newWindow = window.open('http://www.harringtonbrooks.co.uk/privacy-policy.html','Privacy_Policy','width=630,height=500,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1'); 
return false;
}

function popUp(URL) {
  day = new Date();
  id = day.getTime();
  eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=630,height=500');");
  }


function showdiv(name){

if (document.getElementById(name)){
var obj = document.getElementById(name)
}

if (obj.style.display=="none"){
obj.style.display="";



document.getElementById("faq-" + name).style.backgroundImage = "url(/themes/harringtonbrooks/img/hide.png)"


}else{
obj.style.display="none";

document.getElementById("faq-" + name).style.backgroundImage = "url(/themes/harringtonbrooks/img/show.png)"
}
}

function hidediv(name){
var obj = (document.getElementById)? document.getElementById(name) : eval("document.all[name]");
obj.style.display="none";
}
