$(document).ready( function() {
	
//	if($("#checktaken").attr('value') != null	)
//	{
//		alert("lol");
//		var checktaken = $("#checktaken").attr('value');			
//		$.ajax({
//			type: "POST",
//			url: "/callphp/",
//			data: {checktaken:checktaken},
//	  		async:true,
//		});
//	}
	
//old

 //if( $("#banner").length > 0)
 //if (getElementByID("#banner"))
// {
//	 alert("lol");
 //}





	$(".googlemap").each( function() {



		theaddress = $.trim($(this).attr('data-address'));



		$(this).gMap({ markers: [

			{ address: theaddress,

				html: "_address" }],

			address: theaddress,
		
			zoom: 14 });

	})


//new	
	$(".googlemap2").each( function() {
		
		
		thelat = $(this).attr('data-lat');
		thelon = $(this).attr('data-lon');

		$(this).gMap({ markers: [{
			latitude: thelat,
			longitude: thelon,
		}],
		zoom: 14 });

	})
	$(".googlemap4").each( function() {
		
		
		thelat = $(this).attr('data-lat');
		thelon = $(this).attr('data-lon');

		$(this).gMap({ markers: [{
			latitude: thelat,
			longitude: thelon,
		}],
		zoom: 14 });

	})

	var errormsg;


	// Test all functions on submit
	$("#ds-new-entry").submit( function() {

		var valid = true;

		$(".input-field").each( function () {

			if (!validateAll(this)) {

				valid = false;

			}

			finalValidate(this,validateAll(this));

		})

		

		return valid;

	});

	

	$("#deliverydate").datepicker({

		constrainInput: true, 

		dateFormat: 'dd/mm/yy', 

		yearRange: '2011:2050',

		onClose: function(dateText, inst) { finalValidate(this,validateAll(this)) }

	});

	

	function printmsg (field,flag) {

		if (flag){

			$(field).next().children().css('color', '#5FB946');

		} else {

			$(field).next().children().css('color', '#B94646');

		}

		$(field).next().children().text(errormsg).stop(true, true).show().fadeOut(3000);

	}

	$('.free-job-submit').click( function() {

		jobID = $(this).attr('value');

		$('#ds-current-entry-job-taken').val(jobID);

		$('#ds-new-entry').submit();

	});

	$('.available-job-submit').click( function() {

		jobID = $(this).attr('value');

		$('#ds-current-entry-job-taken').val(jobID);

		$('#ds-current-entry').submit();

	});
	
	$('.assign-job-submit').click( function() {

		jobID = $(this).attr('value');
		uniquename = "#usernameid"+jobID;
		var usernameid = $(uniquename).attr('value');
		var userfullname = $(uniquename+" option:selected").text();
		
		msg = "Are you sure you want to assign job with id: "+jobID+" to user: "+userfullname+".";
		var answer = confirm(msg)
		
		if (answer){
			
			$('#ds-current-entry-job-taken').val(jobID);
			$('#ds-current-entry-user-taken').val(usernameid);
			$('#ds-current-entry').submit();
		}
	});

	$('.cancel-job-submit').click( function() {
		jobID = $(this).attr('value');
		msg = "Are you sure you want to cancel job with id: "+jobID+". You may not have cancellation insurance, and therefor will not be refunded";
		
		//var answer = confirm("Are you sure you want to cancel this job.")
		var answer = confirm(msg)
		
		if (answer){
			jobID = $(this).attr('value');
			$('#ds-current-entry-job-taken').val(jobID);
			$('#ds-current-entry').submit();
		}
	});

///////////////////////////////////////////////////////////////wat this
	$('#custom-submit').click( function() {

		$('#ds-new-entry').submit();

	});	

	$('.register-user-submit').click( function() {
		
		var answer = confirm("Only continue if the map shows the correct location.")
		if (answer){

			jobID = $(this).attr('value');
			$('#ds-current-user-taken').val(jobID);
			$('#ds-new-entry').submit();
		}

	});
	
	$('.register-noaddress-submit').click( function() {

			jobID = $(this).attr('value');
			$('#ds-current-user-taken').val(jobID);
			$('#ds-new-entry').submit();

	});
	
	
	$('.custom-takenjob-submit').click( function() {
		//way1
		jobID = $(this).attr('value');
		$('#ds-sel-edit-job-taken').val(jobID);
		$('#ds-sel-edit-job').submit();;
		
		//way2
		//$('#ds-sel-edit-job').submit();
	
	});	
	
	$("#custom-edit-submit").click( function() {
		//var valid = true;
		//return valid;
		//$('#ds-new-entry').submit();
	});
	



	$(".input-field").blur( function() {
		finalValidate(this,validateAll(this));
		
	});

	

	function finalValidate(field,flag){

		if (flag) {

			goGreen(field);

			errormsg = "OK!";

			printmsg(field,flag);

			return true;

		} else {

			goRed(field);

			printmsg(field,flag);

			return false;

		}

	}

	

	function goGreen (field) {

		$(field).css('border', 'solid 1px #5FB946');

	}



	function goRed (field) {

		$(field).css('border', 'solid 1px #B94646');

	}



	function goNeutral (field) {

		$(field).css('border', 'solid 1px #4695B9');

	}



	function validateAll (field) {

		flag = true;

		if ($(field).attr('id') == "username") {

			flag = validateUsername (field);

		}

		if ($(field).attr('id') == "firstname") {

			flag = validateName (field);

		}
		
		if ($(field).attr('id') == "editfirstname") {

			flag = validateEditFirstName (field);

		}

		if ($(field).attr('id') == "surname") {

			flag = validateName (field);

		}

		if ($(field).attr('id') == "email") {

			flag = validateEmail (field);

		}
		
		if ($(field).attr('id') == "applyemail") {

			flag = validateApplyEmail (field);

		}

		if ($(field).attr('id') == "phone") {

			flag = validateNumberNotReq (field);

		}

		if ($(field).attr('id') == "mobile") {

			flag = validateNumber (field);

		}

		if ($(field).attr('id') == "door") {

			flag = validateText (field);
			
			UpdateMap();

		}
		if ($(field).attr('id') == "editdoor") {

			flag = validateText (field);

		}

		if ($(field).attr('id') == "address1") {

			flag = validateText (field);
			
			UpdateMap();
		}

		if ($(field).attr('id') == "city") {

			flag = validateText (field);
			
			UpdateMap();
		}

		if ($(field).attr('id') == "postcode") {

			//flag = validatePostcode (field);
			flag = validateText (field);
			
			syncMap();

		}

		if ($(field).attr('id') == "applypostcode") {

			flag = validateText (field);
			

		}
		if ($(field).attr('id') == "deliverydate") {

			flag = validateDate (field);

		}
		if ($(field).attr('id') == "duration") {//add for hours
			
			flag = validateDuration (field);

		}

		

		return flag;

	}	
	function validateDuration (field) {

		flag = true;

	//	var duration = $("#duration").attr('value');
		//if ($(duration).val() == "8am – 2pm"){
		if ($(field).val() == "8am – 2pm"){
				
			$('.hidehours').show();
//			errormsg = "This field is required.";

//			flag = false;
		}
		else
		{
			$('.hidehours').hide();
		}

		return flag;

	}	
	

	function validateText (field) {

		flag = true;

		

		if ($(field).val().length < 1){

			errormsg = "This field is required.";

			flag = false;

		}

		

		return flag;

	}	

	

	function validateUsername (field) {

		flag = true;

		

		if ($(field).val().length < 1){

			errormsg = "This field is required.";

			flag = false;

		}

		//ajax call to see if email exists

		$.ajax({

			type: "POST",

			url: "/callphp/",

			data: { username:$(field).val()},

	  		async:false,

			success: function(data){

				if(data.search("no") != -1) { 

					//if no

				}

				else if(data.search("yes") != -1) { 

					//if yes

					errormsg = "This username is already in use.";

					flag = false;

				} 

			}

		});

		

		return flag;

	}
	
	/////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	function UpdateMap () {
		var door = $("#door").attr('value');	
		var address1 = $("#address1").attr('value');
		var address2 = $("#address2").attr('value');
		var city = $("#city").attr('value');		
		var postcode = $("#postcode").attr('value');
//alert("here1");
		$.ajax({
			type: "POST",
			url: "/callphp/",
			data: {door:door, address1:address1, address2:address2, city:city, postcode:postcode},
	  		async:true,
			dataType: 'json',
			success: function(data){
				//alert("here2");
				if(data.ans == 0) { 
					//if no 
					//do code to show map
					//alert("here2");
					//$(".googlemap3").text("ssssssss");//data.lat;
					$(".googlemap3").gMap({ markers: [{ 
						latitude: data.lat,
						longitude: data.lon,
					}],							 
						zoom: 14  });
					$('.register-user-submit').show(400);
				}
				else if(data.ans == 1) { 
					//if yes
					errormsg = "Address not found.";
					flag = false;
					
					
					$(".googlemap3").gMap({ markers: [{ 
						latitude: 0,
                          longitude: 0,
					//	latitude: 50000,
                     //     longitude: 70000,
						  
							 }],							 
							 zoom: 14  });
					$('.register-user-submit').hide();
					
				} 
				
				
			}
			
		});
//		alert("here3..");
	
	
	}
	
	function syncMap () {
		var door = $("#door").attr('value');	
		var address1 = $("#address1").attr('value');
		var address2 = $("#address2").attr('value');
		var city = $("#city").attr('value');		
		var postcode = $("#postcode").attr('value');

		$.ajax({
			type: "POST",
			url: "/callphp/",
			data: {door:door, address1:address1, address2:address2, city:city, postcode:postcode},
	  		async:false,
			dataType: 'json',
			success: function(data){
				if(data.ans == 0) { 
					//if no 
					//do code to show map
					
					$(".googlemap3").gMap({ markers: [{ 
						latitude: data.lat,
						longitude: data.lon,
					}],							 
						zoom: 14  });
					$('.register-user-submit').show(400);
				}
				else if(data.ans == 1) { 
					//if yes
					errormsg = "Address not found.";
					flag = false;
					
					
					$(".googlemap3").gMap({ markers: [{ 
						latitude: 0,
                          longitude: 0,
							 }],							 
							 zoom: 14  });
					$('.register-user-submit').hide();
					
				} 
				
				
			}
		});
	
	
	}
	
	function validatePostcode (field) {

		flag = true;
		if ($(field).val().length < 1){
			errormsg = "This field is required.";
			flag = false;
		}

	}
	
	
	/////////////////////////////////////////////////////////////////////////////////////////////////////////



	function validateName (field) {

		flag = true;

		

		if ($(field).val().length < 2){

			errormsg = "This field requires at least 2 characters.";

			flag = false;

		}

		

		return flag;

	}



	function validateEditFirstName (field) {

		flag = true;

		if ($(field).val().length < 2){

			errormsg = "This field requires at least 2 characters.";

			flag = false;

		}

		return flag;

	}




	function validateEmail (field) {

		flag = true;

		

		if ($(field).val().search("@") == -1){

			errormsg = "A valid e-mail requires the @ character.";

			flag = false;

		}

		

		if ($(field).val().search(".") == -1){

			errormsg = "A valid e-mail requires the '.' character.";

			flag = false;

		}

		

		if ($(field).val().length < 3){

			errormsg = "A valid email requires at least 3 characters.";

			flag = false;

		}

		

		//ajax call to see if email exists

		$.ajax({

			type: "POST",

			url: "/callphp/",

			data: { email:$(field).val()},

	  		async:false,

			success: function(data){

				if(data.search("no") != -1) { 

					//if no

				}

				else if(data.search("yes") != -1) { 

					//if yes

					errormsg = "This email address is already in use.";

					flag = false;

				} 

			}

		});

		

		return flag;

	}

	
	
	
	
	
	
	function validateApplyEmail (field) {

		flag = true;
		if ($(field).val().search("@") == -1){
			errormsg = "A valid e-mail requires the @ character.";
			flag = false;
		}
		if ($(field).val().search(".") == -1){
			errormsg = "A valid e-mail requires the '.' character.";
			flag = false;
		}
		if ($(field).val().length < 3){
			errormsg = "A valid email requires at least 3 characters.";
			flag = false;
		}
		return flag;
	}
	


	function validateNumber (field) {

		flag = true;

		

		if (isNaN($(field).val())){

			errormsg = "This field can only contain numbers.";

			flag = false;

		}

		

		if ($(field).val().length < 3){

			errormsg = "Please enter a phone number.";

			flag = false;

		}

		return flag;

	}
	
	function validateNumberNotReq (field) {
		flag = true;
		if (isNaN($(field).val())){
			errormsg = "This field can only contain numbers.";
			flag = false;
		}
		return flag;
	}

	

	function validateDate(field) {

		valid = true;



		var length = field.value.length;

		var full = field.value.split("/",3);

		var day = full[0];

		var month = full[1];

		var year = full[2];
		
		var intRegex = /^\d+$/;

		var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
		
		var d = new Date();

		if (year <= d.getFullYear()) {
			
			if (month <= (d.getMonth() + 1)) {
				
				if (day <= d.getDate()) {

					valid = false;
		
					errormsg = "Bookings must be made at least 1 day in advance"

				}

			}
			

		}
		
		var tomorrow = new Date();
		if (year == tomorrow.getFullYear()) {
			if (month == (tomorrow.getMonth() + 1)) {
				if (day == tomorrow.getDate()+1) {
					if (tomorrow.getHours() >= 18) {
					
						valid = false;
						errormsg = "Its past 6pm, To late to book for tomorrow"
					}
				}
			}
		}


		if (!intRegex.test(month) || !intRegex.test(year)) {

			valid = false; 

			errormsg = "Invalid Format (dd/mm/yyyy)"

		}



		if (day > 31 || day <= 0) {

			valid = false;

			errormsg = "Invalid Day";

		}



		if (month > 12 || month <= 0) {

			valid = false;

			errormsg = "Invalid Month"

		}



		

		if (year > 2100 || year <= 2010) {

			valid = false;

			errormsg = "Invalid Year"

		}

		



		if (length != 10) {

			valid = false;

			errormsg = "Invalid Formatting (dd/mm/yyyy)"

		}



		switch (month) {

			case "04":

			case "06":

			case "09":

			case "11":

				if (day > 30) {

					valid = false;

					errormsg = "Invalid Date"

				}

				break;

			case "02":

				if (day > 29) {

					valid = false;

					errormsg = "Invalid Date"

				}

		}

		

		if (full == "" || field.value == "dd/mm/yyyy") {

			errormsg = "Please Insert a Date"

			return false;

		}

		

		return valid;

	}











});

//-->
