/* 
	Title:		Gumtree Category Selection Fucntions
	Copyright:	2009 Gumtree.com
	Date:		11 May 2009
	Authors:	Adam Perfect/Antonio Lulic
	Email:		aperfect@gumtree.com
*/

// track status of continue button to avoid re-loading Roundies unnecessarily in IE
var buttonReady = false;

// IE6/7 Rounded Corners (Search box, Headings, Main action links, boxouts)
if (ie.DocMode < 8) {
	DD_roundies.addRule('h2.main', '10px');
	DD_roundies.addRule('form#post-ad-form input.submit', '4px');
	DD_roundies.addRule('form#post-ad-form p.submit', '5px');
	DD_roundies.addRule('div#rental-offered-type', '10px');
	DD_roundies.addRule('div#rental-offered-type h3', '10px 10px 0 0');
	DD_roundies.addRule('div#rental-offered-type div.close','0');
// following line commented out - not sure which corners it applies to - but it breaks ie6/7
//	DD_roundies.addRule('div#rental-offered-type p.note, li.category-help');
}

// After the DOM has loaded
$(document).ready( function() {
	
	$("#choose-category li a").click(function(){
	
		// rental property offered London - show popup
		var hrefCatIdMatch = $(this).attr('href').match(/#cat-([0-9]+)/);
		if( hrefCatIdMatch && $('div.popup-for-'+hrefCatIdMatch[1]).length > 0 ) {
			showOverlay('popup-for-'+hrefCatIdMatch[1]);
		}
		// rental property offered London none-private Landlord
		else if ($(this).attr('id') != 'rental-private-landlord' && $(this).parents('div#rental-offered-type').length > 0) {
			return true;
		}
		// help link
		else if ($(this).parents('li').hasClass('category-help')) {
			return true;
		}
		// jobs link
		else if ($(this).attr('href') == '#jobs-choice') {
			toggleCatLink($(this));
			return false;
		}
		else {
			if ($('#rental-offered-type').hasClass('show') ||
			    $('#jobs-type').hasClass('show')) {
				$('#rental-offered-type').removeClass('show');
				$('#jobs-type').removeClass('show');
				resetRoundies();
			}
			toggleCatLink($(this));
		}
		
		// reCalcBreadcrumb();
		
		return false;
	});
	
	$('#post-ad-form input.submit').click(function(){
		if ($(this).hasClass('disabled')) {
			$(this).parents('div#submit').toggleClass('warning');
			return false;
		}
	});
	
	$('#rental-private-landlord').click(function(){
		toggleCatLink($('a[href="#cat-2511"]'));
	});
	$('#job-offer').click(function(){
		toggleCatLink($('a[href="#cat-2553"]'));
	});
	$('#job-wanted').click(function(){
		if( !$('a[href="#cat-2553"]').parent('li').hasClass('active') ) {
			toggleCatLink($('a[href="#cat-2553"]'));
		}
		var catList = document.getElementById("cat-2553");
		catList.scrollTop = catList.scrollHeight;

		toggleCatLink($('a[href="#cat-2541"]'));
	});


	$('div.category-popup div.close a').click(function(){
		$('div#rental-offered-type').removeClass('show');
		$('#jobs-type').removeClass('show');
		resetRoundies();
		return false;
	});
	
});

function showOverlay(catIdClass) {
	$('div.'+catIdClass).addClass('show');
	if ($.browser.msie && $.browser.version < 8) {
		$('#choose-category ignore').show();
	}
	
}

function resetRoundies() {
	if ($.browser.msie && $.browser.version < 8) {
		$('#choose-category ignore').hide();
	}
}

// recursive fun!
function toggleCatChildClass(el, className) {
	el.toggleClass(className);
	
	var targetUl = $(el.children('a').attr('href'));
	
	if (targetUl && targetUl.hasClass(className)) {
		//alert('Child UL is active, deactivate it');
		targetUl.toggleClass(className);
		var activeLi = targetUl.children('li.active')
		if (targetUl.children('li.active').length > 0) {
			toggleCatChildClass(activeLi, className);
		}
	}
	
}

function toggleCatLink(el) {
	if (el.parent('li').hasClass('active')) {
		// alert('Going to remove all active classes from this and children...');
		toggleCatChildClass(el.parent('li'), 'active');
		
		// make target note inactive
		$(el.attr('href').replace(/#cat/, '#note-cat')).toggleClass('active');
		
		var continueButton = $('form#post-ad-form input.submit');
		var continueButtonP = $('form#post-ad-form p.submit');
		// make sure form val is blank
		$('form#post-ad-form input#post-ad-cat').val('');
		
		// disable the button
		continueButton.addClass('disabled');
		// set paragraph class name
		continueButtonP.removeClass('ready');
			
		resetRoundies();
	}
	else {
		// traverse current UL and deactivate any activated LIs and their
		// children first
		// alert('Deactivate same-level LIs');
		el.parents('ul').children('li.active').each(function() {
			//alert('Deactivating LI');
			toggleCatChildClass($(this), 'active');
		});
		
		// make this li active
		el.parent('li').toggleClass('active');
		
		// make target ul active
		$('#category-notes li').removeClass('active');
		$(el.attr('href')).toggleClass('active');
		
		// make target note active
		if (el.attr('href') != '#jobs-choice') {
			$(el.attr('href').replace(/#cat/, '#note-cat')).toggleClass('active');
		}
		
		// make continue button active if end-of-line
		var continueButton = $('form#post-ad-form input.submit');
		var continueButtonP = $('form#post-ad-form p.submit');
		if (el.hasClass('final-level')) {
			// set the hidden field value
			var re = /\d+/;
			var catNum = re.exec(el.attr('href'));
			$('form#post-ad-form input#post-ad-cat').val(catNum);
			
			// enable the button
			continueButton.removeClass('disabled');
			// set paragraph class name
			continueButtonP.addClass('ready');
			$('form#post-ad-form div#submit').removeClass('warning');
			
			resetRoundies();
		}
		else {
			// make sure form val is blank
			$('form#post-ad-form input#post-ad-cat').val('');
			
			// disable the button
			continueButton.addClass('disabled');
			// set paragraph class name
			continueButtonP.removeClass('ready');
			
			resetRoundies();
		}
	}
}

function reCalcBreadcrumb () {
	// return to just the city element
	$('#breadcrumb li').each(function() {
		if ($(this).attr('id') != 'breadcrumb-city') {
			$(this).remove();
		}
	});
	
	var breadcrumbList = $('#breadcrumb');
	var activeLis = $('#choose-category ul[id!=category-notes] li.active');
	
	if (activeLis.length > 0) {
		activeLis.each(function(){
			breadcrumbList.append('<li>' + $(this).text() + '</li>');
		});
		$('#breadcrumb li:first').removeClass('selected');
	}
	
	// make sure the last one doesn't get a chevron
	$('#breadcrumb li:last').addClass('selected');
}

function resetRoundies() {
	if ($.browser.msie && $.browser.version < 8) {
		var continueButton = $('form#post-ad-form input.submit');
		var continueButtonP = $('form#post-ad-form p.submit');
		
		// Only reset the roundies if needed
		if ((continueButtonP.hasClass('ready') && buttonReady == false) || (!continueButtonP.hasClass('ready') && buttonReady == true)) {
			continueButton.css('behavior', '');
			continueButton.siblings('ignore').remove();
			continueButtonP.css('behavior', '');
			continueButtonP.siblings('ignore').remove();
			
			DD_roundies.addRule('form#post-ad-form input.submit', '4px');
			DD_roundies.addRule('form#post-ad-form p.submit', '5px');
			
			if (buttonReady) {
				buttonReady = false;
			}
			else {
				buttonReady = true;
			}
		}
	}
}
/* 
	Title:		Gumtree Post an Ad Actions and Settings
	Copyright:	2008-2009 Gumtree.com
	Date:		11 May 2009
	Authours:	Antonio Lulic/Adam Perfect/Desigan Chinniah
	Email:		anlulic@ebay.com
*/

// Rounded Corners
if (ie.DocMode < 8) {
	DD_roundies.addRule('span.button', '5px');
	DD_roundies.addRule('span.button input', '4px');
	DD_roundies.addRule('div#errors, div#main-content h1', '8px');
	DD_roundies.addRule('form#post-an-ad fieldset.actions', '0 0 8px 8px');
	DD_roundies.addRule('div.error div.content, div.help div.content, div.learn div.content', '4px');
	DD_roundies.addRule('form#post-an-ad', '10px');
	DD_roundies.addRule('form#post-an-ad h2.first', '8px 8px 0 0');
}

// Stripe form rows and apply tabindexes
function reStripeFields() {
	$('ul.striped').each(function(){
		$(this).children('li:visible').removeClass('even odd');
		$(this).children('li:visible:even').addClass('odd');
		$(this).children('li:visible:odd').addClass('even');
		$('input[type!="hidden"], select, textarea, button').each(function(i) {
			$(this).attr('tabindex',i + 1);
		});
	});
	$('table.hpi tr:odd').addClass('even');
	$('table.hpi tr:even').addClass('odd');
}

// Validation - Required text fields
function validateRequiredText(element) {
	if (element.val().length == 0) {
		element.closest('li')
			.removeClass('valid');
	} else {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
	}
}

// Validation - Required select fields
function validateRequiredSelect(element) {
	if (element.val() == 0) {
		element.closest('li')
			.removeClass('valid');
	} else {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
	}
}

// Validation - Rent and price fields should be numbers.
function validatePrice(element) {
	var price = element.val();
	if (!price.match(/^([0-9,]+|[0-9,]+\.[0-9]{1,2}|)$/)) {
		element.closest('li')
			.addClass('error')
			.removeClass('valid');
	} else if (element.val() == '') {
		element.closest('li')
			.removeClass('error')
			.removeClass('valid');
	} else {
		if ($('select#price-frequency').val()) {
			if ($('select#price-frequency').val() != 0) {
				element.closest('li')
					.removeClass('error')
					.addClass('valid');
			}
		} else {
			element.closest('li')
				.removeClass('error')
				.addClass('valid');
		}
	}
}

// Validation - Select week/month box
function validatePriceFrequency(element) {
	if (element.val() == 0) {
		element.closest('li')
			.removeClass('valid');
	} else if ($('input#price').val().length > 0) {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
	}
}

// Validation - Vehicle registration number must exist
function validateHPI(element) {
	if (element.val().length == 0) {
		element.closest('li')
			.removeClass('valid')
			.addClass('error')
			.append('<div class="error"><p>You did not provide a registration number.</p></div>');
		element.focus(function(){
			$(this).closest('li.error').children('div.error').css({display:'block'}).animate({opacity:'1'}, 100);
		});	
		element.blur(function(){
			$(this).closest('li.error').children('div.error').animate({opacity:'0'}, 200, function() {
				$(this).closest('li.error').children('div.error').css({display:'none'});
			});
		});
		element.focus();
		return false;
	} else {
		$(this).closest('li.error').children('div.error').animate({opacity:'0'}, 200, function() {
			element.closest('li').removeClass('error');
		});
		return true;
	}
}

// Validation - Mileage must be a whole number.
function validateMileage(element) {
	var price = element.val();
	if (element.val() == '') {
		element.closest('li')
			.removeClass('error')
			.removeClass('valid');
	} else if (!price.match(/^[0-9,]+$/)) {
		element.closest('li')
			.addClass('error')
			.removeClass('valid');
	} else {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
	}
}
	
// Validation - Postcode must be well-formed
function validatePostcode(element) {
	var postcode = element.val().replace(' ' ,'').toUpperCase();
	if (postcode.match(/(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[0-9][ABD-HJLNP-UW-Z]{2})/)) {
		element.val(element.val().toUpperCase());
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
	} else if (postcode == '') {
		element.closest('li')
			.removeClass('error')
			.removeClass('valid');
	} else {
		element.closest('li')
			.addClass('error')
			.removeClass('valid');
	}
}

// Validation - YouTube URL must be well-formed
function validateYouTubeURL(element) {
	if (element.val().match(/^http:\/\/www.youtube.com\/watch\?(.*)v=(.+)$/ig)) {
		element.closest('li')
			.addClass('valid')
			.removeClass('error');
	} else if (element.val() == '') {
		element.closest('li')				
			.removeClass('valid')
			.removeClass('error');
	} else {
		element.closest('li')				
			.removeClass('valid')
			.addClass('error');
	}
}

// Validation - Passwords need to match
function validateCreatePassword(element) {
	if (element.val().length == 0) {
		element.closest('li')
			.removeClass('valid');
	} else if (element.val() != $('input#confirm-password').val() && $('input#confirm-password').val().length != 0) {
		$('input#confirm-password').closest('li')
			.removeClass('valid')
			.addClass('error');
	} else if (element.val() == $('input#confirm-password').val()) {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
		$('input#confirm-password').closest('li')
			.removeClass('error')
			.addClass('valid');
	} else if ($('input#confirm-password').val().length == 0) {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
	}
}
function validateConfirmPassword(element) {
	if (element.val().length == 0) {
		element.closest('li')
			.removeClass('valid');
	} else if (element.val() != $('input#create-password').val()) {
		element.closest('li')
			.removeClass('valid')
			.addClass('error');
	} else if (element.val() == $('input#create-password').val()) {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
		$('input#create-password').closest('li')
			.removeClass('error')
			.addClass('valid');
	}
}

// Validation - Email address must be well-formed
function validateEmailAddress(element) {
	var emailAddress = element.val();
	if (emailAddress.match(/^[a-zA-Z0-9._%+!#$&'*\/=?^`{|}~-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
		if ($('input#contact-email').val().length == 0) {
			$('label[for="contact-email"].example').addClass('hidden');
			$('input#contact-email').val(element.val());
		}
	} else if (element.val() == '') {
		element.closest('li')
			.removeClass('error')
			.removeClass('valid');
	} else {
		element.closest('li')
			.addClass('error')
			.removeClass('valid');
	}
}

// Validation - If this isn't a valid UK mobile number, disable SMS updates
function validatePhoneNumber(element) {
	var phoneNumber =
		element.val()
			.replace(/ /g,'')
			.replace(/\(/g,'')
			.replace(/\)/g,'')
			.replace(/-/g,'');
	if (!phoneNumber.match(/^((00|\+)44|0)7\d{9}$/)) {
		$('input#sms').removeAttr('checked');
	}
}

// Validation - Check both name fields are filled
function validateNames(element) {
	if ($('input#first-name').val().length > 0 && $('input#last-name').val().length > 0) {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
	} else {
		element.closest('li')
			.removeClass('error')
			.removeClass('valid');	
	}
}

$(document).ready(function() {

	reStripeFields();

	// Support for Non-JS users
	$('label.example').removeClass('hidden');
	$('span#title-counter').removeClass('hidden');
	$('div.contact-method').addClass('hidden');

	// Prevent enter keypresses from submit the form unless posting HPI
	$('form.prevent-enter-key input').each(function(){
		$(this).keydown(function(event){
			var key = event.which;
			if (key == 13) {
				event.preventDefault();
				if ($(this).attr('id') == 'vehicle-registration') {
					$('input#hpi-lookup').click();
				}
			}
		});
	});

	// Have a counter that displays the number of characters in a text field and limit it to it's maxlength
	// To use, add a class of character-count to the field, and give it an id. Give an id of <id of field>-counter to whatever you want to display the count.
	$('.character-count').each(function(){
		var length = $(this).val().length;
		var max = $(this).attr('maxlength');
		var id = $(this).attr('id');
		var counter = '#' + id + '-counter';
		var remaining = max - length;
		var isCtrl = false;
		$(counter).html('<strong>' + remaining + '</strong> characters left');
		$(this).keydown(function(event){
			var key = event.which;
			
			if (key == 17 || key == 224 || event.ctrlKey) {
				isCtrl = true;
			}

			length = $(this).val().length;
			remaining = max - length;

			$(counter).html('<strong>' + remaining + '</strong> characters left');

			if (remaining < 50) {
				$(counter).removeClass('hidden');
			}
			if (remaining <= 0) {
				$(counter)
					.css({color:'#cc0000'})
					.animate({color:'#666666'}, 1000);
			}
			if(length >= max && (key >= 48 || key == 32 || key == 13) && (isCtrl == false || isCtrl == true && key == 86)) {
				event.preventDefault();
			}
		});
		$(this).keyup(function(event){
			var key = event.which;
			if (key == 17 || key == 224 || event.ctrlKey) {
				isCtrl = false;
			}
			length = $(this).val().length;
			remaining = max - length;
			$(counter).html('<strong>' + remaining + '</strong> characters left');
		});
	});
	
	// Enable HPI DatePicker
	$('input#hpi-date_first_reg').datepicker({dateFormat:'dd/mm/yy', showAnim:'fadeIn', firstDay: 1, hideIfNoPrevNext: true});
	
	// Show/hide field help text
	$('li input.text, li textarea').focus(function(){
		$(this).closest('li:not(.error)').children('div.help').css({display:'block'}).animate({opacity:'1'}, 100);
	});
	$('li input.text, li textarea').blur(function(){
		$(this).closest('li').children('div.help').animate({opacity:'0'}, 200, function() {
			$(this).closest('li').children('div.help').css({display:'none'});
		});
	});
	$('a[rel="learn"]').click(function(e){
		e.preventDefault();
		var learnBubble = $(this).closest('li').children('div.learn');
		$('div.learn:visible').animate({opacity:'0'}, 200, function() {
			$(this).css({display:'none'});
		});
		if (learnBubble.css('display') == 'block') {
			learnBubble.animate({opacity:'0'}, 200, function() {
				learnBubble.css({display:'none'});
			});
		} else {
			learnBubble.css({display:'block'}).animate({opacity:'1'}, 100);
		}
	});
	$('div.learn').click(function(e){
		e.preventDefault();
		$(this).animate({opacity:'0'}, 200, function() {
			$(this).css({display:'none'});
		});
	});

	// Show/hide field error text
	$('li.error input.text, li.error textarea').focus(function(){
		$(this).closest('li.error').children('div.error').css({display:'block'}).animate({opacity:'1'}, 100);
	});
	$('li.error input.text, li.error textarea').blur(function(){
		$(this).closest('li.error').children('div.error').animate({opacity:'0'}, 200, function() {
			$(this).closest('li.error').children('div.error').css({display:'none'});
		});
	});


	// Highlight the active form field
	$('li input.text, li input.checkbox, li input.radio, li textarea, li select')
		.focus(function(){
			$(this).closest('li').addClass('active');
		})
		.blur(function(){
			$(this).closest('li').removeClass('active');
		});
	
	// Clear examples if browsers have prefilled fields
	$('input[value!=].exampled').each(function() {
		var field = $(this).attr('id');
		var label = $('label[for=' + field + '].example');
		$(label).addClass('hidden');
	});
	
	// Clear exampled text field on focus, empty on blur (Also, clicking the example label focusses on the input)
	$('label.example').click(function(e){
		e.preventDefault();
		var field=$(this).attr('for');
		$('input#' + field).focus();
	});
	$('input.text.exampled').focus( function() {
		var field = $(this).attr('id');
		var label = $('label[for=' + field + '].example');
		if (!label.hasClass('hidden')) {
			$(label).addClass('hidden');
		}
	});
	$('input.text.exampled').blur( function() {
		var field = $(this).attr('id');
		var label = $('label[for=' + field + '].example');
		if ($(label).hasClass('hidden') && $(this).val() == '') {
			$(label).removeClass('hidden');
		}
	});
	
	$('a.change-city').click(function(e){
		e.preventDefault();
		if ($(this).closest('li').hasClass('active')) {
			$(this).closest('li').removeClass('active')
		} else {
			$(this).closest('li')
				.addClass('active')
				.append($('div#change-city'));
		}
	});
	$('p.close-overlay a').click(function(e){
		e.preventDefault();
		$(this).closest('li')
			.removeClass('active');
	});

	$('div#post-ad-feature-info h2 a.close-popup, a#featured-ad-learn-more').click(function(e) {
		e.preventDefault();
		$($(this).attr('href'))
			.toggle();
		if ($.browser.msie && $.browser.version < 8) {
			DD_roundies.addRule('div.featured-popup', '10px');
			DD_roundies.addRule('div.featured-popup h2', '8px 8px 0 0');
		}
	});

	$('div#homepage-feature-learn-more div.close a, a.homepage-feature-learn-more').click(function(e) {
		e.preventDefault();
		$($(this).attr('href'))
			.toggle();
		if ($.browser.msie && $.browser.version < 8) {
			DD_roundies.addRule('div#homepage-feature-learn-more', '10px');
			DD_roundies.addRule('div#homepage-feature-learn-more h3', '8px 8px 0 0');
		}
	});

	$('div#urgent-feature-learn-more h2 a.close-popup, a.urgent-feature-learn-more').click(function(e) {
		e.preventDefault();
		$($(this).attr('href'))
			.toggle();
		if ($.browser.msie && $.browser.version < 8) {
			DD_roundies.addRule('form#post-an-ad div.featured-popup', '10px');
			DD_roundies.addRule('form#post-an-ad div.featured-popup h2', '8px 8px 0 0');
		}
	});
	
	// 	Validation on load
	$('input.text.required, textarea.required').each(function(){
		if($(this).val() != '') {
			validateRequiredText($(this));
		}
	});
	$('select.required').each(function(){
		if($(this).val() != '0') {
			validateRequiredSelect($(this));
		}
	});
	$('input.radio.required').each(function(){
		if ($(this).attr('checked') == true) {
			$(this).closest('li').addClass('valid');
		}
	});
	$('input#price').each(function() {
		if($(this).val() != '') {
			validatePrice($(this));
		}
	});
	$('select#price-frequency').each(function() {
		if ($(this).val() != '0') {
			validatePriceFrequency($(this));
		}
	});
	$('input#postcode').each(function(){
		if($(this).val() != '') {
			validatePostcode($(this));
		}
	});
	$('input#hpi_mileage').each(function(){
		if($(this).val() != '') {
			validateMileage($(this));
		}
	});
	$('input#youtube-url').each(function(){
		if($(this).val() != '') {
			validateYouTubeURL($(this));
		}
	});
	$('input#create-password').each(function(){
		if($(this).val() != '') {
			validateCreatePassword($(this));
		}
	});
	$('input#confirm-password').each(function(){
		if($(this).val() != '') {
			validateConfirmPassword($(this));
		}
	});
	$('input#user-email, input#contact-email').each(function(){
		if($(this).val() != '') {
			validateEmailAddress($(this));
		}
	});
	$('input#user-phone, input#contact-phone').each(function(){
		if($(this).val() != '') {
			validatePhoneNumber($(this));
		}
	});
	$('input#first-name, input#last-name').each(function(){
		if($(this).val() != '') {
			validateNames($(this));
		}
	});

	// 	Validation on user interaction
	$('input.text.required, textarea.required').blur(function(){
		validateRequiredText($(this));
	});
	$('select.required').click(function(){
		validateRequiredSelect($(this));
	});
	$('input.radio.required').click(function(){
		$(this).closest('li').addClass('valid');
	});
	$('input#price').blur(function() {
		validatePrice($(this));
	});
	$('select#price-frequency').click(function() {
		validatePriceFrequency($(this));
	});
	$('input#hpi-lookup').click(function(){
		return validateHPI($('input#vehicle-registration'));
	});
	$('input#hpi_mileage').blur(function() {
		validateMileage($(this));
	});	
	$('input#postcode').blur(function(){
		validatePostcode($(this));
	});
	$('li.mandatory input#postcode').blur( function() {
		if($(this).val() == '') {
			$(this).closest('li')
				.addClass('error')
				.removeClass('valid');
		}
	});
	$('input#youtube-url').blur(function(){
		validateYouTubeURL($(this));
	});
	$('input#create-password').blur(function(){
		validateCreatePassword($(this));
	});
	$('input#confirm-password').blur(function(){
		validateConfirmPassword($(this));
	});
	$('input#user-email, input#contact-email').blur(function(){
		validateEmailAddress($(this));
	});
	$('input#user-phone, input#contact-phone').blur(function(){
		validatePhoneNumber($(this));
	});
	$('input#first-name, input#last-name').blur(function(){
		validateNames($(this));
	});

	//  Show/hide and fill/empty preferred email address field
	$('input#use-contact-email').click(function() {
		if ($(this).attr('checked') == true) {
			$('input#contact-email').val($('input#user-email').val())
			$('div.contact-email').removeClass('hidden');
			if ($('input#contact-email').val().length == 0) {
				$('label[for="contact-email"].example').removeClass('hidden');
			}
			$(this).closest('li').removeClass('error');			
		} else {
			$('input#contact-email').val('');
			$('div.contact-email').addClass('hidden');
			$('label[for="contact-email"].example').addClass('hidden');
			if ($('input#use-contact-phone').attr('checked') == false) {
				$(this).closest('li')
					.removeClass('valid')
					.removeClass('error');
			}
		}
	});

	// Show/hide and fill/empty preferred name and phone field
	$('input#use-contact-phone').click(function() {
		if ($(this).attr('checked') == true) {
			if ($('input#first-name').val().length > 0 && $('input#user-phone').val().length > 0) {
				var contactPhone = $('input#first-name').val() + ' on ' + $('input#user-phone').val();
			} else if ($('input#user-phone').val().length > 0) {
				var contactPhone = $('input#user-phone').val();			
			} else {
				var contactPhone = '';
			}
			$('#contact-phone').val(contactPhone);
			$('div.contact-phone').removeClass('hidden');
			if ($('input#contact-phone').val().length == 0) {
				$('label[for="contact-phone"].example').removeClass('hidden');
			} else {
				$('label[for="contact-phone"].example').addClass('hidden');			
			}
			$(this).closest('li').removeClass('error');
			if ($.browser.msie && $.browser.version < 7) {
				DD_roundies.addRule('input#contact-phone');
			}
		} else {
			$('#contact-phone').val('');
			$('div.contact-phone').addClass('hidden');
			$('label[for="contact-phone"].example').addClass('hidden');
			if ($('input#use-contact-email').attr('checked') == false) {
				$(this).closest('li')
					.removeClass('valid')
					.removeClass('error');
			}
		}
	});
	
	// Re-enable Contact Email and Phone fields if there is data in them
	if ($('input#use-contact-email').attr('checked') == true || $('input#contact-email').val() && $('input#contact-email').val().length > 0) {
		$('div.contact-email').removeClass('hidden');
		$('input#use-contact-email').attr('checked','checked');
		if ($('input#contact-email').val().length == 0) {
			$('label[for="contact-email"].example').removeClass('hidden');
			$(this).closest('li')
				.removeClass('valid')
				.addClass('error');
		}
	}
	if ($('input#use-contact-phone').attr('checked') == true || $('input#contact-phone').val() && $('input#contact-phone').val().length > 0) {
		$('div.contact-phone').removeClass('hidden');
		$('input#use-contact-phone').attr('checked','checked');
		if ($('input#contact-phone').val().length == 0) {
			$('label[for="contact-phone"].example').removeClass('hidden');
			$(this).closest('li')
				.removeClass('valid')
				.addClass('error');
		}
	}

	// Enable 'Select all' promo option checkboxen
	$('input#select-all-features').click(function() {
		if ($(this).attr('checked') == true) {
			$('input.feature').attr('checked','checked');
		} else {
			$('input.feature').removeAttr('checked');
		}
	});
	
	
	$('input.feature').click(function() {
		var allFeaturesSelected = true;
		$('input.feature').each(function() {
			if ($(this).attr('checked') == false) {
				allFeaturesSelected = false;
			}
		});
		if (allFeaturesSelected == true) {
			$('input#select-all-features').attr('checked','checked');
		} else {
			$('input#select-all-features').removeAttr('checked');
		}
	});
	
	// Enable 'Featured Ad' duration select box
	$('select.featured-duration').click(function(){
		$('td.price span').hide();
		$('td.price span.days-' + $(this).val()).show();
	});
});
// STYLING FILE INPUTS 1.0 | Shaun Inman <http://www.shauninman.com/> | 2007-09-07
if (!window.SI) { var SI = {}; };
SI.Files =
{
	htmlClass : 'SI-FILES-STYLIZED',
	fileClass : 'file',
	wrapClass : 'cabinet',
	
	fini : false,
	able : false,
	init : function()
	{
		this.fini = true;
		
		var ie = 0 //@cc_on + @_jscript_version
		if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) { return; } // no support for opacity or the DOM
		this.able = true;
		
		var html = document.getElementsByTagName('html')[0];
		html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
	},
	
	stylize : function(elem)
	{
		if (!this.fini) { this.init(); };
		if (!this.able) { return; };
		
		elem.parentNode.file = elem;
		elem.parentNode.onmousemove = function(e)
		{
			if (typeof e == 'undefined') e = window.event;
			if (typeof e.pageY == 'undefined' &&  typeof e.clientX == 'number' && document.documentElement)
			{
				e.pageX = e.clientX + document.documentElement.scrollLeft;
				e.pageY = e.clientY + document.documentElement.scrollTop;
			};

			var ox = oy = 0;
			var elem = this;
			if (elem.offsetParent)
			{
				ox = elem.offsetLeft;
				oy = elem.offsetTop;
				while (elem = elem.offsetParent)
				{
					ox += elem.offsetLeft;
					oy += elem.offsetTop;
				};
			};

			var x = e.pageX - ox;
			var y = e.pageY - oy;
			var w = this.file.offsetWidth;
			var h = this.file.offsetHeight;

			this.file.style.top		= y - (h / 2)  + 'px';
			this.file.style.left	= x - (w - 30) + 'px';
		};
	},
	
	stylizeById : function(id)
	{
		this.stylize(document.getElementById(id));
	},
	
	stylizeAll : function()
	{
		if (!this.fini) { this.init(); };
		if (!this.able) { return; };
		
		var inputs = document.getElementsByTagName('input');
		for (var i = 0; i < inputs.length; i++)
		{
			var input = inputs[i];
			if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1)
			{
				this.stylize(input);
			};
		};
	}
};/* 
	Title:		Gumtree Category Selection Fucntions
	Copyright:	2009 Gumtree.com
	Date:		7 May 2009
	Authors:	Adam Perfect, Antonio Lulic
	Email:		anlulic@ebay.com
*/

var overRotation = false;
	
if (ie.DocMode < 8) {
	DD_roundies.addRule('h2.main', '10px');
	DD_roundies.addRule('form#continue-form', '0 0 10px 10px');
	DD_roundies.addRule('div#images-learn-more', '10px');
	DD_roundies.addRule('div#images-learn-more h3', '10px 10px 0 0');
	DD_roundies.addRule('div#images-learn-more div.close');
	DD_roundies.addRule('div#overlay', '8px');
}

$(document).ready( function() {
	
	if ($('#add-another-picture').length > 0) {
		SI.Files.stylizeById('add-another-picture');
	}
	
	$('form#upload-image').appendTo('ol#images li.empty div#add-another-picture');
	$('form#upload-image').addClass('ready');

	$('#image-manager').addClass('have-js');
	
	$('ol#images li.image div.image').mouseenter(function() {
		$(this).next('div.rotation').addClass('show');
	})
	.mouseleave(function() {
		setTimeout('unShowRotation()', 250);
	});
	$('ol#images li.image div.rotation').mouseenter(function() {
		overRotation = true;
		$(this).next('div.rotation').addClass('show');
	})
	.mouseleave(function(){
		overRotation = false;
	});
	
	$('ol#images li.image div.image')
		.mouseenter(function() {
			$(this).next('div.rotation').addClass('show');
		})
		.mouseleave(function() {
			setTimeout('unShowRotation()', 250);
		});
	$('ol#images li.image div.rotation')
		.mouseenter(function() {
			overRotation = true;
			$(this).next('div.rotation').addClass('show');
		})
		.mouseleave(function(){
			overRotation = false;
		});

	$('input#file').change(function(){
		$('div#overlay')
			.height($('div#image-manager').height() + 20)
			.show();
		$('form#upload-image')[0].submit();
		$('form#upload-image').addClass('uploading');
	});
	
	$('h4.more-images a, #images-learn-more div.close a').click(function(){
		if ($('#images-learn-more').hasClass('show')) {
			hideTipsRoundies();
		}
		else {
			unHideTipsRoundies();
		}
		$('#images-learn-more').toggleClass('show');
		return false;
	});
	
	$('input[type="submit"]').click(function() {
		$('div#overlay')
			.height($('div#image-manager').height() + 20)
			.show();
	});
	
});

function hideTipsRoundies() {
	if ($.browser.msie && $.browser.version < 8) {
		$('#images-learn-more ignore').hide();
		$('#image-manager ol#images ~ ignore').hide();
	}
}
function unHideTipsRoundies() {
	if ($.browser.msie && $.browser.version < 8) {
		$('#images-learn-more ignore').show();
		$('#image-manager ol#images ~ ignore').show();
	}
}

function unShowRotation() {
	if (!overRotation) {
		$('div#image-manager.have-js ol#images li.image div.rotation').removeClass('show');
	}
}