/* 
	Title:		Gumtree Category Selection Fucntions
	Copyright:	2009-2010 Gumtree.com
	Date:		19 Jan 2010
	Authors:	Antonio Lulic/Adam Perfect
	Email:		anlulic@gumtree.com
*/

// 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', '0 0 10px 0');
	DD_roundies.addRule('div#choose-category-intro', '10px 10px 0 0');
	DD_roundies.addRule('ul#categories', '0 0 0 10px');
}

function resetSubmitRoundies() {
    if (ie.DocMode < 8) {
        var continueDiv = $('div#submit');
        var continueButton = $('form#post-ad-form input.submit');
    	var continueButtonP = $('form#post-ad-form p.submit');
    	
    	// Only reset the roundies if needed
    	if ((continueDiv.hasClass('ready') && buttonReady == false) || (!continueDiv.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;
    		}
    	}
    }
}
	
// 'el' is the link that's been clicked on
function toggleCatLink(el) { 
    var id = el.attr('href'); // id is the id of the target ul
    // Close down the inappropriate lists
    if (($(id).hasClass('level-two')) || (el.hasClass('final-level') && el.parents('ul').hasClass('level-one'))) {
        $('ul.level-one li.active, ul.level-two, ul.level-two li.active, ul.level-three, ul.level-three li.active, ul.level-four, ul.level-four li.active, ul.level-five, ul.level-five li.active').removeClass('active');
    }
    if (($(id).hasClass('level-three')) || (el.hasClass('final-level') && el.parents('ul').hasClass('level-two'))) {
        $('ul.level-two li.active, ul.level-three, ul.level-three li.active, ul.level-four, ul.level-four li.active, ul.level-five, ul.level-five li.active').removeClass('active');
    }
    if (($(id).hasClass('level-four')) || (el.hasClass('final-level') && el.parents('ul').hasClass('level-three'))) {
        $('ul.level-three li.active, ul.level-four, ul.level-four li.active, ul.level-five, ul.level-five li.active').removeClass('active');
    }
    if (($(id).hasClass('level-five')) || el.hasClass('final-level') && el.parents('ul').hasClass('level-four')) {
        $('ul.level-four li.active, ul.level-five, ul.level-five li.active').removeClass('active');
    }
    if (el.hasClass('final-level') && el.parents('ul').hasClass('level-five')) {
        $('ul.level-five li.active').removeClass('active');
    }
    // Slide the cats left if we need to make room        
    if ($(id).hasClass('level-five') || el.closest('ul').hasClass('level-five')) {
        $('#categories').css({marginLeft:'-201px'});
    } else {
        $('#categories').css({marginLeft:'0'});
    }
    // Open out the appropriate list
    $(id).addClass('active');
    // Toggle the link's active state
    el.parent('li').toggleClass('active');
    // Hide irrelevant category name note
	$('ul#category-notes li.active').removeClass('active');
    // If it's a leaf category...
	if (el.hasClass('final-level')) {
        // Put the category number in the appropriate form field, enable the continue button, show the category name next to it
		var catNum = /\d+/.exec(el.attr('href'));
		$('span#cat-name').text(el.text());
		$('form#post-ad-form input#post-ad-cat').val(catNum);
		$('form#post-ad-form input.submit').removeClass('disabled');
		$('form#post-ad-form div#submit').removeClass('warning').addClass('ready');
        resetSubmitRoundies();
	} else {
	   // Remove the category number from the form field, disable the continue button, hide the category name next to it
		$('form#post-ad-form input#post-ad-cat').val('');
		$('form#post-ad-form input.submit').addClass('disabled');
		$('form#post-ad-form div#submit').removeClass('ready');
        resetSubmitRoundies();
	}
}

var preselectedCats = new Array();

function preselectCats() {
    for ( var i=preselectedCats.length-1;i>=0;--i ){
        toggleCatLink(preselectedCats[i]);
    }
}

function gatherPreselectCats(currentCatLink) {
    var currentCatLinkEl = $('a[href="#' + currentCatLink + '"]');
    var nextCatLink = currentCatLinkEl.closest('ul').attr('id');

    preselectedCats.push(currentCatLinkEl);

    if ( $('a[href="#' + nextCatLink + '"]').length > 0 ) {
        gatherPreselectCats(nextCatLink);
    } else {
        preselectCats();
    }
}

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

// After the DOM has loaded
$(document).ready( function() {

    // category links
    var isAgent = $('input#is-agent').val();
    $('div#submit.agent input.submit').live('click', function(e) {
        e.preventDefault();
        window.location = 'http://www.zoopla.co.uk/agents/join/';
    });
	$('a[href^="#cat-"], a[href="#rentals-choice"], a[href="#jobs-choice"], a[href="#uk-property-choice"]').click(function() {
		toggleCatLink($(this));
		if ($(this).hasClass('is-agent')) {
            $('input#is-agent').val('1');
			$('div#submit').addClass('agent');
        } else {
            $('input#is-agent').val(isAgent);
			$('div#submit').removeClass('agent');
        }
	});
	// help link
	$('li.category-help a').click(function() {
		return true;
	});
	
	$('#post-ad-form input.submit').click(function(e){
		if ($(this).hasClass('disabled')) {
			e.preventDefault();
			$('div#submit').removeClass('ready').addClass('warning');
		}
	});

    gatherPreselectCats(document.location.toString().split('#')[1]);

});
/* 
	Title:		Gumtree Post an Ad Actions and Settings
	Copyright:	2008-2009 Gumtree.com
	Date:		11 May 2009
	Authors:	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 - New 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 - Old password is valid when entered
function validateOldPassword(element) {
	if (element.val().length == 0) {
		element.closest('li')
			.removeClass('valid')
			.removeClass('error');
	} else {
		element.closest('li')
			.removeClass('error')
			.removeClass('valid');
	}
}

// Validation - Changed passwords need to match
function validateChangePassword(element) {
	if (element.val().length == 0) {
		element.closest('li')
			.removeClass('valid')
			.removeClass('error');
	} else if (element.val() != $('input#password-new-confirm').val() && $('input#password-new-confirm').val().length != 0) {
		$('input#password-new-confirm').closest('li')
			.removeClass('valid')
			.addClass('error');
	} else if (element.val() == $('input#password-new-confirm').val()) {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
		$('input#password-new-confirm').closest('li')
			.removeClass('error')
			.addClass('valid');
	} else if ($('input#password-new-confirm').val().length == 0) {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
	}
}
function validateChangeConfirmPassword(element) {
	if (element.val().length == 0) {
		element.closest('li')
			.removeClass('valid')
			.removeClass('error');
	} else if (element.val() != $('input#password-new').val()) {
		element.closest('li')
			.removeClass('valid')
			.addClass('error');
	} else if (element.val() == $('input#password-new').val()) {
		element.closest('li')
			.removeClass('error')
			.addClass('valid');
		$('input#password-new').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 && $('input#use-contact-email').attr('checked') == true) {
			$('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');	
	}
}

// Validation - Check if Response Manager or Contact Email checkboxes are checked
function validateContactMethod(element) {
	if ($('input#appvault').attr('checked') == true || $('input#use-contact-email').attr('checked') == true ) { 
        if ($('input#contact-email').val().length > 0) {
            element.closest('li')
    			.removeClass('error')
    			.addClass('valid');
    	} else {
    		element.closest('li')
        		.addClass('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');
	$('#password-buttons').removeClass('hidden');
	$('input#cancel-password-change, .change-password-field').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 (ie.DocMode < 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 (ie.DocMode < 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 (ie.DocMode < 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#password-new').each(function(){
		if($(this).val() != '') {
			validateChangePassword($(this));
		}
	});
	$('input#password-new-confirm').each(function(){
		if($(this).val() != '') {
			validateChangeConfirmPassword($(this));
		}
	});
	$('li.change-password-field.error, li.change-password-field.valid').each(function(){
		$('li.change-password-field, li.change-password-field.valid, li.change-password-field.error, input#cancel-password-change').removeClass('hidden');
		$('input#password-change').addClass('hidden');
		reStripeFields();
	});
	$('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#password-old').blur(function(){
		validateOldPassword($(this));
	});
	$('input#password-new').blur(function(){
		validateChangePassword($(this));
	});
	$('input#password-new-confirm').blur(function(){
		validateChangeConfirmPassword($(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));
	});
	$('input#appvault, input#use-contact-email').click(function(){
		validateContactMethod($(this));
	});
	$('input#contact-email').blur(function(){
		validateContactMethod($(this));
	});

    // Response Manager

	$('input#appvault').click(function() {
		if ($(this).attr('checked') == true) {

            // turn off contact phone
			$('#contact-phone').val('');
			$('div.contact-phone').addClass('hidden');
			$('label[for="contact-phone"].example').addClass('hidden');
            $('input#use-contact-phone').removeAttr('checked');

            // turn off contact email
            $('input#use-contact-email').removeAttr('checked');
            
            // copy user email to contact email
			$('input#contact-email').val($('input#user-email').val());

			// move contact email to response manager
			$('div.contact-email').appendTo('#appvault-description').removeClass('hidden');
			if ($('input#contact-email').val().length == 0) {
				$('label[for="contact-email"].example').removeClass('hidden');
			} else {
				$('label[for="contact-email"].example').addClass('hidden');			
			}

            // remove error
			$(this).closest('li').removeClass('error');

        } else {

			$('div.contact-email').addClass('hidden');
			$('input#contact-email').val('');
			$('label[for="contact-email"].example').addClass('hidden');

        }
	});

	//  Show/hide and fill/empty preferred email address field
	$('input#use-contact-email').click(function() {
		if ($(this).attr('checked') == true) {

            // turn off appvault
			if ($('input#appvault').attr('checked') == true) {
                $('input#appvault').removeAttr('checked');
    			// move contact email to this section
            }

            // copy user email to contact email
			$('input#contact-email').val($('input#user-email').val());

            // show the field
			$('div.contact-email').removeClass('hidden');

			$('div.contact-email').insertAfter('label[for="use-contact-email"]');
			if ($('input#contact-email').val().length == 0) {
				$('label[for="contact-email"].example').removeClass('hidden');
			} else {
				$('label[for="contact-email"].example').addClass('hidden');			
			}

            // remove error
			$(this).closest('li').removeClass('error');

		} else {

            // If there's nothing in the field, show the example
			$('input#contact-email').val('');
			$('div.contact-email').addClass('hidden');
			$('label[for="contact-email"].example').addClass('hidden');

		}
	});

	// Show/hide and fill/empty preferred name and phone field
	$('input#use-contact-phone').click(function() {
		if ($(this).attr('checked') == true) {

            // Prefill the field if we have a first name and phone number
			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);

            // Show the field
			$('div.contact-phone').removeClass('hidden');

            // If there's nothing in the field, show the example
			if ($('input#contact-phone').val().length == 0) {
				$('label[for="contact-phone"].example').removeClass('hidden');
			} else {
				$('label[for="contact-phone"].example').addClass('hidden');			
			}

            // Round the field corners
			if (ie.DocMode < 8) {
				DD_roundies.addRule('input#contact-phone');
			}

            // turn off appvault
			if ($('input#appvault').attr('checked') == true) {
                $('input#appvault').removeAttr('checked');
    			$('input#contact-email').val('');
    			$('div.contact-email').addClass('hidden');
    			$('label[for="contact-email"].example').addClass('hidden');
			}

            // remove error
			$(this).closest('li').removeClass('error');	

		} else {
			$('#contact-phone').val('');
			$('div.contact-phone').addClass('hidden');
			$('label[for="contact-phone"].example').addClass('hidden');
		}
	});
	
	// Re-enable Contact Email and Phone fields if there is data in them
	if ($('input#appvault').attr('checked') == true) {
		$('div.contact-email').appendTo('#appvault-description').removeClass('hidden');
		if ($('input#contact-email').val().length == 0) {
			$('label[for="contact-email"].example').removeClass('hidden');
			$(this).closest('li')
				.removeClass('valid')
				.addClass('error');
		}
	} else {
    	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');
		}
	});
	
	// Check or uncheck 'Select all' promo option checkbox when promo options are 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').change(function(){
		$('td.price span').hide();
		$('td.price span.days-' + $(this).val()).show();
	});
	
	// Enable 'Change Password' button
	$('input#password-change').click(function(e){
		e.preventDefault();
		$('.change-password-field, input#cancel-password-change').removeClass('hidden');
		$('input#password-change').addClass('hidden');
		reStripeFields();
	});
	// Enable 'Cancel Password Change' button
	$('input#cancel-password-change').click(function(e){
		e.preventDefault();
		$('.change-password-field, input#cancel-password-change').addClass('hidden');
		$('input#password-change').removeClass('hidden');
		$('.change-password-field input').val('');
		$('input#password-old, input#password-new, input#password-new-confirm').closest('li')
			.removeClass('error')
			.removeClass('valid');
		reStripeFields();
	});
});
// 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');
	}
}