// JavaScript Document

function messagePopFill(messageBody) {
    if ($('#messagePopBox').length > 0) {
		var boxData = '<div id="xx"><a href="#" id="close-link">x</a></div><div id="x">' + messageBody + '</div>';
		$('#messagePopBox').html(boxData);
	} else {
		var boxData = '<div id="messagePopBox"><div id="xx"><a href="#" id="close-link">x</a></div><div id="x">' + messageBody + '</div></div>';
		$('#site-wrapper').prepend(boxData);
	}
};

// Convert all words in a string to uppercase
function ucwords (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}

// validate an email address

function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};

// The inpage popup
function messagePop(thisElement, thisAction) {
    if (thisAction == 'load') {
		thisElement.delay(1000).fadeIn(400);	
	} else if (thisAction == 'in') {
		thisElement.fadeIn(400);	
	} else {
		thisElement.fadeOut(400);
	}
};

// Change the content of the inpage popup
function messageSlideFill(messageBody) {
    alert(messageBody);
};

// Change the currently selected link in the AJAX autosuggest tool
function changePos(suggestPos) {
	nthClass = 'pos' + suggestPos;
	$('#suggestions').removeClass().addClass(nthClass);
};

$(function() {
	
		// Karl Swedberg's js class technique via http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx
		$('body').addClass('js');

	    // Date picker
		var dateMin = new Date();
        var weekDays = AddWeekDays(1);

        dateMin.setDate(dateMin.getDate() + weekDays);

        var natDays = [
          [1, 1, 'uk']
        ];

        function noWeekendsOrHolidays(date) {
            var noWeekend = jQuery.datepicker.noWeekends(date);
            if (noWeekend[0]) {
                return nationalDays(date);
            } else {
                return noWeekend;
            }
        }
        function nationalDays(date) {
            for (i = 0; i < natDays.length; i++) {
                if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == natDays[i][1]) {
                    return [false, natDays[i][2] + '_day'];
                }
            }
            return [true, ''];
        }
        function AddWeekDays(weekDaysToAdd) {
            var daysToAdd = 0
            var mydate = new Date()
            var day = mydate.getDay()
            weekDaysToAdd = weekDaysToAdd - (5 - day)
            if ((5 - day) < weekDaysToAdd || weekDaysToAdd == 1) {
                daysToAdd = (5 - day) + 2 + daysToAdd
            } else { // (5-day) >= weekDaysToAdd
                daysToAdd = (5 - day) + daysToAdd
            }
            while (weekDaysToAdd != 0) {
                var week = weekDaysToAdd - 5
                if (week > 0) {
                    daysToAdd = 7 + daysToAdd
                    weekDaysToAdd = weekDaysToAdd - 5
                } else { // week < 0
                    daysToAdd = (5 + week) + daysToAdd
                    weekDaysToAdd = weekDaysToAdd - (5 + week)
                }
            }

            return daysToAdd;
        }

        /* var pickupDate = jQuery('#to_when').datepicker(
        {
            inline: true,
            beforeShowDay: noWeekendsOrHolidays,
            altField: '#txtCollectionDate',
            changeFirstDay: false,
            minDate: dateMin,
            dateFormat: 'dd/mm/yy' 
        });*/
		
		var pickupDate = jQuery('#to_when').datepicker(
        {
            inline: true,
            altField: '#txtCollectionDate',
            changeFirstDay: false,
            minDate: dateMin,
            dateFormat: 'dd/mm/yy' 
        });
	
	// Close page-based messages
	$('#close-link').live('click', function() {
		messagePop($('#messagePopBox'), 'out');
		return false;	
	});
	
	// When the page has fully loaded
	$(window).load( function () {
		// Check if there's an element called "message-pop"
		// Add content to the right divs
		$('#messagePop').each(function(){
			messagePopFill($(this).html());
		});
	
		// Auto fade in page-base messages - on pages with .autoPop
		$('.autoPop #messagePopBox').each(function(){
			messagePop($(this), 'load');
		});
		
	});
	
	// Ts&Cs popup
	$('#terms-popup').live('click', function() {
		messagePop($('#messagePopBox'), 'load');
		return false;
	});
	
	var messageVar = '';
	// Booking form validation
	$('#booking-form').submit( function() {
		var canGo = 1;
		$('#booking-form input, #booking-form select, #booking-form textarea').each(function(index) {
    		if ($(this).attr('rel') == 'required') {
				if ($(this).val() == '') {
					// the field is empty
					if (messageVar == '') {
						messageVar = "The following required fields are empty: " + ucwords ($(this).attr('name'));
					} else {
						messageVar += ", " + ucwords ($(this).attr('name'));
					}
					
					canGo = 0;
				} else if ($(this).attr('name') == 'email') {
					var isValidEmail = isValidEmailAddress($(this).attr('value'));
					if (isValidEmail == false) {
						// The email's not valid
						messageVar = "That's not a valid email address";
						
						canGo = 0;
					}
				}
			}
  		});
		
		if (canGo == 1 && $('input[name=terms]:checked').length > 0 && $('input[name=terms]:checked').val() != 'Yes') {
			// The ts&Cs haven't been agreed to
			messageVar = "You need to agree to the Terms & Conditions";
			canGo = 0;
		}

		if (canGo != 1) {
			// Need to do a fancier message box..
			alert(messageVar);
			return false;
		}
	}); 
	
	// The autosuggest drop down for countries
	/*
	countryField = $('input[name="country"]');
	countryField.append('<div id="country"></div>');
	country = $('#country');
	
	var suggestPosC = 0;
	countryField.attr("autocomplete","off");
	countryField.keyup(function(event) {
	     var post = {};
	     post['address1'] = countryField.val();
	     country.load('/property/ajax_search',post);
	     
	     country.fadeIn();
	     
	     if (countryField.val() == "") {
	     	country.fadeOut();
	     };
		 
		 if (event.keyCode == 38) {
			 // UP key pressed
			 suggestPosC--;
			 if (suggestPosC < 1) {suggestPosC = 1};
			 changePos(suggestPosC);
			 return false;
		 } else if (event.keyCode == 40) {
			 // DOWN key pressed
			 suggestPosC++;
			 if (suggestPosC > $('#country dd').length) {suggestPosC = $('#country dd').length};
			 changePos(suggestPosC);
			 return false;
		 } else if (event.keyCode == 13) {
			 // ENTER key pressed
			 thisElement = '#country dd:nth-child(' + (suggestPosC + 1) + ') a'
			 thisURL = $(thisElement).attr('href');
			 if (thisURL) {
			 	window.location = thisURL;
			 	return false;
			 }
		 } else {
			 // ANY OTHER key pressed
			suggestPosC = 0;
			$('#country').removeClass();
		 };
	});
	
	countryField.keydown(function(event) {
		if (event.keyCode == 13) {
			return false;
		}
	});
	/* 
	countryField.live("focus", function() {
		country.fadeIn();
	});
	
	countryField.live("blur", function() {
		country.fadeOut();
	});
	*/
	
	// The autosuggest drop down for the search 
	propName = $('#property_name');
	//suggestions = $('#suggestions'); IE7/6 doesnt like this line :s
	var suggestPos = 0;
	propName.attr("autocomplete","off");
	propName.keyup(function(event) {
	     var post = {};
	     post['address1'] = propName.val();
	     $('#suggestions').load('/property/ajax_search',post);
	     
	     $('#suggestions').fadeIn();
	     
	     if (propName.val() == "") {
	     	$('#suggestions').fadeOut();
	     };
		 
		 if (event.keyCode == 38) {
			 // UP key pressed
			 suggestPos--;
			 if (suggestPos < 1) {suggestPos = 1};
			 changePos(suggestPos);
			 return false;
		 } else if (event.keyCode == 40) {
			 // DOWN key pressed
			 suggestPos++;
			 if (suggestPos > $('#suggestions dd').length) {suggestPos = $('#suggestions dd').length};
			 changePos(suggestPos);
			 return false;
		 } else if (event.keyCode == 13) {
			 // ENTER key pressed
			 thisElement = '#suggestions dd:nth-child(' + (suggestPos + 1) + ') a'
			 thisURL = $(thisElement).attr('href');
			 if (thisURL) {
			 	window.location = thisURL;
			 	return false;
			 }
		 } else {
			 // ANY OTHER key pressed
			suggestPos = 0;
			$('#suggestions').removeClass();
		 };
	});
	
	propName.keydown(function(event) {
		if (event.keyCode == 13) {
			return false;
		}
	});
	
	// Show the autosuggest when the user is focussed on the field
	propName.focus(function() {
		$('#suggestions').fadeIn();
	});
	
	// Hide the autosuggest when the user is not focussed on the field
	propName.blur(function() {
		$('#suggestions').fadeOut();
	});
});
