﻿
// ********************************************************************************************** //
// StayCity Site Template v3.0
// JavaScript Functions v1.0
// Major revision: 14/05/2009


// ********************************************************************************************** //
// Determine Functions Relevant to Section to Initialise

var ie6;

// Boot up jQuery:
jQuery(document).ready(function($)
{
	init_PageContent();
});


// Determine functions to initialise at page load:
function init_PageContent()
{
	// Set IE6 detection global variable:
	if($.browser.msie && (parseInt(jQuery.browser.version) == 6)) { ie6 = true; }
	
	// Generic cross-site functions:
	init_MainNav_DropDowns();
	init_DatePicker();
	init_Guarantee();
	
	// Page specific functions:
	switch (curSection)
	{
		case("sect-home"):
			init_Main_Image_Rotator();
			init_Homepage_Apartment_Slider();
			init_Modal_BookNow();
			
			/*
			$.sifr({
                path: 'flash/',
                save: true,
				build: 436,
				version: 3,
				color: 'ffffff'
			});
			$('.usp h3').sifr({
				font: 'helvetica55',
				forceSingleLine: true,
				width: '636'
			});
			*/
			
			
			
			break;
		case("sect-results"):
			init_Results_Table();
			break;
		case("sect-booking"):
			init_TableRowColours();
			break;
		case("sect-apartments"):
			init_MultiTabs();
			init_Accordion();
			init_Lightbox();
			init_Modal_BookNow();
			break;
		case("sect-landing"):
			init_Main_Image_Rotator();
			init_MultiTabs();
			init_Accordion();
			init_Lightbox();
			init_Modal_BookNow();
			init_GoogleMap_Locations(markerList); /* Markerlist defined on html page */
			break;
		case("sect-generic"):
			init_MultiTabs();
			init_Modal_BookNow();
			break;
		case("sect-faq"):
			init_Modal_BookNow();
			init_FAQ();
			break;
	}
	
}


// ======================================================================================================= //
/* Site-wide Generic Functionality */
// ======================================================================================================= //

function init_MainNav_DropDowns()
{
	$("div.navigation > ul").superfish(
	{
		animation	: { height:"show" },
		speed		: "fast",
		delay		: 400
	});
}

function init_Main_Image_Rotator()
{
	$('.main-image-rotator').cycle(
	{
		timeout:	4000,
		speed:		500,
		pause:		0
	});
}

function init_Lightbox()
{
	$("a[rel^='lightbox']").prettyPhoto({
		animationSpeed: 'fast', /* fast/slow/normal */
		padding: 40, /* padding for each side of the picture */
		opacity: 0.7, /* Value betwee 0 and 1 */
		showTitle: false, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: ' of ', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'light_square', /* light_rounded / dark_rounded / light_square / dark_square */
		callback: function(){}
	});
}

function init_Modal_BookNow()
{
	$("a.book-now").click(function (e) {
		e.preventDefault();
		var myApt = $(this).attr("rel").substring(4);
		$('.booking-panel').modal({
			opacity: 80,
			zIndex: 400,
			persist: true,
			containerCss: {
				height: 322,
				width: 308,
				backgroundColor: '#E0E0CB',
				border: '3px solid #fff'
			},
			onOpen: function (dialog) {
				$('#building').val(myApt);
				$('.header').css('z-index',0);
				dialog.overlay.fadeIn('fast', function () {
					dialog.container.slideDown('fast', function () {
						dialog.data.fadeIn('fast');
					});
				});
				dialog.overlay.click(function (e) {
					e.preventDefault();
					dialog.overlay.unbind('click');
					$.modal.close();
					$('.header').css('z-index',200);
				});
			},
			onClose: function (dialog) {
				dialog.data.fadeOut('fast', function () {
					dialog.container.slideUp('fast', function () {
						dialog.overlay.fadeOut('fast', function () {
							dialog.overlay.unbind('click');
							$.modal.close();
							$('.header').css('z-index',200);
						});
					});
				});
			}
		});
	});
}


// ======================================================================================================= //
/* Datepicker Functionality */
// ======================================================================================================= //

function init_DatePicker()
{
	$("#checkin").datepicker(
	{
		showOn:				'both',
		buttonText:			'Select date...',
		buttonImageOnly:	true,
		buttonImage:		'images/common/calendar.gif',
		showOtherMonths:	true,
		dateFormat:			'dd/mm/yy',
		minDate:			0,
		numberOfMonths:		1,
		duration:			'fast',
		firstDay:			1,
		beforeShow:			datePicker_ReadLinked,
		onSelect:			datePicker_UpdateLinked
	});
	
	$("#checkout").datepicker(
	{
		showOn:				'both',
		buttonText:			'Select date...',
		buttonImageOnly:	true,
		buttonImage:		'images/common/calendar.gif',
		showOtherMonths:	true,
		dateFormat:			'dd/mm/yy',
		minDate:			0,
		numberOfMonths:		1,
		duration:			'fast',
		firstDay:			1,
		beforeShow:			datePicker_ReadLinked,
		onSelect:			datePicker_UpdateLinked
	});
	
	if(ie6) {
		$('#checkin').datepicker('option', 'duration', '');
		$('#checkout').datepicker('option', 'duration', '');
	}
	
}

// Read what's in the associated dummy field to make sure we're pulling out the right 
function datePicker_ReadLinked()
{
	var myElement = $(this).attr("id"); // Get id of dummy field, ie #checkIn or #checkOut
    $('#'+myElement).val(
		$('#'+myElement+'_day'  ).val() + '/' +
		$('#'+myElement+'_month').val() + '/' +
		$('#'+myElement+'_year' ).val()
	);
    return{};
}

// Update the three select controls to match a date picker selection
function datePicker_UpdateLinked(newDate)
{	
	var myElement = $(this).attr("id"); // Get id of dummy field, ie #checkIn or #checkOut
    $('#'+myElement+'_day'  ).val(newDate.substring(0, 2));
    $('#'+myElement+'_month').val(newDate.substring(3, 5));
    $('#'+myElement+'_year' ).val(newDate.substring(6, 10));
	
	if (myElement == 'checkin') {
		
		// Create date objects from the fields for us to use:
		var checkInDate = new Date(
			$('#checkin_year').val(),
			$('#checkin_month').val()-1,
			$('#checkin_day').val()
		);
		var checkOutDate = new Date(
			$('#checkout_year').val(),
			$('#checkout_month').val()-1,
			$('#checkout_day').val()
		);
		
		// Update the minimum date allowable in the check-out to be that of the new check-in:
		var newMin = new Date(checkInDate);
		newMin.setDate(newMin.getDate()+1);
		$("#checkout").datepicker('option','minDate',newMin);
		
		// If the previous check-out date is older, update it to the new check-in date:
		var newDay = newMin.getDate();
		if (newDay < 10) { newDay = "0" + newDay; }
		var newMonth = newMin.getMonth() + 1;
		if (newMonth < 10) { newMonth = "0" + newMonth; }
		var newYear = newMin.getFullYear();
		
		if (checkOutDate < checkInDate) {
			$('#checkout').val(newDay+"/"+newMonth+"/"+newYear);
			$('#checkout_day'  ).val(newDay);
			$('#checkout_month').val(newMonth);
			$('#checkout_year' ).val(newYear);
		}
	}
}

function init_Guarantee()
{
	$("#guarantee-target").ezpz_tooltip({
		contentId: 'guarantee-content',
		showContent: function(content) {
			content.fadeIn('fast');
		},
		hideContent: function(content) {
			content.stop(true, true).hide();
		},
		offset: 0,
		contentPosition : 'belowRightFollow'
	});
}

// Table Row Colours:
function init_TableRowColours() {
	$('table.zebra tr:even').addClass('alt');
}



// ======================================================================================================= //
/* Homepage Functionality */
// ======================================================================================================= //

function init_Homepage_Apartment_Slider()
{	
	$('.apt-list a.1').addClass('selected');
	$(".hp-sector").jCarouselLite({
			btnGo:		[".1",".2",".3",".4",".5",".6",".7",".8",".9"],
			auto:		4000,
			speed:		400,
			vertical:	true,
			visible:	1,
			ul:			"ul.slider",
			li:			"li.apt-detail",
			afterEnd: function(slideshow) {
				$('.apt-list a').removeClass('selected');
				var theList = $("ul.slider").find('>li');
				var listLength = theList.size() - 1;
				var listNum = theList.index(slideshow[0]);
				if (listNum >= listLength) { listNum = 1 };
				$('ul.apt-list>li:nth-child('+listNum+') a').addClass('selected');
			}
	});
}


// ======================================================================================================= //
/* Results Table Functionality */
// ======================================================================================================= //

function init_Results_Table()
{	
	sortTable();
	rowHover();
	
	// Set form fields to update the table on change:
	/*
	$("#sleeps").change(function() {
		$("#type").val('');
		$("#building").val('');
		updateTable();
	});
	$("#building").change(function() {
		$("#type").val('');
		$("#sleeps").val('7');
		updateTable();
	});
	$("#type").change(function() {
		$("#sleeps").val('7');
		$("#building").val('');
		updateTable();
	});
	*/
	
	// Hide the 'Search Again' button if Javascript is enabled, to force AJAX updates
	//$("#btn-refine").hide();
	
	init_Results_Popup();
	init_Quantity_Selectors();
	init_DailyRates_Popup();
	
}

function init_Quantity_Selectors()
{	
	$('input.book-selected').attr("disabled", "disabled");
	
	$('.quantity').change(function() {
		var myNum = $(this).attr('id').substring(8, 10);
		if($(this).val() != 0) {
			$('#book-selected'+myNum).removeAttr("disabled"); // To enable
		} else {
			$('#book-selected'+myNum).attr("disabled", "disabled"); // To disable 
		}
		var buttonsActive = $('.book-selected').not(":disabled");
		if (buttonsActive.length <= 1) {
			$('.book-selected').val('Book & Pay');
		} else {
			$('.book-selected').val('Book all & Pay');
		};
	});
	
}

function init_DailyRates_Popup() {
	$("a.daycost").click(function(){ return false; }).css('display:block');
	$("table.results div.daycost-matrix").clone().prependTo("div.container");
	$("table.results").remove("div.daycost-matrix");
	if(ie6) {
		$("div.container>div.daycost-matrix").bgIframe();	
	};
	$(".daycost").ezpz_tooltip({
		showContent: function(content) {
			content.fadeIn('fast');
		},
		hideContent: function(content) {
			content.stop(true, true).hide();
		},
		contentPosition : 'belowRightFollow'
	});
}

function rowHover()
{	
	$("table.results tbody tr").hover(
		function()
		{
			$(this).addClass("rollover");
		},
		function()
		{
			$(this).removeClass("rollover");
		}
	);	
}

function sortTable()
{	
	$("table.results").tablesorter({
		//sortList:[[3,0]], // this slows down IE6 massively, for an unknown reason.
		headers: { 4: { sorter: false }, 5: { sorter: false } },
		widgets: ['zebra'],
		textExtraction: 'complex'
	});
}


function updateTable()
{	
	var params = {
			sleeps		: $("#sleeps").val(),
			building	: $("#building").val(),
			type		: $("#type").val(),
			ajaxupdate	: 1
		};
	
	// Handler for response from database search
	var callback = function (data) {

		// Remove existing table rows and append returned results: -------------
		$("table.results tbody").empty('tr').append(data.tablerows);
		
		// Update zebra stripping/sorting on new rows: -------------------------
		if(data.num != 0) {
			$("table.results").trigger("update");
			$("table.results").trigger("sorton",[[[3,0]]]);
			rowHover();
		}
		
		// Update search criteria: ---------------------------------------------
		$("#criteria-num").text(data.num);
		var descType = "";
		
		if (data.type == "") {
			descType = "no preference on bedrooms";
		} else {
			descType = "a " + data.type;
		}
		
		var descBuilding = "";
		if (data.building == "") {
			descBuilding = "any of our apartment buildings";
		} else {
			descBuilding = "in " + data.building;
		}
		//$("#criteria-type").text(descType);
		//$("#criteria-building").text(descBuilding);
		
		// General tidy-up and restart: ---------------------------------------
		$(document).trigger('close.facebox'); // Close loading overlay
		init_Results_Popup(); // Init the facebox overlays for the new results
		init_Quantity_Selectors(); // Init the quantity select box updaters for the new results
		init_DailyRates_Popup();
		
	};
	
	$.facebox.settings.closeButton = false; // Loading overlay
	$.facebox({div : '#loader'}); // Loading overlay
	
	// Send AJAX request for new search criteria
	$.getJSON("resources/inc/results-table.php",params,callback);
		
}


function init_Results_Popup()
{
	$("a[rel*=facebox]").click(function (e) {
		e.preventDefault();
		var myApt = $(this).attr('title');
		$.get($(this).attr('href'), function(data){
			var response = $(data);
			
			var toLoad = response.find('#results-loader').html();
			$(toLoad).modal({
				opacity: 80,
				zIndex: 400,
				persist: true,
				containerCss: {
					width: 675,
					height: 535,
					backgroundColor: '#E0E0CB',
					border: '3px solid #fff',
					textAlign: 'left'
				},
				onShow: function() {
					init_MultiTabs();
					$("a.book-now").hide();
					init_Lightbox();
					
				},
				onOpen: function (dialog) {
					$('.header').css('z-index',0);
					dialog.overlay.fadeIn('normal', function () {
						dialog.container.slideDown('normal', function () {
							dialog.data.fadeIn('normal');
							dialog.container.prepend('<h4 class="modal-title">'+myApt+'</h4>');
						});
					});
					
					dialog.overlay.click(function (e) {
						e.preventDefault();
						dialog.overlay.unbind('click');
						$.modal.close();
						$('.header').css('z-index',200);
					});
				},
				onClose: function (dialog) {
					dialog.data.fadeOut('normal', function () {
						dialog.container.slideUp('normal', function () {
							dialog.overlay.fadeOut('normal', function () {
								dialog.overlay.unbind('click');
								$.modal.close();
								$('.header').css('z-index',200);
							});
						});
					});
				}
			});
		});
		return false;
	});
}


// ======================================================================================================= //
/* Landing Page Functionality */
// ======================================================================================================= //

function init_Accordion()
{
	$('.accordion p').hide();
	
	$('.accordion li a').click(
		function() {
			
			var checkLink = $(this);
			var checkElement = $(this).next();
			
			$('.accordion a').removeClass('selected');
			
			if((checkElement.is('p')) && (checkElement.is(':visible'))) {
				$('.accordion p:visible').slideUp('normal');
				return false;
			}
			
			if((checkElement.is('p')) && (!checkElement.is(':visible'))) {
				$('.accordion p:visible').slideUp('normal');
				checkElement.slideDown('normal');
				checkLink.addClass('selected');
				return false;
			}
			
			return false;
			
		}
		
	);
	
}

// Allows multiple sets of tabs on a page
function init_MultiTabs()
{
	var mapInited = 0;
	
	$("div.tab-region").each(
		function(intIndex) {
			
			var myTabContainers = $(this).find('div.tab-panel');
			var myTabs = $(this).find("ul.tabs");
			
			myTabs.show();
			$(this).find('div.tab-panel h3').hide();
			
			$(this).find('ul.tabs a').click(function () {
				myTabContainers.hide().filter(this.hash).show();
				$(this).parent().parent().find('a').removeClass('active');
				$(this).addClass('active');
				
				if ($(this).text() == "Location") {
					if (mapInited != 1) {
						/* 'markerlist' should be defined at the bottom of the html page */
						init_GoogleMap_Locations(markerList);
						mapInited = 1;
					}
				}
				
				return false;
			}).filter(':first').click();
			
		}
	);
	
}


function googleMap_Create_Locations(markerList)
{
	
	var locMarkerDetails = new Array();
	
	locMarkerDetails[0] = new Array();
	locMarkerDetails[0].code		= "mount-pleasant";
	locMarkerDetails[0].lat			= 53.404671;
	locMarkerDetails[0].lng			= -2.976458;
	locMarkerDetails[0].bubbletext	= "<p><strong>Mount Pleasant Apartments</strong><br>Duke Street,<br>Liverpool L3 5TF.</p>";
	
	locMarkerDetails[1] = new Array();
	locMarkerDetails[1].code		= "lever-court";
	locMarkerDetails[1].lat			= 53.402304;
	locMarkerDetails[1].lng			= -2.983732;
	locMarkerDetails[1].bubbletext	= "<p><strong>Lever Court Apartments</strong><br>Duke Street,<br>Liverpool L3 5TF.</p>";
	
	return locMarkerDetails;
	
}


function init_GoogleMap_Locations(markerList)
{
	var locMarkerDetails = googleMap_Create_Locations();
	
	if (GBrowserIsCompatible()) {
		
		//Basic Setup:
		var map = new GMap2(document.getElementById("map-contact"));
		map.setCenter(new GLatLng(53.404671,-2.976458), 14);
		
		// Controls:
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		
		// Marker:
		function createMarker(point,iconColor,html) {
			var baseIcon = new GIcon(G_DEFAULT_ICON);
			baseIcon.image = "images/utility/mapmarkers/marker-"+iconColor+".png";
			var marker = new GMarker(point,{icon:baseIcon});
				GEvent.addListener(marker, "click", function() {
					marker.openInfoWindowHtml(html);
			});
			return marker;
		}
		
		// To make a single marker with no icon:
		//var point = new GLatLng(53.344454, -6.277270);
		//var marker = createMarker(point,'blue','<p></p>');
		//map.addOverlay(marker);
		
		// Create custom marker:
		function createLetterMarker(point,index,html) {
			var baseIcon = new GIcon();
			baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
			baseIcon.iconSize = new GSize(20, 34);
			baseIcon.shadowSize = new GSize(37, 34);
			baseIcon.iconAnchor = new GPoint(9, 34);
			baseIcon.infoWindowAnchor = new GPoint(9, 2);
			baseIcon.infoShadowAnchor = new GPoint(18, 25);
			var letter = String.fromCharCode("A".charCodeAt(0) + index);
			var letteredIcon = new GIcon(baseIcon);
			letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
			markerOptions = { icon:letteredIcon };
			var marker = new GMarker(point, markerOptions);
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(html);
			});
			return marker;
		}
		
		// Match predefined locations with those requested and create a custom marker:
		var k = 0;
		for (var i = 0; i < markerList.length; i++)
		{
			for (var j in locMarkerDetails)
			{
				if(locMarkerDetails[j].code == markerList[i])
				{
					var point = new GLatLng(locMarkerDetails[j].lat, locMarkerDetails[j].lng);
					var marker = createLetterMarker(point,k,locMarkerDetails[j].bubbletext);
					map.addOverlay(marker);
					k++;
				}
			}
		}
		
	}
	
	$(document.body).unload(function() {
		if (GBrowserIsCompatible()) {
			GUnload();
		}
	});
	
}


function init_GoogleMap_Locations_Aug() {

	if (GBrowserIsCompatible()) {
		
		//Basic Setup:
		var map = new GMap2(document.getElementById("map-contact"));
		map.setCenter(new GLatLng(53.404671,-2.976458), 14);
		
		// Controls:
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		
		// Marker:
		function createMarker(point,iconColor,html) {
			var baseIcon = new GIcon(G_DEFAULT_ICON);
			baseIcon.image = "images/utility/mapmarkers/marker-"+iconColor+".png";
			var marker = new GMarker(point,{icon:baseIcon});
				GEvent.addListener(marker, "click", function() {
					marker.openInfoWindowHtml(html);
			});
			return marker;
		}
		
		function createLetterMarker(point,index,html) {
			var baseIcon = new GIcon();
			baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
			baseIcon.iconSize = new GSize(20, 34);
			baseIcon.shadowSize = new GSize(37, 34);
			baseIcon.iconAnchor = new GPoint(9, 34);
			baseIcon.infoWindowAnchor = new GPoint(9, 2);
			baseIcon.infoShadowAnchor = new GPoint(18, 25);
			var letter = String.fromCharCode("A".charCodeAt(0) + index);
			var letteredIcon = new GIcon(baseIcon);
			letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
			markerOptions = { icon:letteredIcon };
			var marker = new GMarker(point, markerOptions);
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(html);
			});
			return marker;
		}
	
		//var point = new GLatLng(53.344454, -6.277270);
		//var marker = createMarker(point,'blue','<p></p>');
		//map.addOverlay(marker);
		
		//var point = new GLatLng(53.48105,-2.22834);
		//var marker = createLetterMarker(point,0,'<p><strong>Augustine Apartments</strong><br>42-76 St. Augustine Street, Dublin 8.</p>');
		//map.addOverlay(marker);
		
	}
	
	$(document.body).unload(function() {
		if (GBrowserIsCompatible()) {
			GUnload();
		}
	});
	
}


function init_FAQ()
{
	$('.faq-accordion div.answer').hide();
	
	$('.faq-accordion li a').click(
		function() {
			
			var checkLink = $(this);
			var checkElement = $(this).next();
			
			$('.faq-accordion a').removeClass('selected');
			
			if((checkElement.is('div')) && (checkElement.is(':visible'))) {
				$('.faq-accordion div:visible').slideUp('normal');
				return false;
			}
			
			if((checkElement.is('div')) && (!checkElement.is(':visible'))) {
				$('.faq-accordion div:visible').slideUp('normal');
				checkElement.slideDown('normal');
				checkLink.addClass('selected');
				return false;
			}
			
			return false;
			
		}
		
	);
	
}