$(document).ready(function(){

		/************************* global inits *********************/

	  	SwapImage.rollover.init();
		iHelper($('#supplierUsername'));
		initPasswordInputs();
		
		
		keypressDelay = 100;
		minCharLength = 2;
		currentCharLength = 0;
		listShowing = false;
		locInput = $('#loc');
		typeInput = $('#types');
		//Note there is one suggestedLocationss hard coded below rather than using this.
		suggestedLocations = $('#suggestedLocationss');
		initialVal = locInput.attr('initiall');
		locInput.val(initialVal);
		plusOneVal = locInput.attr('plusOne');
		locTagsArray = new Array();
		typeTagsArray = new Array();
		// this var gets changed all the time, relies on those two above
		initialValScratch = initialVal;
		// kill is for stopping the keyup event if certain keys have been pressed
		kill = false;
		// Page first load
		firstLoad = true;
		
////////// Events


// SEARCH FORM

if($('#suggestedLocationss').length) {
	
	searchForm.init();
	searchForm.inputHelper(locInput);
	
	
	//SCROLL TO TOP HOMEPAGE	
	
	$('#helpArrow').css('opacity', '0');
	
	function fireArrow(theEl) {
		theEl.animate({opacity: 1}, {queue:false, duration: 300}).animate({left: "-60px"}, {queue:false, duration: 900});
		
		setTimeout(function(){
			theEl.animate({opacity: 0}, {queue:false, duration: 400});
				
		}, 600);
		
		theEl.css('left', '-100px');
		return false;
	}
	
	
	$('#homeSearchFor').click(function(e) {
	  	$('html, body').animate({
		scrollTop: $("#homeForm").offset().top-380
		}, 1000, function() {
			fireArrow($('#helpArrow'));
		});
		e.preventDefault();
		return false;
			   
	});
	
	
}


/****************************************** other functions ***************************************/

// price popups for results

if($('.result').length) {
	$thePriceHover = $('<div>').attr({id: "priceHover"}).hide();
	
	$('#content').prepend($thePriceHover);
	
	
	$('.rTags li a').hover(function() {
		var price = $(this).data('price');
		$thePriceHover.removeClass('priceHoverLarge');
		if(price == "") {
			$thePriceHover.addClass('priceHoverLarge').html("<p>Please enquire<br />for rates</p>").css({top: Math.round($(this).position().top-73)+"px", left: Math.round($(this).position().left+(($(this).outerWidth() / 2) - 58))+"px"}).stop(true, true).fadeIn(200);
			
		} else {
			$thePriceHover.html("from <span>" + price + "</span> per night").css({top: Math.round($(this).position().top-73)+"px", left: Math.round($(this).position().left+(($(this).outerWidth() / 2) - 40))+"px"}).stop(true, true).fadeIn(200);			
		}
		
		
		
	}, function() {
		$thePriceHover.stop(true, true).fadeOut(500, function() {
		});

	}).click(function() {
		return false;
	});
}	


// internal show / hide functionality

	if($('#innerFormWrap').length) {
		jInnerFormWrap = $('#innerFormWrap');
		
		function showTheForm() {
			if(!jInnerFormWrap.is(':visible')) {
				
				jInnerFormWrap.slideDown(250);
				$('#searchTop').removeClass('searchTopBorder');
				$('#refine').html('Close Search Box').addClass('searchTopClose');
				return false;
			} else {				
				jInnerFormWrap.slideUp('fast');
				$('#searchTop').addClass('searchTopBorder');
				$('#refine').html('Click here to refine your search').removeClass('searchTopClose');
				return false;
			}
		}
		
		
		jInnerFormWrap.hide();

		$('#refine').click(function() {
				showTheForm();
		});
		
		$('#youCan a').click(function(e) {
			if($('body').scrollTop() != 0) {
				$('body').animate({
				scrollTop: 0
				}, 600, function() {
					showTheForm();

				});
			} else {
				showTheForm();
				
			}

			
			e.preventDefault();
		})
		


	}
	
	
//OVERLAY

if($('#overlay').length) {
	showing = false;
	hoverLay = false;
	firstLoad = true;
	
	
	function bindOverlayEvents() {
		$('#oClose').click(function() {
	        $('#overlay').fadeOut('fast');
	        showing = false;
	        return false;
	    });

		$('#intWrap input').change(function() {

			if($(this).next().hasClass('selected')) {
				$(this).next().removeClass('selected')
			} else {
				$(this).next().addClass('selected');
			}
		});
		
		if($('#StartDate').length) {
			$('#StartDate, #EndDate').datepicker({
	            dateFormat: 'dd/mm/yy'
	        });
		}


		$('#oSubmit').click(function(event) {
			validateForm.validate(event);
			
		});
	}


	function overlay(theEl) {
		var oDebug = false;
		var urlLoc;
		
		if(!oDebug) {
			urlLoc = $('#overlay').attr("url");
		} else {
			urlLoc = "/cleanHTML/formData/apartmentContact.html"
		}
		
		
	    if(showing) {
	        $('#overlay').fadeOut('fast');
	        showing = false;
	    } else {
			if(firstLoad) {
				$('#oWhite').addClass('oLoading');
				$('#oWhite').css('marginTop', $(document).scrollTop()+40 + "px");        
		        $('#overlay').fadeIn('fast');

				$.ajax({
				    url: urlLoc,
				  	cache: false,
					data: {formType: theEl.attr('rFormType')},
				  	success: function(html){
					$('#oWhite').removeClass('oLoading').html(html);
					SwapImage.rollover.init();
					bindOverlayEvents()
				  	validateForm.init();
					_enhanceForm.init();
				  }
				});
		        showing = true;
				firstLoad = false;
				
			} else {
				$('#oWhite').css('marginTop', $(document).scrollTop()+40 + "px");        
		        $('#overlay').fadeIn('fast');
		        showing = true;
			}
		

	    }
	}
	
    $('#overlay').hide().height($(document).height()).addClass('overlayWithJs');


    
    $('#oWhite').hover(function() {
        hoverLay = true;
    }, function() {
	// if statement is fix for Chrome 9.x
		if(event.target == this) {
			hoverLay = false;
			
		}
    });
    
    $('#overlay').click(function() {
        if(!hoverLay) {
            $('#overlay').fadeOut('fast');
            showing = false;
            return false;
        }
    });
	
    $('.overlayTrigger').click(function() {
       overlay($(this)); 
       return false;
    });

}



validateForm = function() {

	function init() {
		$('#oSubmit').before('<div id="formErrors"><p>Please fill out the following required fields above:</p><ul></ul></div>');
		$('#formErrors').hide();
	}
	
	function validate(theEvent) {
		$('#formErrors').hide();
		theEvent.preventDefault();
		
		var theFields = "";
		var notValid = false;
		$('#overlay .required').each(function() {
			var theId = $(this).attr('for');
			var theVal = $("#"+theId).val();
			if(theVal == "" || theVal == "Please Select...") {
				notValid = true;
				theFields += "<li>" + $(this).html() + "</li>";
			}
		});
		
		if(notValid) {
			$('#formErrors ul').html(theFields).parent().slideDown('fast');
		} else {
			_enhanceForm.submitLoader();
			$('#overlay form').submit();
		}
	}

	return {
		init: init,
		validate: validate
	}
	
}();

_enhanceForm = function() {
	
	function init() {
		$('#pleaseWait').hide();
	//	contactPref();
	}
	
	function submitLoader() {
		$('#oSubmit').css({opacity: 0.4, cursor: "default"}).unbind().click(function() {
			return false;
		});
		$('#pleaseWait').show();
	}
	
	function contactPref() {
		// bind elements
		var elContactNumber = $('#ContactNumber');
		var elContactNumberLabel = $('label[for="ContactNumber"]');
		var	requiredHTML = '<span class="red">*</span>';

		// hide contact box initially
		$(elContactNumber).hide();
		$(elContactNumberLabel).hide();
		
		
		// bind handlers
		$('#oEmail,#oTelephone').change(function() {
			if($('#oEmail').attr('checked') == true) {
				if($(elContactNumber).is(':visible')) {
					$(elContactNumber).slideUp('fast');
					$(elContactNumberLabel).removeClass('required').slideUp('fast').children('span').remove();
				}
			}
			 else{
				if(!$(elContactNumber).is(':visible')) {
					$(elContactNumber).slideDown('fast');
					$(elContactNumberLabel).addClass('required').append(requiredHTML).slideDown('fast');
				}
			}
		});
	}
	
	return {
		init: init,
		submitLoader : submitLoader
	}
}();


/////////////////////////////////// SEARCH FORM FUNCTIONs ////////////////////////////////////////



// prices per night selector

if($('#pricesPerNight').length) {
	
	theTable = $('#pPNTableWrap');
	
	$('#nightsStay').hide();
	
	$('#nightsTrigger a').click(function() {
		$('#nightsStay').show();
		$(this).parent().hide();
		return false;
	});
	
	$('#nightsStay').change(function() {
		theTable.addClass('pLoader').children('table').children('tbody').children('tr').remove();
		theVal = $(this).val();
		theText = $(this).children("option:selected").text();
		theApartmentId = $(this).attr("apartmentId");
		$.getJSON("/httphandlers/apartmenttypeprices.ashx", { apartmentid: theApartmentId, priceperiod: theVal }, function(json, worked) {
			
			if(worked == "success") {
				
				for (var i=0; i < json.length; i++) {
					var theEl = $('<tr>');
					var theElHTML = $('<td>'+json[i][0]+'</td><td>'+json[i][1]+'</td>');
					theEl.html(theElHTML);

					theTable.children('table').append(theEl);

				};
				theTable.removeClass('pLoader');
				$('#nightsStay').hide();
				$('#nightsTrigger').children('span').html(theText).end().show();
			}
			

		
		});
		
	});
	
}

/////////////////////////////////// CLOCK ////////////////////////////////////////


Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getUTCFullYear(), 0, 1);
var jul = new Date(this.getUTCFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}

var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var jsonLoaded = false;
var cTime;
var openingTime;
var closingTime;
var status = "";

// Get the proper time initially
if ($('.oCTime').length > 0) $.getJSON("http://json-time.appspot.com/time.json?tz=Europe/London&callback=?", updateTimeJSON);

function updateTime() {
	
/*	if(cTime < openingTime || cTime > closingTime || cTime.getDay() == 0 || cTime.getDay() == 6) {
		if (status != "Closed") {
			status = "Closed";
			$('.oC').html(status).addClass('closed');
		}
	} else if (status != "Open") {
		status = "Open";
		$('.oC').html(status).removeClass('closed');
	} */
	
	$('.oCTime').html(leadingZero(cTime.getHours()) + ":" + leadingZero(cTime.getMinutes()) + ":" + leadingZero(cTime.getSeconds()));
	$('.OCDate').html(cTime.getDate() + " " + months[cTime.getMonth()] + " " + cTime.getFullYear());
	
}

function updateTimeJSON(data) {
	
	// remove hours changer thing
	strcTime = data.datetime;
	patt = /[\+\-]\d{3,6}/; 
	strcTime = strcTime.replace(patt, "");
	cTime = new Date(strcTime);	
	
	openingTime = new Date(strcTime);
	closingTime = new Date(strcTime);
	
	openingTime.setHours(9,0,0,0);
	closingTime.setHours(17,30,0,0);
	
	updateTime();
	
	// If this is the first load, set the local time counter going
	if (!jsonLoaded) {
		
		// If it's daylight saving time, show that
		if (cTime.dst) $('.oCDST').html('GMT+1');
		
		jsonLoaded = true;
		setInterval(function() {
			
			
			cTime.setTime(cTime.getTime() + 1000);
			updateTime();
			
		}, 1000);
		
	}
	
}

function leadingZero(num) {
	if (num < 10) return '0' + num;
	return String(num);
}

// generic input helper

function iHelper(theInput) {
	if(theInput.is('textarea')) {
		var orig = theInput.attr('title');	
		$(this).html(orig);			

		 theInput.focus(function() {
	        if($(this).html() == orig) {
	            $(this).html('');
	        } 
	     }).blur(function() {
	         if($(this).html() == "") {
	             $(this).html(orig);
	         }
	     });
	} else {
		var orig = theInput.attr('title');
		theInput.val(orig);			
	     theInput.focus(function() {
	        if($(this).val() == orig) {
	            $(this).val('');
	        } 
	     }).blur(function() {
	         if($(this).val() == "") {
	             $(this).val(orig);
	         }
	     });
	}

}

function initPasswordInputs() {
    
    $('input[type="password"]').each(function() {
        
        var cInput = $(this).hide().blur(inputBlur);
        
        var cDummy = $('<input type="text" />').attr({ 
            'title': cInput.attr('title'), 
            'class': cInput.attr('class') + ' default', 
            'value': cInput.attr('title') }).focus(dummyFocus).insertAfter(cInput);
        
        function dummyFocus() {
            $(this).hide();
            cInput.show().focus();
        }
        
        function inputBlur() {
            if ($(this).val() == '') {
                $(this).hide();
                cDummy.show();
            }
        }
        
    });
    
}


iHelper($('#reference'));

/////////////////////////////////// CONTACT PAGE  ////////////////////////////////////////

if($('#loginRight').length) {
	loginMores = $('#loginRight .loginMore');
	loginMores.hide();
	
	if($('#loginWhichTwo').is(':checked')) {
		loginMores.show();
	}
	$('#loginWhichOne, #loginWhichTwo').change(function() {
		if($('#loginWhichOne').is(':checked')) {
			loginMores.slideUp('fast');
		} else {
			loginMores.slideDown('fast');
			
		}
	});
}

/////////////////////////////////// APARTMENT DETAILS PAGE  ////////////////////////////////////////

if($('.fBlock').length) {
	

	apartmentFeatures.init();
	

}

/////////////////////////////////// SUPPLIER EDIT  ////////////////////////////////////////


if($('.suppLeft').length) {
	
	function confirmIt(theMessage) {
		return confirm(theMessage);
	}


	$('.deleteConfirm').click(function() {
		return confirmIt("Please confirm deletion of selected items");
		
	});
	
	$('.cancelConfirm').click(function(){
		return confirmIt("Please confirm you would like to reset your changes")
	})
	
	$('.saveConfirm').click(function(){
		return confirmIt("Please confirm you would like to make these changes")
	})
}

/////////////////////////////////// HOMEPAGE  ////////////////////////////////////////

if($('#homeTabs').length) {
	_homepage.init();
}


});

// END DOCUMENT READY	

config = {
	slideshow: {
		fadeUp: 0.6,
		fadeHover: 0.9,
		loaderOpacity: 0.6
	},
	
	homepage: {
		
		slideshow: {
			slideDuration: 6000,
			fadeSpeed: 1000,
			slides: [
			"/assets/images/homepageSlides/UkServicedApartments.jpg",
			"/assets/images/homepageSlides/independantAndUnbiased.jpg",
			"/assets/images/homepageSlides/bestAccommodation.jpg"
			]
		}
	}
}

// Search form 

searchForm = function() {
	
	var firstLocation = true,
	firstType = true,
	allowTypeTagCreation = false,
	timeOutID = 0;
	
	// init
	
	function init() {
		
		// create the match list and inset into DOM
		matchList = $('<ul>').attr({id: 'pList'}).hide();
		$('#homeForm').append(matchList);
		
		flushSuggestedLocations();
		

		// sets the new current char length correctly
		currentCharLength = locInput.val().length;
		
		// PREPOPULATE FORM IF HIDDEN INPUTS HAVE VALUES SET

		if($('#submitLocs').length) {
			if($('#submitLocs').val() != "") {
				preLocs = new Array();
				preLocsString = $('#submitLocs').val();
				preLocs = preLocsString.split(',');

				preLocIDs = new Array();
				preLocIDsString = $('#submitLocs').attr('locIDs');
				preLocIDs = preLocIDsString.split(',');

				// set the locTagsArray (used by all the other stuff) to math the prepopulated list.
				locTagsArray = preLocIDs;

				
				//prepare form...
				
				//if there is only one tag...				
				if(preLocs.length == 1) {
					locInput.val(preLocs[0]);
					activateStartTag($('#nLocTags .startTag'));
					firstLocation = false;
					getSuggestedLocations(preLocIDs[0]);

				} else {
					for (var i=0; i < preLocs.length; i++) {
						$('#nLocTags').prepend(buildTag(preLocs[i], preLocIDs[i]));
					};
					$('#nLocTags .startTag').hide();
					firstLocation = false;
					locInput.val(plusOneVal);
					initialValScratch = plusOneVal;
					inputHelper(locInput);
				}
			}

			if($('#submitTypes').val() != "") {
				preTypes = new Array();
				preTypesString = $('#submitTypes').val();
				preTypes = preTypesString.split(',');

				preTypeIDs = new Array();
				preTypeIDsString = $('#submitTypes').attr('typeIDs');
				preTypeIDs = preTypeIDsString.split(',');

				// set the typeTagsArray (used by all the other stuff) to math the prepopulated list.
				typeTagsArray = preTypeIDs;
				
				//prepare form...
				firstType = false;
				
				
				//if there is only one tag...				
				if(preTypes.length == 1) {
					//console.log(preTypeIDs[0]);
					activateStartTag($('#nTypeTags .startTag'));
					$('#types').children('option[value=' + preTypeIDs[0] + ']').attr('selected', 'selected');

				} else {
					for (var i=0; i < preTypes.length; i++) {
						$('#nTypeTags').prepend(buildTag(preTypes[i], preTypeIDs[i]));
					};
					$('#nTypeTags .startTag').hide();
					allowTypeTagCreation = true;
				}


			}
		}
		
		bindEvents();
	}
	
	function bindEvents() {
		
		$('#nLocTags .startTagActive').live('mouseenter', function() {
			$(this).css({backgroundColor: "#610608"});
		}).live('mouseleave', function() {
			$(this).css({backgroundColor: "#83171a"});
			
		}).live('click', function() {
			searchForm.animateFirstTag($(this));
		});
		
		$('#nTypeTags .startTagActive').live('mouseenter', function() {
			$(this).css({backgroundColor: "#610608"});
		}).live('mouseleave', function() {
			$(this).css({backgroundColor: "#83171a"});
			
		}).live('click', function() {
			firstTypeTag($(this));
		});
		

		locInput.keydown(function(e) {
			kill = false;
			// enter key...
			if(e.keyCode == 13) {

				kill = true;
				topResult = matchList.children('li.hover');
				searchForm.createTag(topResult, true);
				return false;
			}
			//tab key
			if(e.keyCode == 9) {
				kill = true;
				topResult = matchList.children('li.hover');
				searchForm.createTag(topResult, true);
				return true;
			}

			// down arrow...
			if(e.keyCode == 40) {
				kill = true;

				currentlySelected = matchList.children('li.hover');
				if(currentlySelected.next().length) {
					currentlySelected.removeClass('hover').next().addClass('hover');

				}
			}

			// up key
			if(e.keyCode == 38) {
				kill = true;

				currentlySelected = matchList.children('li.hover');
				if(currentlySelected.prev().length) {
					currentlySelected.removeClass('hover').prev().addClass('hover');

				}
			}
			
			// left + right keys
			
			if(e.keyCode == 37 || e.keyCode == 39) {
				kill = true;
			}	
		});

		// key up for the locations input	
		locInput.keyup(function() {
			if(firstLoad) {
				firstLoad = false;
			} else {
				// if it wasn't one of the special bound keys in the handler above...
				if(!kill) {
					// if it was the first location to be entered, reset the locTagsArray immediately
					if(locTagsArray.length == 1) {
						
						if($('#nLocTags .startTag').is(':visible')) {
							resetLocations();
							flushSuggestedLocations();
						}
					}
					var tempLength = $(this).val().length;
					// if the character length is 2 or more...
					if(tempLength >= minCharLength) {	
						//if there is already a list showing and the user has added more letters to their input string....
						if(listShowing && tempLength > currentCharLength) {
							// just highlight the text and don't bother with another request
							searchForm.highlightText($(this).val());
						} else {
							// asks if keyup event isn't followed by another one before the set delay. Designed to prevent too many requests - fast typing.
							searchForm.requestSafe($(this).val(), tempLength);
						}
					} else {
						matchList.fadeOut('fast');
						listShowing = false;

					} 

				} 
			}

		}).blur(function() {
			matchList.fadeOut('fast');
			listShowing = false;
		}); 



		// location tag clicks
		$('#nLocTags .nTag .nTagRight span').live('click', function() {

			//if its the last one, get rid of the suggested locations list		
			if(locTagsArray.length == 1) {
				searchForm.flushSuggestedLocations();
				initialValScratch = initialVal;
				locInput.val(initialVal);
				searchForm.inputHelper(locInput);
				firstLocation = true;
				deactivateStartTag($('#nLocTags .startTag'));
				
			}

			for (var i=0; i < locTagsArray.length; i++) {
				if(locTagsArray[i] == $(this).parent().parent().attr('data-location-id')) {
					locTagsArray.splice(i,1);
				}
			};
			$(this).parent().parent().remove();
		});

		// TYPE TAGS CLICK
		$('#nTypeTags .nTag .nTagRight span').live('click', function() {
			var typeID = $(this).parent().parent().attr('data-location-id');
			
			// if its the last one...
			if(typeTagsArray.length == 1) {
				$(this).children('option:first').attr('selected', 'selected');
				firstType = true;
				allowTypeTagCreation = false;
				
				deactivateStartTag($('#nTypeTags .startTag'));
			}
			
			for (var i=0; i < typeTagsArray.length; i++) {
				if(typeTagsArray[i] == typeID) {
					typeTagsArray.splice(i,1);
				}
			};
			$(this).parent().parent().remove();
			
		});

		// TYPE SELECT CHANGE
		$('#types').change(function() {
			// if its not the first option...
			if($(this).children('option:selected').index() != 0) {
				
				if(firstType) {
					typeTagsArray[0] = $(this).val();
					activateStartTag($('#nTypeTags .startTag'));
					firstType = false;

				} else {
					// checks if the start tag has been clicked for additional types to be allowed
					if(allowTypeTagCreation) {
						createTypeTag($(this));
					} else {
						typeTagsArray[0] = $(this).val();
					}
				}
				
			}
		}).focus(function() {
			$(this).addClass('focus');
		}).blur(function() {
			$(this).removeClass('focus');
		});	

		//SUGGESTED LOCATIONS CLICK
		$('#suggestedLocationss ul li a').live('click', function() {
			var createIt = true;
			var newTagID = $(this).parent().attr("theID");
			var newTagInner = $(this).html();

			// checks if the location is already within the created tags
			for (var i=0; i < locTagsArray.length; i++) {
				if(locTagsArray[i] == newTagID) {
					createIt = false;
				}
			};

			if(createIt) {
				locTagsArray[locTagsArray.length] = newTagID;

				$('#nLocTags').prepend(buildTag(newTagInner, newTagID));
				
				$(this).remove();
			}

		});

		//SUBMIT BUTTON	

		$('#submit').click(function() {
			$('#submitLocs').val(locTagsArray);
			$('#submitTypes').val(typeTagsArray);
			return true;
		});
	}
	


	function inputHelper(theInput) {
		var orig = initialValScratch;			
	     theInput.unbind('focus').unbind('blur').focus(function() {
	        if($(this).val() == orig) {
	            $(this).val('');
	        } 
	     }).blur(function() {
	         if($(this).val() == "") {
	             $(this).val(orig);
	         }
	     });
	} 

	function animateFirstTag(el) {
		locInput.animate({ color: "white" }, 500, function() {
			el.hide();
			$('#nLocTags').append(buildTag(locInput.val(), locTagsArray[0]));
			initialValScratch = plusOneVal;
			inputHelper(locInput);
			setTimeout(function() {
				locInput.css("color", "#4a4a4a")
						.val(plusOneVal)
						.animate({ color: "#b9b9b9" }, 200)
						.animate({ color: "#4a4a4a" }, 200)
						.animate({ color: "#b9b9b9" }, 200)
						.animate({ color: "#4a4a4a" }, 200);
			}, 330);

		});
	}
	
	function firstTypeTag(el) {
		el.hide();
		allowTypeTagCreation = true;
		$('#nTypeTags').append(buildTag($('#types :selected').text(), typeTagsArray[0]));
		$('#types').children('option:first').attr('selected', 'selected');
	}

	function tagSuccess(theVal, newInitial) {
		locInput.val(theVal).animate({ color: "white" }, 700, function() {
			locInput.css("color", "#4a4a4a").val(newInitial);
		});
	}

	function resetLocations() {
		$('#nLocTags .startTags').show();
		deactivateStartTag($('#nLocTags .startTag'));
		locTagsArray.length = 0;
		initialValScratch = initialVal;
		inputHelper(locInput);
		firstLocation = true;
	}

	function activateStartTag(el) {
		var fadeTime = 500;
		setTimeout(function() {
			el.addClass('startTagActive')
			.animate({ backgroundColor: "#83171a"}, {duration: fadeTime, queue: false })
			.animate({ color: "#fff"}, {duration: fadeTime, queue: false})
			.animate({ borderLeftColor: "#cb3a3e"}, {duration: fadeTime, queue: false})
			.animate({ borderRightColor: "#cb3a3e"}, {duration: fadeTime, queue: false})
			.animate({ borderBottomColor: "#cb3a3e"}, {duration: fadeTime, queue: false})
			.animate({ borderTopColor: "#cb3a3e"}, {duration: fadeTime, queue: false});
		}, 330);
	}
	
	function deactivateStartTag(el) {
		var fadeTime = 10;
		el.removeClass('startTagActive')
		.animate({ backgroundColor: "#921a1d"}, {duration: fadeTime, queue: false })
		.animate({ color: "#b76062"}, {duration: fadeTime, queue: false})
		.animate({ borderLeftColor: "#a72428"}, {duration: fadeTime, queue: false})
		.animate({ borderRightColor: "#a72428"}, {duration: fadeTime, queue: false})
		.animate({ borderBottomColor: "#a72428"}, {duration: fadeTime, queue: false})
		.animate({ borderTopColor: "#a72428"}, {duration: fadeTime, queue: false})
		.fadeIn(200);
	}

	function createTag(theEl, wasKeyEvent) {
		
		var createIt = true;
		var newTagInner = theEl.children('span').html();
		var newTagID = theEl.attr('theID');
		newTagInner = newTagInner.replace(/<b>/i, "").replace(/<\/b>/i, "");
		strNewTagID = theEl.attr('theId');

		matchList.fadeOut('fast');
		listShowing = false;
		
		if(firstLocation) {
			locTagsArray[locTagsArray.length] = strNewTagID;			
			locInput.val(newTagInner);
			activateStartTag($('#nLocTags .startTag'));
			firstLocation = false;
			searchForm.getSuggestedLocations(strNewTagID);
			
			
		} else {
			// checks to see if the to-be-created tag already exists in the locTags array. If it does, dont add it again.
			for (var i=0; i < locTagsArray.length; i++) {
				if(newTagID == locTagsArray[i]) {
					createIt = false;
				}
			};

			if(createIt) {
				locTagsArray[locTagsArray.length] = strNewTagID;
				$('#nLocTags').append(buildTag(newTagInner, strNewTagID));

			}

			// if it was a key event that made the new tag, set the default value in the input to nothing
			if(!wasKeyEvent) {
				searchForm.tagSuccess(newTagInner, initialValScratch);
			} else {
				searchForm.tagSuccess(newTagInner, "");
			}
			// reset the 'input helper' with the new text
			searchForm.inputHelper(locInput);
		}

	}
	
	function buildTag(newTagInner, strNewTagID) {
		var newTag = [];
		var j = 0;
		newTag[j++] = '<div class="nTagLeft">';
		newTag[j++] = newTagInner;
		newTag[j++] = '</div><div class="nTagRight"><span><!-- --></span></div>';
		var newTagWrap = $('<div>').addClass('nTag').addClass('clearfix').attr('data-location-id', strNewTagID).html(newTag.join(''));
		return newTagWrap;
	}

	function createTypeTag(el) {
		var createIt = true;
		var newTagInner = $('#types :selected').text();
		var typeID = el.val();
		

		// checks to see if the to-be-created tag already exists in the TypeTags array. If it does, dont add it again.
		for (var i=0; i < typeTagsArray.length; i++) {
			if(typeID == typeTagsArray[i]) {
				createIt = false;
			}
		};

		if(createIt) {
			typeTagsArray[typeTagsArray.length] = typeID;
			
			$('#nTypeTags').append(buildTag(newTagInner, typeID));
			el.children('option:first').attr('selected', 'selected');

		}
		
	}

	function flushSuggestedLocations() {
		suggestedLocations.hide().children('ul').children('li').remove();
	}

	function getSuggestedLocations(v) {
		var debug = false,
		suggestedLocationsURL;
		
		if (debug) {
			suggestedLocationsURL = "/cleanHTML/jsonSuggestedTwo.js";
		} else {
			suggestedLocationsURL = "/httphandlers/proximatelocationhandler.ashx";
		}
		suggestedLocations.show().children('ul').addClass('loading');

		$.getJSON(suggestedLocationsURL, {locationid: v}, function(json, worked){
			if(json.length >= 1) {
				for (var i=0; i < json.length; i++) {
					var sugg = $('<li>').attr("theID", json[i].theID);
					var suggInner = $('<a>').html(json[i].theMatch);
					sugg.html(suggInner);
					suggestedLocations.children('ul').append(sugg);
				};
				//if(suggestedLocations.children('ul').children('li').length) {
				//	suggestedLocations.show();
				//}
				suggestedLocations.children('ul').removeClass('loading');
			} else {
				suggestedLocations.children('ul').html('<li>None</li>').removeClass('loading');
			}

		});
	}


	function bindMatchListEvents() {
		matchList.children('li').click(function() {
			searchForm.createTag($(this), false);

		}).mouseenter(function() {
			$(this).addClass('hover');
		}).mouseleave(function() {
			$(this).removeClass('hover');
		});

	}

	function requestSafe(theString, tempLength) {
		clearTimeout ( timeOutID );
		timeOutID = setTimeout(function(){callList(theString, tempLength);}, keypressDelay);
	}

	// takes the string from the input, and finds matches in the <span>s in the list items, and wraps those matches with bold tags.
	function highlightText(theString) {
		matchList.children('li').each(function() {
			
			theHTML = $(this).children().html().replace(/<b>/i, "").replace(/<\/b>/i, "");

			myregexp = new RegExp("("+theString+")", "i");
			//test if the user input string matches the span at all. If not, remove the element
			if(myregexp.test(theHTML)) {
				theHTML = theHTML.replace(myregexp, "<b>$1</b>" );
				$(this).children().html(theHTML);
			} else {
				if($(this).siblings().length == 0) {
					noMatch(matchList);
				}				
				$(this).remove();
			}

		});

		$('#locWrap').removeClass('pListLoad');
		currentCharLength = locInput.val().length;

	};

	function callList(theString, tempLength) {
		var debug = false;
		// if there is a minimum of {minCharLength} characters in the string, and if the length of the string has changed since the last test...
		if(tempLength >= minCharLength && tempLength != currentCharLength) {
			$('#locWrap').addClass('pListLoad');
			if(debug) {
				locationHandler = "/cleanHTML/jsonTestTwo.js";
			} else {
				locationHandler = "/httphandlers/locationhandler.ashx";
			}
			$.getJSON(locationHandler, { keyword: locInput.val() }, function(json, worked) {
				matchList.html('').fadeIn('fast');
				
				$('#locWrap').removeClass('pListLoad');

				if(json.matches.match.length > 0) {
					var theFirstItem = true;
					for (var i=0; i < json.matches.match.length; i++) {

						var newSpan = $('<span>').html(json.matches.match[i].theMatches[0]);
						var newEl = $('<li>').html(newSpan).attr("theId", json.matches.match[i].theId);

						if(theFirstItem) {
							newEl.addClass('hover');
							theFirstItem = false;
						} 

						for (var j=1; j < json.matches.match[i].theMatches.length; j++) {

							newEl.append(" - " + json.matches.match[i].theMatches[j]);
						};

						matchList.append(newEl);
						listShowing = true;
					}

					searchForm.bindMatchListEvents();
					searchForm.highlightText(theString);
				} else {
					noMatch(matchList);
				}

			});

		}

	}
	
	function noMatch(matchList) {
		matchList.append('<li id="noMatchFound"><b>No Match Found</b> - Please check your entry</li>');
	}
	
	return {
		init: init,
		inputHelper: inputHelper,
		tagSuccess: tagSuccess,
		createTag: createTag,
		createTypeTag: createTypeTag,
		flushSuggestedLocations: flushSuggestedLocations,
		getSuggestedLocations: getSuggestedLocations,
		bindMatchListEvents: bindMatchListEvents,
		requestSafe: requestSafe,
		highlightText: highlightText,
		callList: callList,
		animateFirstTag : animateFirstTag
	}
	
}();


_slideshow = function() {
	var $slideshow;
	var $slideshowImage;
	var $leftButton;
	var $rightButton;
	var $theButtons;
	var $loader;
	var $newImage;
	var $initBar;
	var $coverImage = $('<img>').css({opacity: 0});
	
	var imageArray = new Array();
	var imageArrayLength;
	var slideshowPosition = 1;
	var slideOver = false;
	var buttonsOver = false;
	

	function init(theImages) {

		// bind 
		$slideshow = $('#slideshow');		
		$slideshowImage = $slideshow.children('img');
		$newImage = $slideshowImage;
		$initBar = $('#initSlideBar');
		
		// insert coverImge
		$newImage.after($coverImage);
		
		// add buttons to DOM
		$leftButton = $('<span>').attr('id', 'picLeft').css('opacity', 0);
		$rightButton = $('<span>').attr('id', 'picRight').css('opacity', 0);
		
		$slideshow.append($leftButton);
		$slideshow.append($rightButton);
		
		$theButtons = $slideshow.children('span');
		
		//add loader
		$loader = $('<div>').attr('id', 'sLoader').css('opacity', 0);
		$slideshow.append($loader);
		
		// create image array
		var sImageString = theImages;
		imageArray = sImageString.split('{}');
		imageArray.unshift($slideshowImage.attr('src'));
		imageArrayLength = imageArray.length;
		
		//bind events
		bindEvents();
	}
	
	function nextImage() {
		$coverImage.attr('src', $newImage.attr('src')).css({opacity: 1});
		$loader.fadeTo(200, config.slideshow.loaderOpacity);
		
		if(slideshowPosition == imageArrayLength) {
			slideshowPosition = 1;
		} else {
			slideshowPosition += 1;
		}
		
		$newImage.attr('src', imageArray[slideshowPosition-1]).load(function() {
			$loader.stop(true).fadeTo(200, 0);
			$coverImage.stop(true).fadeTo(200, 0);
		});
	}
	
	function prevImage() {
		$coverImage.attr('src', $newImage.attr('src')).css({opacity: 1});
		$loader.fadeTo(200, config.slideshow.loaderOpacity);
		
		if(slideshowPosition == 1) {
			slideshowPosition = imageArrayLength;
		} else {
			slideshowPosition -= 1;
		}
		
		$newImage.attr('src', imageArray[slideshowPosition-1]).load(function() {
			$loader.stop(true).fadeTo(200, 0);
			$coverImage.stop(true).fadeTo(200, 0);
		});
		
		
	}


	
	function bindEvents() {	
		$slideshow.hover(function() {
			
			slideOver = true;
			// If user hovers onto the slideshow but not yet the buttons...
			if(!buttonsOver) {
				//fade both buttons up
				$theButtons.clearQueue().fadeTo(200, config.slideshow.fadeUp);
				$initBar.fadeOut(100);
			} else { 
				// don't fade up the hovered button (handled by the hover handler below) - just fade up the other one.
				$theButtons.not(event.target).clearQueue().fadeTo(200, config.slideshow.fadeUp);
			}
			
		}, function() {
			slideOver = false;
			$theButtons.clearQueue().fadeTo(200, 0);
			$initBar.fadeIn(100);
			
			
		});
		
		$theButtons.hover(function(event) {
			buttonsOver = true;
			$(this).clearQueue().fadeTo(100, config.slideshow.fadeHover);
			$initBar.fadeOut(100);
			
		}, function() {
			buttonsOver = false;
			var $theEl = $(this);
			
			setTimeout(function() { 
				if (slideOver) {
					$theEl.clearQueue().fadeTo(250, config.slideshow.fadeUp);
				} else {
					$initBar.fadeIn(100);
					
				}
							
			}, 40);
			
		}).click(function() {
			if($(this).attr('id') == 'picRight') {
				nextImage();
			} else {
				prevImage();
			}
		});
		
		
	}
	
	return {
		init: init
	}
	
}();


_homepage = function() {
	
	var DOM;
	var slideLength;
	var slideScratch;
	var $mainImages;
	
	function init() {
		loadDOM();
		loadFirstSlide();
	}
	
	function loadDOM () {
		DOM = {
			slidesWrap:  $('#slidesWrap')
		}		
	}
	
	function loadFirstSlide() {
		DOM.slidesWrap.html('');
		var firstSlide = $('<img>').attr({src: config.homepage.slideshow.slides[0]}).css("opacity", 0).load(function() {
			DOM.slidesWrap.append(firstSlide);
			firstSlide.animate({opacity: 1}, config.homepage.slideshow.fadeSpeed, "", function() {
				
				loadRemainingSlides();
			});
		});
	}
	
	function loadRemainingSlides() {
		//start on second slide, insert all slides
		var counter = config.homepage.slideshow.slides.length;
		for (var i=1; i < counter; i++) {
			
			// if its the last slide thats loading
			
			if(counter-1 == i) {
				var slide = $('<img>').attr({src: config.homepage.slideshow.slides[i]}).load(function() {
					DOM.slidesWrap.prepend(slide);
					startSlideshow(counter);
				});
				
			// or carry on loading the slides
				
			} else {
				var slide = $('<img>').attr({src: config.homepage.slideshow.slides[i]});
				DOM.slidesWrap.prepend(slide);	
			}

		};
	}
	
	function startSlideshow(counter) {
		slideLength = counter;
		slideScratch = slideLength -1;
		$mainImages = DOM.slidesWrap.children('img');
		//$mainImages.css({opacity: 1});
		fadeIt();
	}
	
	function fadeIt() {
		setTimeout(function(){
			if(slideScratch == 0) {
				slideScratch = slideLength -1;
				$mainImages.eq(slideScratch).fadeIn(config.homepage.slideshow.fadeSpeed, function() {
					$mainImages.show();

				});
			} else {
				$mainImages.eq(slideScratch).fadeOut(config.homepage.slideshow.fadeSpeed);
				slideScratch --;
			}

			fadeIt();	
		}, config.homepage.slideshow.slideDuration);
	}
	
	return {
		init: init
	}
}();

apartmentFeatures = function() {
	
	function init() {
		
		$('.fBlock').each(function() {
			var theItems = $(this).children('span');
			var noOfItems = theItems.length;
			if(noOfItems >= 7) {
				var hideItems = theItems.slice(7, noOfItems+1);
				hideItems.wrapAll('<div>');
				$(this).append('<a href="#">Click to see more items</a>');

			}
		});
		
		$('.fBlock div').hide();
		$('.fBlock a').click(function() {
			if(!$(this).prev().is(':visible')) {
				$(this).html('Click to see less items').prev('div').slideDown('fast');
			} else {
				$(this).html('Click to see more').prev('div').slideUp('fast');
				
			}
			return false;
		});
	}
	
	return {
		init: init
	}
	
}();

	

// image rollovers

SwapImage = {};

SwapImage.rollover =
{
   init: function()
   {
      this.preload();

      $('.hover').css('cursor', 'pointer').hover(function () { 
          $(this).attr( 'src', SwapImage.rollover.newimage($(this).attr('src')) ); 
      }, function () { 
          $(this).attr( 'src', SwapImage.rollover.oldimage($(this).attr('src')) ); 
      });
   },

   preload: function()
   {
      $(window).bind('load', function() {
         $('.hover').each( function( key, elm ) { $('<img>').attr( 'src', SwapImage.rollover.newimage( $(this).attr('src') ) ); });
      });
   },

   newimage: function( src ) { return src.replace(/\.(\w{3})/g, "Hover.$1"); },
   oldimage: function( src ){ return src.replace(/Hover\.(\w{3})/g, ".$1"); }
};

// preload additional images

function preloadImages(thePaths) {
	thePaths
	
	for (var i=0; i < thePaths.length; i++) {
		$('<img>').attr({src: thePaths[i]});
	};	
}


 

