$(function(){
	
	$( ".datepicker" ).datepicker( { dateFormat: 'dd-mm-yy' } );
	
	$('#noOfItems').live('change', function(){
		if ( $(this).val() == 'custom' ){
			$(this).replaceWith('<input type="text" name="noOfItems" id="noOfItems" class="txtInput" />');
			$('#noOfItems').focus();
		}
	});

	$('#quote_form').submit(function(){
		if ( $('#noOfItems').val() == '' ){
			alert('Please provide No of items');
			$('#noOfItems').focus();
			return false;
		}else if ( isNaN($('#noOfItems').val()) ){
			alert('Please enter numeric value');
			$('#noOfItems').focus();
			return false;
		}else if ( $('#county').val() == '' ){
			alert('Please select your county');
			$('#county').focus();
			return false;
		}else{
			$('#quote_text').html('Please wait...<br /><br />');

			$.ajax({
				url: base_url + "quote/get_quote",
				type: "post",
				data: $('#quote_form').serializeArray(),
				success: function(msg){
					$('#quote_text').html(msg);
				}
			});
		}
		return false;
	});
	
	$('#download_form').submit(function(){
		
		if ( $('#download_name').val() == '' ){
			alert('Please enter your name');
			$('#download_name').focus();
			return false;
		}else if ( $('#download_email').val() == '' ){
			alert('Please enter your email address');
			$('#download_email').focus();
			return false;
		}else if ( echeck($('#download_email').val()) == false ){
			alert('Please enter a valid email address');
			$('#download_email').focus();
			return false;
		}else if ( $('#download_phone').val() == '' ){
			alert('Please enter your phone number');
			$('#download_phone').focus();
			return false;
		}else if ( !/^[0-9 ]+$/.test( $('#download_phone').val() ) ){
			alert('Please enter a valid phone number');
			$('#download_phone').focus();
			return false;
		}
		return true;
	});
});

function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}

	if (str.indexOf(at,(lat+1))!=-1){
		return false
	}

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	}

	if (str.indexOf(dot,(lat+2))==-1){
		return false
	}

	if (str.indexOf(" ")!=-1){
		return false
	}

	return true
}
