// JQUERY FUNCTIONS: ////////////////////////
$(document).ready(function() {
    
    screenSizer();    
    
     jQuery.preloadImages = function() {
         for (var i = 0; i < arguments.length; i++) {
             jQuery("<img>").attr("src", arguments[i]);
         }
     }
    
    $("#showEditables").click(function() {
        $(".editableDisplay, .editableDisplay p").animate({ backgroundColor: "yellow" }, 100)
        .animate({ backgroundColor: "#222222" }, 1400);

        setTimeout(function() {
            $(".editableDisplay, .editableDisplay p").css("background-color", "Transparent");
        }, 1550);
    });

    $("#showEditablesImages").click(function() {
        $(".editableDisplay img, .editableDisplay a.pagenav").css({ "border": "1px solid yellow" });
        setTimeout(function() {
            $(".editableDisplay img, .editableDisplay a.pagenav").css("border", "none");
        }, 1500);
    });

    //Hotel search:
    $("#LinkHotelSearch").click(function() {
        $(this).toggleClass("HotelSearch_on");
        $("#PanelHotels").slideToggle(500);
    });

    //Clear search field on click
    $("#search > input:not(.themeBG)").click(function() {

    });

    // Clear textbox on click:
    $(".subscribe_txt").focus(function() {
        if ($(this).val() == "Name" || $(this).val() == "E-mail Address" || $(this).val() == "Promo Code:") { $(this).val("") }
    });

    // Homecoming open and shuts:
    $(".showDate_text").hide();
    $(".showDate").click(function() {
        $(".showDate_text").slideUp();
        $(".showDate").removeClass("showDate_on");
        $("#" + this.id).parent().next("div").slideToggle();
        $("#" + this.id).addClass("showDate_on");
    });

    $("#awards li div").hide();
    $(".awardstable").parent().hide();

    $("#awards li").click(function() {
        $("#awards li").removeClass("on");
        $("#awards li div").slideUp(400);

        $("#" + this.id + " div").slideDown(400);
        $("#" + this.id).addClass("on");
    });
    $(".showtable").click(function() {
        $(".awardstable").parent().slideUp(400);
        $("#" + this.id).next("div").slideDown(400);
    });

	// Sidebar Booking Form Dates
   $('.date-pick-bookForm').datePicker();

	// Register Page Dropdowns
	if(document.getElementById('registerForm')) {
		function hideAllOptions(){
			$('#advertisingRow, #onlineRow, #otherRow, #heardOtherRow').hide();
		}

		function changeOptions(){
			var val = $('#referrerOption').val();

			if (val == '') {
				hideAllOptions();
			} else if (val == 'Advertising') {
				hideAllOptions();
				$('#advertisingRow').show();
				$('#onlineOption, #otherOption').val('');
				// make heardOtherRow appear on page refresh after error
				if ($('#advertisingOption').val() == 'Other') {
					$('#heardOtherRow').show();
				} else {
					$('#heardOther').val('');
				}
				// check if the textbox should appear for the "other" option in advertising
				$('#advertisingOption').change(function(){
					if ($('#advertisingOption').val() == 'Other') {
						hideAllOptions();
						$('#advertisingRow, #heardOtherRow').show();
						$('#onlineOption, #otherOption').val('');
					} else {
						hideAllOptions();
						$('#advertisingRow').show();
						$('#onlineOption, #otherOption, #heardOther').val('');
					}
				});

			} else if (val == 'Online') {
				hideAllOptions();
				$('#onlineRow').show();
				$('#advertisingOption, #otherOption').val('');
				// make heardOtherRow appear on page refresh after error
				if ($('#onlineOption').val() == 'Other') {
					$('#heardOtherRow').show();
				} else {
					$('#heardOther').val('');
				}
				// check if the textbox should appear for the "other" option in advertising
				$('#onlineOption').change(function(){
					if ($('#onlineOption').val() == 'Other') {
						hideAllOptions();
						$('#onlineRow, #heardOtherRow').show();
						$('#advertisingOption, #otherOption').val('');
					} else {
						hideAllOptions();
						$('#onlineRow').show();
						$('#advertisingOption, #otherOption, #heardOther').val('');
					}
				});

			} else if (val == 'Other') {
				hideAllOptions();
				$('#otherRow').show();
				$('#advertisingOption, #onlineOption').val('');
				// make heardOtherRow appear on page refresh after error
				if ($('#otherOption').val() == 'Other') {
					$('#heardOtherRow').show();
				} else {
					$('#heardOther').val('');
				}
				// check if the textbox should appear for the "other" option in advertising
				$('#otherOption').change(function(){
					if ($('#otherOption').val() == 'Other') {
						hideAllOptions();
						$('#otherRow, #heardOtherRow').show();
						$('#advertisingOption, #onlineOption').val('');
					} else {
						hideAllOptions();
						$('#otherRow').show();
						$('#advertisingOption, #onlineOption, #heardOther').val('');
					}
				});
			}
		}

		function initHeardAbout(){
			if (document.getElementById('referrerOption')){
				var heard = document.getElementById('referrerOption');
				heard.onchange = changeOptions;
			}
		}
		hideAllOptions();
		changeOptions();
		initHeardAbout();

	}
	

	// Sidebar room booking validation
	$('#BookaRoom').submit(function(event) {
		// remove all previous error messages
		$('#switch_links .error').remove();

		// set global error array
		var roomErrors = new Array();

		// do validation and stack them in the array
		if ($('#sidebarBookHotel').val() == '') {
			roomErrors.push('Please select a hotel.');
		}
		if ($('#sidebarBookAdults').val() == '0') {
			roomErrors.push('Please select a number of persons.');
		}
		if ($('#sidebarBookNights').val() == '0') {
			roomErrors.push('Please select a number of nights.');
		}
		if ($('#sidebarBookArrival').val() == 'Date:') {
			roomErrors.push('Please select a date.');
		}

		// show errors
		if (roomErrors[0]) {
			$('<p class="error">We\'re sorry, there has been an error:</p>').fadeIn(500).insertBefore('#switch_rooms');
			$('<ul class="error"></ul>').fadeIn(500).insertAfter('#switch_links p:eq(0)');
			var errors = '';
			$(roomErrors).each(function(i, roomError){
				errors += '<li>' + roomError + '</li>';
			});
			$('#switch_links ul:eq(0)').html(errors);
			event.preventDefault();
		}

	});

	// Main room booking validation
	if (document.getElementById('bookRoomForm') && document.getElementById('bookRoomFormDefault')) {
		$('#bookRoomForm').submit(function(event) {
			console.log('main booking submit');
			// remove all previous error messages
			$('.wFull .error').remove();

			// set global error array
			var roomErrors = new Array();

			// do validation and stack them in the array
			if ($('#bookHotel').val() == '') {
				roomErrors.push('Please select a hotel.');
			}
			if ($('#bookAdults').val() == '') {
				roomErrors.push('Please select a number of persons.');
			}
			if ($('#bookNights').val() == '') {
				roomErrors.push('Please select a number of nights.');
			}
			if ($('#bookArrival').val() == '') {
				roomErrors.push('Please select a date.');
			}

			// show errors
			if (roomErrors[0]) {
				$('<p class="error">We\'re sorry, there has been an error:</p>').fadeIn(500).insertBefore('#bookRoomForm');
				$('<ul class="error"></ul>').fadeIn(500).insertAfter('.wFull p.error');
				var errors = '';
				$(roomErrors).each(function(i, roomError){
					errors += '<li>' + roomError + '</li>';
				});
				$('.wFull ul.error').html(errors);
				event.preventDefault();
			}
		});

		// Show / Hide extras on main booking form
		$('.bookFormExtra').hide();
		$('#bookRoomFormDefault #bookHotel').change(function() {
			if($(this).val() != '') {
				$('.bookFormExtra').show();
			} else {
				$('.bookFormExtra').hide();
			}
		});
	}

	// Sidebar bistro booking validation
	$('#BookBistro').submit(function(event) {
		// remove all previous error messages
		$('#switch_links .error').remove();

		// set global error array
		var roomErrors = new Array();

		// do validation and stack them in the array
		if ($('#sidebarBistroHotel').val() == '') {
			roomErrors.push('Please select a hotel.');
		}
		if ($('#sidebarBistroAdults').val() == '0' || $('#sidebarBistroAdults').val() == '') {
			roomErrors.push('Please select a number of persons.');
		}
		if ($('#sidebarBistroType').val() == '0' || $('#sidebarBistroType').val() == '') {
			roomErrors.push('Please select a meal type.');
		}
		if ($('#sidebarBistroArrival').val() == 'Date:' || $('#sidebarBistroArrival').val() == '') {
			roomErrors.push('Please select a date.');
		}

		// show errors
		if (roomErrors[0]) {
			$('<p class="error">We\'re sorry, there has been an error:</p>').fadeIn(500).insertBefore('#switch_rooms');
			$('<ul class="error"></ul>').fadeIn(500).insertAfter('#switch_links p:eq(0)');
			var errors = '';
			$(roomErrors).each(function(i, roomError){
				errors += '<li>' + roomError + '</li>';
			});
			$('#switch_links ul:eq(0)').html(errors);
			event.preventDefault();
		}
	});

	// Bistro Booking Main Page
	if (document.getElementById('bookForm') && document.getElementById('bistroBookFormDefault')) {

		// hide extras when there are no errors on the page
		if($('.wFull .error').html() == null) {
			$('.bookFormExtra').hide();
		}

		// open extra panel for bookings from sidebar
		if($('#bistroBookFormDefault #bistroHotel').val() != '') {
			$('.bookFormExtra').show();
		}

		$('#bistroBookFormDefault #bistroHotel').change(function() {
			if($(this).val() != '') {
				$('.bookFormExtra').show();
			} else {
				$('.bookFormExtra').hide();
			}
		});
		// NOTE: js for lunch/dinner time switch is on page itself as it gets the times from the view

		$('#bookForm').submit(function(event){
			$('.wFull .error').remove(); // remove all pre-exisiting errors for main form
			var bistroErrors = new Array(); // set global error array

			// do validation and stack them in the array
			if ($('#bookForm #bistroHotel').val() == '') {
				bistroErrors.push('Please select a hotel.');
			} else {
				// do the other validation only after the other segments are visible
				if ($('#bookForm #bistroAdults').val() == '0') {
					bistroErrors.push('Please select a number of persons.');
				}
				if ($('#bookForm #bistroArrivalDay').val() == '' || $('#bookForm #bistroArrivalMonth').val() == '' || $('#bookForm #bistroArrivalYear').val() == '') {
					bistroErrors.push('Please select a date.');
				}
				if ($('#bookForm #time').val() == '') {
					bistroErrors.push('Please select a time.');
				}
			}

			// show errors
			if (bistroErrors[0]) {
				$('<p class="error">We\'re sorry, there has been an error:</p>').fadeIn(500).insertBefore('#bookForm');
				$('<ul class="error"></ul>').fadeIn(500).insertAfter('.wFull p.error');
				var errors = '';
				$(bistroErrors).each(function(i, bistroError){
					errors += '<li>' + bistroError + '</li>';
				});
				$('.wFull ul.error').html(errors);
				event.preventDefault();
			}
		});
	}

	// Newsletter sidebar validation
	$('#newsletterSidebar').submit(function(event) {
		// remove all previous error messages
		$('#newsletterSidebar .error').remove();

		// set global error array
		var newsletterErrors = new Array();
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

		// do validation and stack them in the array
		if ($('#newsletterName').val() == '' || $('#newsletterName').val() == 'Name') {
			newsletterErrors.push('Please enter your name.');
		}
		if ($('#newsletterEmail').val() == '' || $('#newsletterEmail').val() == 'E-mail Address') {
			newsletterErrors.push('Please enter your email address.');
		} else if (!filter.test($('#newsletterEmail').val())) {
			newsletterErrors.push('Please enter a valid email address.');
		}

		// show errors
		if (newsletterErrors[0]) {
			$('<p class="error">We\'re sorry, there has been an error:</p>').fadeIn(500).insertBefore('#newsletterName');
			$('<ul class="error"></ul>').fadeIn(500).insertAfter('#newsletterSidebar p:eq(0)');
			var errors = '';
			$(newsletterErrors).each(function(i, newsletterError){
				errors += '<li>' + newsletterError + '</li>';
			});
			$('#newsletterSidebar ul:eq(0)').html(errors);
			event.preventDefault();
		}

	});

}); // END OF $ FUNCTION

// Homepage tabs - 2DO check on funcitonality as it's taken from inner page script insert
if (document.getElementById('homeSlideShow')) { // loading script only on homepage - added id to element for that
	$(function() {
		$("div.tabs").tabs(".images > a", {
			effect: 'fade',
			fadeOutSpeed: 'slow',
			rotate: true,
			autoplay: true
		}).slideshow();
	});
	$(document).ready(function() {
		$("div.tabs").tabs().play();
	});
}


// Sidebar Booking Form Switch
function BookSwitch() {
	// remove all previous error messages that come from the validation
	$('#switch_links .error').remove();
	$('#BookBistro').toggle();
	$('#BookaRoom').toggle();
	$('#switch_bistro').toggleClass("on");
	$('#switch_rooms').toggleClass("on");
	roomTab = !roomTab;
}


function screenSizer() {
    var heightWindow = $(window).height();
    var heightDocument = $(document).height();
    var heightFooter = $("#Footer").height();
    var heightWrap = $(".Wrap").height()

    if (heightWindow >= heightDocument) {
        heightFooter += (heightWindow - heightWrap);
        $("#Footer").height(heightFooter);
    }
}


/*
JSTarget function by Roger Johansson, www.456bereastreet.com
*/
var JSTarget = {
    init: function(att, val, warning) {
        if (document.getElementById && document.createElement && document.appendChild) {
            var strAtt = ((typeof att == 'undefined') || (att == null)) ? 'class' : att;
            var strVal = ((typeof val == 'undefined') || (val == null)) ? 'non-html' : val;
            var strWarning = ((typeof warning == 'undefined') || (warning == null)) ? ' (opens in a new window)' : warning;
            var arrLinks = document.getElementsByTagName('a');
            var oLink;
            var oRegExp = new RegExp("(^|\\s)" + strVal + "(\\s|$)");
            for (var i = 0; i < arrLinks.length; i++) {
                oLink = arrLinks[i];
                if ((strAtt == 'class') && (oRegExp.test(oLink.className)) || (oRegExp.test(oLink.getAttribute(strAtt)))) {
                    oLink.onclick = JSTarget.openWin;
                }
            }
            oWarning = null;
        }
    },
    openWin: function(e) {
        var event = (!e) ? window.event : e;
        if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true;
        else {
            var oWin = window.open(this.getAttribute('href'), '_blank');
            if (oWin) {
                if (oWin.focus) oWin.focus();
                return false;
            }
            oWin = null;
            return true;
        }
    },
    /*
    addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
    */
    addEvent: function(obj, type, fn) {
        if (obj.addEventListener)
            obj.addEventListener(type, fn, false);
        else if (obj.attachEvent) {
            obj["e" + type + fn] = fn;
            obj[type + fn] = function() { obj["e" + type + fn](window.event); }
            obj.attachEvent("on" + type, obj[type + fn]);
        }
    }
};
JSTarget.addEvent(window, 'load', function() { JSTarget.init("rel", "external"); });

function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}


