// JavaScript Document
var offsetTop = '-200%';
var timer;
var isRoomShown = false;
(function ($) {
	
	
	
	$.event.special.load = {
		add: function (hollaback) {
			if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
				// Image is already complete, fire the hollaback (fixes browser issues were cached
				// images isn't triggering the load event)
				if ( this.complete || this.readyState === 4 ) {
					hollaback.handler.apply(this);
				}

				// Check if data URI images is supported, fire 'error' event if not
				else if ( this.readyState === 'uninitialized' && this.src.indexOf('data:') === 0 ) {
					$(this).trigger('error');
				}

				else {
					$(this).bind('load', hollaback.handler);
				}
			}
		}
	};
}(jQuery));

$(function(){
	
	$('div.page_rooms tbody tr:nth-child(4n+1)').css('background-color', '#D6D6D6');
	
	$('a[rel="external"]').attr('target', '_blank').attr('title','Link opens in a new window/tab'); 
	
	
	$('#header').ajaxError(function(e, jqxhr, settings, exception) {
		var theURL = settings.url;
	 	if (theURL.match(/randImg.php/i) != null) {
			
			return false;
	 	}
	  	if (theURL.match(/processBooking.php/i) != null) {
			sendError("Sorry, there seems to have been a problem checking for bookings. Please try again!");
			return false;
	  	}
	  	//sendError("Something went wrong with the website, don't worry, it shouldn't cause you any problems. Carry on!");
	});
	$('body').append('<div id="overlay">'+
		'<div id="ajaxholder">' +
			'<div class="content"><div class="section"></div><img class="close" src="i/common/close.png" alt="close" /></div>'+
			'<div id="loading">'+
			 ' <p><img  src="i/common/ajax-loader.gif" /> Please Wait</p>' +
			'</div>' +
		'</div>'+
	'</div>');
	$('#overlay').click(function(e) {
		if($(e.target).attr('id') == 'overlay') {
			$(this).fadeOut(100);
		}
	});
	$('img.close').click(function() {
		$('#overlay').fadeOut(100);	
	});
	
	$("#loading").ajaxStart(function(){
		$(this).show();
	}).ajaxStop(function(){
		$(this).hide();
	});

	$('.fresheditable').fresheditor().click(function() {
		
		return false;
		
	}).addClass('javascriptLink').one("mouseup",function(e) {
		if (e.button != 2) {
			editField(this);
		}
		
	}).hover(function() {
		if (!editting) {
			$(this).append('<div class="edit">edit</div>');
		}
	}, function() {
		$(this).find('.edit').remove();
	});
	
	
	
	
		$("#checkIn .in .cal").append('<input type="text" id="dateStart" />');
		$("#checkIn .out .cal").append('<input type="text" id="dateEnd" />');
		$( "#dateStart" ).datepicker({ dateFormat: 'dd/m/yy',  onSelect: function(dateText, inst) { 
		
		   		var arr = dateText.split("/");
				$('#daysI').val(arr[0]);
				$('#monthsI').val(arr[1]);
				$('#yearI').val(arr[2]);
				
				if (($('#yearI').val() > $('#yearS').val()) || (($('#yearI').val() <= $('#yearS').val()) && $('#monthsI').val() > $('#monthsS').val()) || (($('#yearI').val() <=  $('#yearS').val()) && ($('#monthsI').val() <= $('#monthsS').val()) && $('#daysI').val() > $('#daysS').val())) {
						$('#daysS').val(arr[0]);
						$('#monthsS').val(arr[1]);
						$('#yearS').val(arr[2]);
				}
				
		   } });
		$( "#dateEnd" ).datepicker({ dateFormat: 'dd/m/yy',  onSelect: function(dateText, inst) { 
		
		   		var arr = dateText.split("/");
				$('#daysS').val(arr[0]);
				$('#monthsS').val(arr[1]);
				$('#yearS').val(arr[2]);
		   } });
		
				
		$('#expandArea .holder').hide();
		$('#expandArea > div > h2').addClass('javascriptLink');
		$('#expandArea > div > h2').bind('click', function(event) {
			if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; }
			if ($(this).siblings('.holder').css('display') == "none") {
				$(this).siblings('.holder').slideDown(400);	
			} else {
				$(this).siblings('.holder').slideUp(400);	
			};
		});
		
		$('#addPost').click(function() {
			
			$(this).parent().after('<div id="blog_0" class="new post fe fresheditable javascriptLink" contenteditable="false">' +
'<h2>Example</h2>'+
'<p>Example</p>'+
'</div>');
$('#r1 .g65 .new').fresheditor().click(function() {
		
		return false;
		
	}).addClass('javascriptLink').one("click",function(e) {
		if (e.button != 2) {
			$(this).removeClass('new');
			editField(this);
		}
		
	}).hover(function() {
		if (!editting) {
			$(this).append('<div class="edit">edit</div>');
		}
	}, function() {
		$(this).find('.edit').remove();
	});
	$('#r1 .g65 .new').click();
			return false;
		});
		
		
		$('#addFaq').click(function() {
			
			$(this).parent().after('<div id="faq_0" class="new fresheditable javascriptLink" contenteditable="false">' +
'<h3>Question</h3>'+
'<p>Answer</p>'+
'</div>');
$('#r1 .g65 .new').fresheditor().click(function() {
		
		return false;
		
	}).addClass('javascriptLink').one("click",function(e) {
		
		if (e.button != 2) {
			$(this).removeClass('new');
			editField(this);
		}
		
	}).hover(function() {
		if (!editting) {
			$(this).append('<div class="edit">edit</div>');
		}
	}, function() {
		$(this).find('.edit').remove();
	});
	$('#r1 .g65 .new').click();
			return false;
		});
		
		$('.twtr-doc').width($('#twitterArea').width()-20);
		
		
		
		$(window).resize(function() {
		  $('.twtr-doc').width($('#twitterArea').width()-20);
		});
				
		
	
				$('#yearI').blur(function() {
					var str = $(this).val();
					if (str.length != 4) {
						$(this).val() = "20"+str.substr(str.length-2);
					}
				});
				$('#bookingForm').submit(function(event) {
					if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; }
					getAvailability();
				});

		rooms_img_baseline = $('div.page_rooms #r1 .col.g25>div').offset();
		var windowHeight = $('body').height();
		var currentRoomsImgPos;
		//$('body').append('<div id="scrollTest" style="position: fixed; z-index: 1000; top: 0; background-color: #ffffff;"></div>');
		$(window).scroll(function() {
			if (isRoomShown) {
			//$('#scrollTest').text(windowHeight+' : '+($(window).scrollTop()+$(window).height()));
			//if ((windowHeight - ($(window).scrollTop()+$(window).height())) > $(window).height()) {
			currentRoomsImgPos = ($(window).scrollTop()-rooms_img_baseline.top)+15;
			if (currentRoomsImgPos < 0) {
				currentRoomsImgPos = 0;	
			}
			
			$('div.page_rooms #r1 .col.g25>div').css({'position': 'relative','top': currentRoomsImgPos+'px'});
			}
		});
		
		$("table .details td").hide();
		$('table tr').addClass('javascriptLink');
		$("table tr").click(function(event) {
			event.preventDefault();
			if ($(this).next('.details').children('td').css('display') == "none") {
				isRoomShown = true;
				
				currentRoomsImgPos = ($(window).scrollTop()-rooms_img_baseline.top)+15;
				if (currentRoomsImgPos < 0) {
					currentRoomsImgPos = 0;	
				}
			
				$('div.page_rooms #r1 .col.g25>div').animate({'top': currentRoomsImgPos+'px'},500);
				
				$('table .details td').hide();
				$(this).next('.details').children('td').fadeIn(400, function() {
					windowHeight = $('body').height();
				});
				if 	($(this).find('.room').text() == "1") {
					$('#r1 .col.g25 img.one').fadeIn(200);	
				}
				if 	($(this).find('.room').text() == "2 + 3") {
					$('#r1 .col.g25 img.two').fadeIn(200);	
				}
				if 	($(this).find('.room').text() == "4") {
					$('#r1 .col.g25 img.three').fadeIn(200);	
				}
				if 	($(this).find('.room').text() == "5") {
					$('#r1 .col.g25 img.four').fadeIn(200);	
				}
				if 	($(this).find('.room').text() == "6") {
					$('#r1 .col.g25 img.five').fadeIn(200);	
				}
				if 	($(this).find('.room').text() == "7") {
					$('#r1 .col.g25 img.six').fadeIn(200);	
				}
				if 	($(this).find('.room').text() == "8") {
					$('#r1 .col.g25 img.seven').fadeIn(200);	
				}
				if 	($(this).find('.room').text() == "9") {
					$('#r1 .col.g25 img.eight').fadeIn(200);	
				}
			} else {
				isRoomShown = false;
				$('div.page_rooms #r1 .col.g25>div').animate({'top': '0px'},500);
				$(this).next('.details').children('td').fadeOut(400, function() {
					windowHeight = $('body').height();
				});
				$('#r1 .col.g25 img').hide();
			}
		});
		
	
	
});

function getAvailability() {
				
				
				
				$.post("processBooking.php", { daysI: $('#daysI').val().replace(/^0+/,""), monthsI: $('#monthsI option:selected').val(), yearI: $('#yearI').val(), daysS: $('#daysS').val().replace(/^0+/,""), monthsS: $('#monthsS option:selected').val(), yearS: $('#yearS').val(), guests: $('#guests').val(), rooms: $('#rooms').val()  },
 					function(data){
						$('#overlay').show();
						
						//$('body').prepend(data);
						$('#overlay .content .section').empty();
						var bookingSlots = $(data).find('form[action="reserve.php"]');
						
						if (bookingSlots.length > 0) {
							bookingSlots.each(function(index) {
								$('#overlay .content .section').append(this);
							});
							
							$('#overlay .content .section td').attr('bgcolor','');
							$('#overlay .content .section table').attr('border','0').attr('bgcolor','');
							$('#overlay .content .section input[type="submit"]').attr('class','button').css('font-size','1.7em');
							$('#overlay .content .section form').css({'border-bottom': '1px dashed #999999', 'margin-bottom': '20px', 'padding-bottom': '10px', 'position' :'relative'});
							$('#overlay .content .section form:nth-child(odd)').css('background-color','#fafafa');
							$('#overlay .content .section form').each(function() {
								$(this).attr('action','http://booking.caterbook.com/thegriffin/A1156/'+$(this).attr('action'));	
							});
						
							$('#overlay .content .section table > tbody > tr:nth-child(2) > td > table > tbody > tr >td:nth-child(2) > table > tbody > tr:nth-child(1) td:nth-child(1)').css({'font-size':'1.8em'});
							$('#overlay .content .section table > tbody > tr:nth-child(2) > td > table > tbody > tr >td:nth-child(2) > table > tbody > tr td:nth-child(1)').css({'width':'45%'});
							$('#overlay .content .section table > tbody > tr:nth-child(2) > td > table > tbody > tr >td:nth-child(2) > table > tbody > tr td:nth-child(1) > table > tbody > tr td:nth-child(1)').css({'width':'45%'});
							$('#overlay .content .section table > tbody > tr:nth-child(2) > td > table > tbody > tr >td:nth-child(2) > table > tbody > tr:nth-child(1) td:nth-child(1)').each(function () {
								$(this).html($(this).html().replace(/&nbsp;Room Type:&nbsp;/gi,''));	
								$(this).find('img').remove();
							});
							$('#overlay .content .section table > tbody > tr:nth-child(2) > td > table > tbody > tr >td:nth-child(2) > table > tbody > tr:nth-child(4) > td > table td').css({'padding':'5px','font-size':'1.4em'});
							$('#overlay .content .section table > tbody > tr:nth-child(2) > td > table > tbody > tr >td:nth-child(2) > table > tbody > tr:nth-child(4) > td > table td.textbluebold11').css({'font-weight':'bold','font-size':'1.5em'});
							$('#overlay .content .section table > tbody > tr:nth-child(2) > td > table > tbody > tr >td:nth-child(2) > table > tbody > tr:nth-child(4) > td > table td.textorangebold11').css({'font-weight':'bold','font-size':'1.5em'});
							$('#overlay .content .section table > tbody > tr:nth-child(2) > td > table > tbody > tr >td:nth-child(2) > table > tbody > tr:nth-child(3)').remove();
							$('#overlay .content .section table > tbody > tr:nth-child(2) > td > table > tbody > tr >td:nth-child(2) > table > tbody > tr:nth-child(2)').remove();
							$('#overlay .content .section form').each(function() {

								var roomText = $.trim($(this).find('table > tbody > tr:nth-child(2) > td > table > tbody > tr >td:nth-child(2) > table > tbody > tr:nth-child(1) td:nth-child(1)').text());
								//alert(roomText.length);
								roomText = $.trim(roomText.replace(/\xA0/g,""));
								
								//alert(roomText.length);
								console.log(roomText);
								roomText = roomText.substring(roomText.length-1);
								
								$(this).find('table > tbody > tr:nth-child(2) > td > table > tbody > tr >td:nth-child(2)').eq(1).append('<img style="position:absolute; top: 15px; height: 120px; border: 1px solid #333; left:70%;" src="i/cms/Room-'+roomText+'.jpg">');
							});
							$('#overlay .content .section form > table > tbody > tr:nth-child(1)').remove();
							$('#overlay .content .section form > table > tbody > tr:nth-child(3)').remove();
							
							
						} else {
							$('#overlay .content .section').append('<p>We\'re afraid there are no available rooms for those dates. Perhaps you could try a different date?</p>');
						}
					}
				);
			}
var editting = false;
var editO  = null;
var currentHTML = '';
function editField (o) {
    //o.contentEditable = "true";
	if (!editting) {
		editting = true;
		$(o).fresheditor("edit", true);	
		editO = o;
		currentHTML = $(o).clone();
		$(currentHTML).find('div.edit').remove();
		
		$(o).find('.edit').remove();
		$(document).one("click", function() { 
			//o.contentEditable = "false";
			$(o).fresheditor("edit", false).one("mouseup",function(e) {
				if (e.button != 2) {
					editField(this);
				 }
			}
			);
			
			if (currentHTML.html() != $(o).html()) {
				$(o).fresheditor("save", function(id, content) {
					saveCMS(id,content);
				});
			}
			
			editO = null;
			editting = false;
			
		
		});	
	} else {
		if (editO != null) {
			$(document).click();
			editO = null;
			editting = false;
			
		}
		$(o).one("mouseup",function(e) {
			 if (e.button != 2) {
				editField(this);
			 }
		});	
	}
	
}

function saveCMS(id,html) {

	
	var type = '';

	if (id.match('cms') != null) {
		type = '1';	
	}
	if (id.match('blog') != null) {
		type = '2';	
	}
	if (id.match('poi') != null) {
		type = '3';	
	}
	if (id.match('faq') != null) {
		type = '4';	
	}
	id = id.replace("cms_",'');
	id = id.replace("poi_",'');
	id = id.replace("blog_",'');
	id = id.replace("faq_",'');
	
	$.post("inc/cms.php", { ajax: 'true', set: id, type: type},
 		function(data){
		
			if (data.id) {
				$.post("inc/cms.php", { ajax: 'true', cid: data.id, set: id, type: type, val: html, ar : $.sha1($('#CMS_ar').val()+data.challenge)},
 					function(data){
						alert(data);
					}
				);
			}
			
			//Call a save PHP ajax	
		}
	, "json");
			
}


function sendError(s) {
	
	$('body').prepend('<div class="errorBar javascriptLink"><p>'+s+'</p></div>');
	$('div.errorBar').slideDown(400,function() {
		$(this).click(function() {
			$(this).slideUp(400, function() {
				$(this).remove();	
			});
		});
	});
}
