$(document).ready(function() { 
    
    popupLoginForm();
    //processLoginForm();
    
    manualForm();
    updateParts();
    updatePartsOther();
    processPartsForm();
    datePicker();
    
    searchDateDropdown();
    
    addressLookup();
    
});

function addressLookup(){
	$("a#postcodesearch").livequery('click', function (){
		fetchAddress();
		return false;
	});
	$('input[name=postcode]').keypress(function (e) {
		if(e.which == 13){
			fetchAddress();
			return false;
		}
	});
}

function fetchAddress(){
	var postcode = $('input[name=postcode]').val();
	$.get("/ajax.php", {type:'addresslookup', postcode: postcode},
		function(data){
			$("li#addressid").remove();
			$("li#postcode").after('<li id="addressid"><label for="addressid">Address</label><span class="input">' + data + '</span></li>');
		}
	);
}

function manualForm(){
	$("#manualForm select.make").livequery('change', function (){
		updateModel(this);
		updateYear(this);
		updateBody(this);
		updateTrim(this);
	});
	$("#manualForm select.model").livequery('change', function (){
		updateYear(this);
		updateBody(this);
		updateTrim(this);
	});
	$("#manualForm select.year").livequery('change', function (){
		updateBody(this);
		updateTrim(this);
	});
	$("#manualForm select.body").livequery('change', function (){
		updateTrim(this);
	});
}

function updateModel(parentid){
	$.get("/ajax.php", {type:'manualform', name: 'model', parentid: parentid.value},
		function(data){
			$('#manualForm select.model').replaceWith(data);
		}
	);
}

function updateYear(parentid){
	$.get("/ajax.php", {type:'manualform', name: 'year', parentid: parentid.value},
		function(data){
			$('#manualForm select.year').replaceWith(data);
		}
	);
}

function updateBody(parentid){
	$.get("/ajax.php", {type:'manualform', name: 'body', parentid: parentid.value},
		function(data){
			$('#manualForm select.body').replaceWith(data);
		}
	);
}

function updateTrim(parentid){
	$.get("/ajax.php", {type:'manualform', name: 'trim', parentid: parentid.value},
		function(data){
			$('#manualForm select.trim').replaceWith(data);
		}
	);
}

function updateParts(){
	$("#partsForm select.categoryid").livequery('change', function (){
		$.get("/ajax.php", {type:'partsform', parentid: this.value},
			function(data){
				$('#partsForm select.partid').replaceWith(data);
			}
		);
	});
}

function updatePartsOther(){
	$("#partsForm select.partid").livequery('change', function (){
		if(this.value == 'otherselector'){
			$.get("/ajax.php", {type:'partsform', parentid: this.value, other: true},
				function(data){
					$('#partsForm ul li:last-child').before(data);
				}
			);
		}
	});
}

function processPartsForm(){
	$('#partsForm').livequery('submit', function(){
		var error = false;
		var categoryid = $('select[@name=categoryid]').val();
		var partid = $('select[@name=partid]').val();
		var other = $('input[@name=other]').val();
		var regex = /^(\d+)$/;
		var msg = '';
		if((!regex.exec(categoryid)) && (partid != 'otherselector') && (!regex.exec(partid))){ //validate partid and categoryid
			error = true;
			msg = '<li>Please select from the list provided.</li>';
		}
		if(partid == 'otherselector'){
			var whitespace = /^(\s+)$/;
			var range = /^(.{3,254})$/;
			if(whitespace.exec(other) || !range.exec(other)){
				error = true;
				msg += '<li>Please input details of your required part.</li>';
			}
		}
		if(error == true){
			//display error message
			$('#errors').remove();
			$('#partsForm').prepend('<ul id="errors">' + msg + '</ul>'); //display error message
			return false;
		}
	});
}

function updateMainMenu(){
	$('#nav').load('/ajax.php?type=menu');
}

function popupLoginForm(){
	var init = function() {
		$(this).toggle(function(e) {
			$.get("/ajax.php", {type:'loginform'},
				function(data){
					$('#nav ul li.login').after(data);
				}
			);
		}, function(e) {
			$('#nav ul li.loginform').remove();
		});
	};
	var destroy = function() {
		$(this).unbind('toggle').unbind('click');
	};
	$("#loginbutton").livequery(init, destroy);
}

function loadLoginForm(){
	$('#loginBar').load('/ajax.php?type=loginform');
}

function processLoginForm(){
	$('form#login').livequery('submit', function(){
		var error = false;
		var email = $('#login_email').val();
		var password = $('#login_password').val();
		var rememberme = $('#login_rememberme').val();
		var msg;
		var temp;
		
		//validate email
		var regex = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+$/;
		if(!regex.exec(email)){
			msg = '<li>Please input a valid email address.</li>';
			error = true;
		}
		
		//validate password
		var regex = /^[a-zA-Z0-9]{6,18}$/;
		if(!regex.exec(password)){
			msg = msg + '<li>Passwords must be Alpha Numeric and between 6 and 18 characters in length.</li>';
			error = true;
		}
		
		if(error == true){
			//validation failed, echo out error message
			$('#loginOutput').replaceWith('<ul id="errors">' + msg + '</ul>');
		} else {
			//validated successfully, log them in
			$.get("/ajax.php", {type:'newlogin', email: email, password: password, rememberme: rememberme},
				function(data){
					var regex = /^success$/;
					if(regex.exec(data)){
						$("#loginBar").slideUp("slow");
						updateMainMenu();
						if(window.location == 'http://www.sparesnetwork.co.uk/requestquotes/register/') window.location = 'http://www.sparesnetwork.co.uk/requestquotes/confirm/'; //if the login form is on submission page, it needs to redirect somewhere
    				} else {
    					//validation failed, echo out error message
						$('#loginOutput').replaceWith(data);
    				}
				}
			);
		}
		return false;
	});
}

function datePicker(){
	$('li.datepicker input').datepicker({
		firstDay: 1,
		dateFormat: 'dd/mm/yy'
	});
}

function dateRangePicker(){
	$('li.daterangepicker input').datepicker({
		rangeSelect: true, 
		firstDay: 1,
		dateFormat: 'dd/mm/yy'
	});
}

function searchDateDropdown(){
	$('select[name="iscompleted"]').livequery('change', function(){
		if(this.value == 'yes'){
			$('li.completeddate').slideDown();
		} else {
			$('li.completeddate').slideUp();
		}
	});
	$('select[name="iscancelled"]').livequery('change', function(){
		if(this.value == 'yes'){
			$('li.cancelleddate').slideDown();
		} else {
			$('li.cancelleddate').slideUp();
		}
	});
	$('select[name="isquoted"]').livequery('change', function(){
		if(this.value == 'yes'){
			$('li.quoteddate').slideDown();
		} else {
			$('li.quoteddate').slideUp();
		}
	});
	
	
	/*
	$('li.iscancelled select').livequery('change', function(){
		if(this.value == 'yes'){
			$('li.cancelleddate').css("display", "block");
		} else {
			$('li.cancelleddate').css("display", "none");
		}
	});*/
}