
// word limit
var WordLimit = function(options) {

	this.field = $('#' + options.textarea);
	this.limit = options.limit ? options.limit : 100;
	this.callback = options.callback ? options.callback : null ;

	// binding
	var that = this;
	
	// events
	this.field.bind('keyup', function() {
		that.check();
	});

	this.check = function() {
		var v = this.field.val();
		v.replace(/\s+/g, ' ');
		var words = v.split(' ');
		var remaining = words.length > this.limit ? 0 : this.limit - words.length;
		if(words.length > this.limit) {
			var max = words.slice(0, this.limit);
			this.field.val(max.join(' '));
		}
		if(this.callback) {
			this.callback(this.limit, remaining);
		}
	};

};


// default form field values
var d = {
	// <input id='<KEY>'
	'name_expert': 'Enter Name of Expert...',
	'area_expert': 'e.g. Accountants, Solicitors',
	'location_expert': 'e.g. UK, town, postcode',
	'sub_name': 'Your Name...',
	'sub_email': 'Your Email Address...'
};

// wait till document is ready
$(document).ready(function() {

	/*
	 * Default form values
	 */

	for(var k in d) {
		// set defaults
		if($('#' + k).val() == '') { $('#' + k).val(d[k]); }
		// apply event to fields
		$('#' + k).bind('focus', function() { if($(this).val() == d[$(this).attr('id')]) { $(this).val(''); }});
		$('#' + k).bind('blur', function() { if($(this).val() == '') { $(this).val(d[$(this).attr('id')]); }});
	}

	// clear forms of default vales on submit
	$('form').submit(function() {
		var inputs = $(this).find('input');
		for(var i = 0; i < inputs.length; i++) {
			var input = inputs[i];
			if(d[input.id]) {
				if(input.value == d[input.id]) {
					input.value = '';
				}
			}
		}
		return true;
	});

	/*
	 * Form toggles
	 */

	// toggler for form sections
	$('.form_section').css('display', 'none');

	// open first 
	$('.form_section:first').css('display', 'block');

	// apply clicks
	$("a[href^='#'][href$='details']").click(function() {

		var k = $(this).attr('href');
		var d = $(k);

		if(d.css('display') == 'block') {
			return false;
		}

		// reset other class
		$('.link2').attr('class', 'link1');

		var p = $(this).parent();
		p.attr('class', 'link2');

		$('.form_section').css('display', 'none');
		d.css('display', 'block');

		return false;
	});

	// toggler for form sections
	$('p[id^=ref]').css('display', 'none');

	// open first
	$('p[id^=ref]:first').css('display', 'block').attr('class', 'link2');

	// apply clicks
	$("a[href^='#ref']").click(function() {
		var k = $(this).attr('href');
		$(k).css('display', 'block');

		var p = $(this).parent();
		p.attr('class', 'link2');
		
		return false;
	});

	/*
	 * External links
	 */
	var host = window.location.host.toLowerCase();
	$("a[href^='http:']").not("[href*='"+host+"']").attr('target','_blank');

});