// string bufferer
function StringBuffer() { 
	this.buffer = []; 
} 
StringBuffer.prototype.append = function append(string) { 
	this.buffer.push(string); 
	return this; 
}
StringBuffer.prototype.toString = function toString() { 
	return this.buffer.join(""); 
} 

// stop image flicker on hover in ie6
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

// ajax config
$.ajaxSetup({
	headers: {"X-Requested-With":"Ajax"},
	contentType: "application/x-www-form-urlencoded",
	cache: false,
	data: {}
});

// ie6 sniffer
var ie6 = (document.body && typeof document.body.style.maxHeight == "undefined")? true:false;

// for the scrollable books, etc
// IE only insists these are at this scope
var upVar;
var downVar;
var upVarTwo;
var downVarTwo;

var demoSubmitCount = 0;

var hotelsdotcom = {
	
	/**
 	* sets up the invite form	
 	*/
	innitInviteForm : function(){
		if($("#friendsForm")){
			$("#inviteEmail").focus(function(){
				var msg = $("#inviteEmail").val();
				if(msg=="Their email"){
					$("#inviteEmail").val("");
				}
			});
			$("#inviteEmail").blur(function(){
				var msg = $("#inviteEmail").val();
				if(!msg.length){
					$("#inviteEmail").val("Their email");
				}
			});
			$("#inviteMessage").focus(function(){
				var msg = $("#inviteMessage").val();
				if(msg=="Message"){
					$("#inviteMessage").val("");
				}
			});
			$("#inviteMessage").blur(function(){
				var msg = $("#inviteMessage").val();
				if(!msg.length){
					$("#inviteMessage").val("Message");
				}
			});
			$("#friendsForm > a.button").click(function(){
				hotelsdotcom.inviteFriend();
			});
		}
	},
	
	/**
 	* invites a friend	
 	*/
	inviteFriend : function(){
		var email 	= $("#inviteEmail").val();
		var msg 	= $("#inviteMessage").val();
		if(!email.length||email=="Their email"||!hotelsdotcom.checkEmail(email)){
			if($("p#invite-error")) $("p#invite-error").remove();
			var error			= document.createElement('P');
			error.id			= "invite-error";
			error.style.display = "none";
			error.className		= "form-error";
			error.innerHTML		= "You must enter a valid email address";
			$("#friendsForm").prepend(error);
			$("#invite-error").fadeIn("slow");
			return;
		}
		if(!msg.length||msg=="Message"){
			if($("p#invite-error")) $("p#invite-error").remove();
			var error			= document.createElement('P');
			error.id			= "invite-error";
			error.style.display = "none";
			error.className		= "form-error";
			error.innerHTML		= "You must enter a message";
			$("#friendsForm").prepend(error);
			$("#invite-error").fadeIn("slow");
			return;
		}
		if($("p#invite-error")) $("p#invite-error").remove();
		$.ajax({
			type: "POST",
			url: "/teams/addTeamUser/",
			data: '&data[User][inviteEmail]=' + $("#inviteEmail").val() + '&data[User][inviteMessage]=' + $("#inviteMessage").val(),
			error: function(data){
				hotelsdotcom.createErrorText('hotelsdotcom.inviteFriend',data);
				var error			= document.createElement('P');
				error.id			= "invite-error";
				error.style.display = "none";
				error.className		= "form-error";
				error.innerHTML		= "Sorry, we've hit a problem. Please try again later.";
				$("#friendsForm").prepend(error);
				$("#invite-error").fadeIn("slow");
				return;
			},
			success: function(data){
				var email 	= $("#inviteEmail").val("Their email");
				hotelsdotcom.getSPFriendsList();
			}
		});
	},
	
	
	/**
 	* gets the list of friends for side panel	
 	*/
	getSPFriendsList : function(title){
		// clear any old stuff, ready for new list or error
		if($("#friendsListResults").children()) $("#hotfriendsListResultselsListResults").empty();
		// show loader
		$("#friendsList > div.loader").removeClass("hide");
		
		if(!(/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent))){
			$("#sidePanelFriends > .blue-box-body").addClass("ff");
		}
		
		// clear any old stuff, ready for new list or error
		if($("#friendsListResults").children()) $("#friendsListResults").empty();
		// show loader
		$("#friendsList > div.loader").removeClass("hide");
		
		// JSON url
		var jsonURL = "/teams/getTeamUsers/";
		
		$.ajax({
			type: "GET",
			url: jsonURL,
			error: function(data){
				hotelsdotcom.createErrorText('hotelsdotcom.getSPFriendsList',data);
				var friendsP 		= document.createElement('P');
				friendsP.className	= 'ajax-error';
				friendsP.innerHTML	= 'Sorry, we are unable to retrieve your friends list at the moment.';
				
				$("#friendsList > div.loader").addClass("hide");
				$("#friendsListResults").append(friendsP);
			},
			success: function(data){
				hotelsdotcom.displaySPFriendsList(title,data);
			}
		});
	},
	
	/**
 	* displays the friends list for the side panel
 	*/
	displaySPFriendsList : function(title,data){
		
		var data = $.parseJSON(data);
				
		// have friends?
		if(data.length>0){
			
			var friendsUL = document.createElement('UL');
			$.each(data, function(i){
				$("#sidePanelFriends > div.blue-box-body > a.accordion").html("invite more friends");
				
				var friendsLI 			= document.createElement('LI');
				// put a class of "last" on the last item
				friendsLI.className 	= ((i+1)==data.length)? 'last':'';

				var friendsSPAN			= document.createElement('SPAN');
				if(data[i].guestUser) friendsSPAN.className = "guest";
				
				friendsSPAN.innerHTML	= data[i].name;
				
				if(data[i].online) friendsSPAN.innerHTML	+= " (online)";
				
				friendsLI.appendChild(friendsSPAN);
				friendsUL.appendChild(friendsLI);
				
			});
			
			// clear
			var friendsClear 		= document.createElement('DIV');
			friendsClear.className	= 'clear';
			
			$("#friendsList > div.loader").addClass("hide");
			$("#friendsListResults").append(friendsUL);
			$("#friendsListResults").append(friendsClear);
			
		}else{
			var friendsP 		= document.createElement('P');
			friendsP.className	= 'no-results';
			var title = (title)? title:'friends';
			friendsP.innerHTML	= 'You can vote on the hotels you like and invite your ' + title + ' to vote too';
			
			$("#friendsList > div.loader").addClass("hide");
			$("#friendsListResults").append(friendsP);
		}
	},
	
	/**
 	* gets the list of friends for side panel	
 	*/
	getSPHotelsList : function(travelWith){      
		// clear any old stuff, ready for new list or error
		if($("#hotelsListResults").children()) $("#hotelsListResults").empty();
		// clear any old stuff for the pop ups
		if($("#spHotelPopsContainer").children()) $("#spHotelPopsContainer").empty();
		// show loader
		$("#hotelsList > div.loader").removeClass("hide");
		
		// JSON url
		var jsonURL = "/votes/getAllVotes/";
		
		$.ajax({
			type: "GET",
			url: jsonURL,
			error: function(data){
				hotelsdotcom.createErrorText('hotelsdotcom.getSPHotelsList',data);
				var hotelsP 		= document.createElement('P');
				hotelsP.className	= 'ajax-error';
				hotelsP.innerHTML	= 'Sorry, we are unable to retrieve your hotels list at the moment.';
				
				$("#hotelsList > div.loader").addClass("hide");
				$("#hotelsListResults").append(hotelsP);
			},
			success: function(data){
				
				var data = $.parseJSON(data);
				var hotelIds = new Array;

				// have hotels?
				if(data.length){
					
					if(data.length>3) $("#sidePanelHotels > div.blue-box-body > a.accordion").removeClass("hide");					
					
					// deal with the first three for our summary
					var hotelsTABLE 		= document.createElement('TABLE');
					hotelsTABLE.className 	= "votedHotelsSummary";
					hotelsTABLE.cellSpacing = "0";

					// fix IE bug
					var hotelsTBODY 		= document.createElement('TBODY');
					
					var totalHotels = (data.length>3)? 3:data.length;

					for(i=0;i<totalHotels;i++){
						
						var hotelsTR 		= document.createElement('TR');
														
						var hotelsTD		= document.createElement('TD');
						hotelsTD.headers	= "th" + data[i].name.replace(/\s+/g, '');
						
						var hotelsImgOuterDIV		= document.createElement('DIV');
						hotelsImgOuterDIV.className	= "imgOuterDiv";
						
						var hotelsImgInnerDIV					= document.createElement('DIV');

						if( data[i]['dummy'] ) {
							hotelsImgInnerDIV.className				= "imgInnerDiv spHotel" + data[i]['id'] + "-trigger allVotes-no-results-img";
						}else{
							hotelsImgInnerDIV.className				= "imgInnerDiv spHotel" + data[i]['id'] + "-trigger";
						}

						hotelsImgInnerDIV.innerHTML				= hotelsdotcom.adjustImage(data[i].photos[0].thumb,54,54,true,true);

						hotelsImgOuterDIV.appendChild(hotelsImgInnerDIV)
						
						hotelsTD.appendChild(hotelsImgOuterDIV);
						hotelsTR.appendChild(hotelsTD);
						
						if( data[i]['dummy'] ) {
							var hotelsTD		= document.createElement('TD');
							hotelsTD.headers	= "th" + data[i].name.replace(/\s+/g, '');
							hotelsTD.className	= "allVotes-no-results";
							var dummyText = '<p>You can vote on the hotels you like';
							if(travelWith){
								if(travelWith=='family'){
									dummyText += ' and invite your family to vote too.';
								}else if(travelWith=='partner'){
									dummyText += ' and invite your partner to vote too.';
								}else if(travelWith=='friends'){
									dummyText += ' and invite your friends to vote too.';
								}else if(travelWith=='group'){
									dummyText += ' and invite your group to vote too.';
								}else{
                                    dummyText += '.';
								}
							}
                            dummyText += '</p>';
							hotelsTD.innerHTML	= dummyText;
						} else {
							var hotelsTH		= document.createElement('TH');
							hotelsTH.scope		= "row";
							hotelsTH.id			= "th" + data[i].name.replace(/\s+/g, '');
							
							var hotelsH6		= document.createElement('H6');
							hotelsH6.className	= "spHotel" + data[i]['id'] + "-trigger";
							hotelsH6.innerHTML	= data[i].name;
							
							hotelsTH.appendChild(hotelsH6);
							
							// 'popup window' container
							var hotelPopDiv = document.createElement("DIV");
							hotelPopDiv.className = "jqmWindow";
							hotelPopDiv.id = "spHotel" + data[i]['id'] + "-detail";
							hotelPopDiv.innerHTML = '<div class="jqmWindow-loading"><img src="/img/general/large-loader-on-white.gif" alt="loading..." /></div>';
							
							if($("#spHotel" + data[i]['id'] + "-detail").length==0){
								// add 'popup window' container
								$("#spHotelPopsContainer").append(hotelPopDiv);
							}
							
							hotelsTR.appendChild(hotelsTH);	
							
							var hotelsTD		= document.createElement('TD');
							hotelsTD.headers	= "th" + data[i].name.replace(/\s+/g, '');
							hotelsTD.className	= "votes spHotel" + data[i]['id'] + "-votes";
							hotelsTD.alt = $.toJSON(data[i].userVotes);
							hotelsTD.innerHTML	= data[i].voteScore;
						}
						
						hotelsTR.appendChild(hotelsTD);	
						hotelsTBODY.appendChild(hotelsTR);	
						
						var hotelsTR 		= document.createElement('TR');
						
						var hotelsTD		= document.createElement('TD');
						hotelsTD.colSpan	= "3";
						hotelsTD.className	= "blank-row";
						hotelsTD.innerHTML	= "&nbsp;";
						
						hotelsTR.appendChild(hotelsTD);	
						hotelsTBODY.appendChild(hotelsTR);
										
						hotelsTABLE.appendChild(hotelsTBODY);
						
						hotelIds.push(data[i]['id']);
					}
					
					// grab the rest
					var allHotelsTABLE			= document.createElement('TABLE');
					allHotelsTABLE.className 	= "votedHotelsRemaining";
					allHotelsTABLE.cellSpacing 	= "0";
					
					// fix IE bug
					var allHotelsTBODY 			= document.createElement('TBODY');
					
					for(i=3;i<data.length;i++){
						
						if($("#allHotelsList").children()) $("#allHotelsList").empty();
						
						var allHotelsTR 		= document.createElement('TR');
														
						var allHotelsTD			= document.createElement('TD');
						allHotelsTD.headers		= "th" + data[i].name.replace(/\s+/g, '');
						
						var allHotelsImgOuterDIV		= document.createElement('DIV');
						allHotelsImgOuterDIV.className	= "imgOuterDiv";
						
						
						var allHotelsImgInnerDIV					= document.createElement('DIV');
						allHotelsImgInnerDIV.className				= "imgInnerDiv spHotel" + data[i]['id'] + "-trigger";
						allHotelsImgInnerDIV.innerHTML				= hotelsdotcom.adjustImage(data[i].photos[0].thumb,54,54,true,true);
						
						allHotelsImgOuterDIV.appendChild(allHotelsImgInnerDIV)
						
						allHotelsTD.appendChild(allHotelsImgOuterDIV);
						allHotelsTR.appendChild(allHotelsTD);
						
						var allHotelsTH			= document.createElement('TH');
						allHotelsTH.id			= "th" + data[i].name.replace(/\s+/g, '');
						allHotelsTH.scope		= "row";
						
						var allHotelsH6			= document.createElement('H6');
						allHotelsH6.className	= "spHotel" + data[i]['id'] + "-trigger";
						allHotelsH6.innerHTML	= data[i].name;
						
						allHotelsTH.appendChild(allHotelsH6);
						
						// 'popup window' container
						var hotelPopDiv = document.createElement("DIV");
						hotelPopDiv.className = "jqmWindow";
						hotelPopDiv.id = "spHotel" + data[i]['id'] + "-detail";
						hotelPopDiv.innerHTML = '<div class="jqmWindow-loading"><img src="/img/general/large-loader-on-white.gif" alt="loading..." /></div>';
						
						if($("#spHotel" + data[i]['id'] + "-detail").length==0){
							// add 'popup window' container
							$("#spHotelPopsContainer").append(hotelPopDiv);
						}
						
						allHotelsTR.appendChild(allHotelsTH);	
						
						var allHotelsTD			= document.createElement('TD');
						allHotelsTD.headers		= "th" + data[i].name.replace(/\s+/g, '');
						allHotelsTD.className	= "votes spHotel" + data[i]['id'] + "-votes";	
						allHotelsTD.alt = $.toJSON(data[i].userVotes);
						allHotelsTD.innerHTML = data[i].voteScore;
						
						allHotelsTR.appendChild(allHotelsTD);	
						allHotelsTBODY.appendChild(allHotelsTR);					
						
						var allHotelsTR 		= document.createElement('TR');
						
						var allHotelsTD			= document.createElement('TD');
						allHotelsTD.colSpan		= "3";
						allHotelsTD.className	= "blank-row";
						allHotelsTD.innerHTML	= "&nbsp;";
						
						allHotelsTR.appendChild(allHotelsTD);	
						allHotelsTBODY.appendChild(allHotelsTR);					
						allHotelsTABLE.appendChild(allHotelsTBODY);
						
						hotelIds.push(data[i]['id']);
					}
					
					$("#allHotelsList").append(allHotelsTABLE);
					
					$("#hotelsList > div.loader").addClass("hide");
					$("#hotelsListResults").append(hotelsTABLE);
					
					for(i=0;i<hotelIds.length;i++){
						
						// innit the 'popup windows'
						var windowID = hotelIds[i];
						var extraParam = (document.body && typeof document.body.style.maxHeight == "undefined")? '/ie6':'';
						$('#spHotel'+windowID+'-detail').jqm({ajax: '/products/getProductDetails/'+windowID+extraParam, trigger: '.spHotel'+windowID+'-trigger'});
						//$('#spHotel'+windowID+'-detail').jqDrag();
						var userVotes = $('.spHotel'+windowID+'-votes');
						$(userVotes).each(function(k){
							$(userVotes[k]).mouseover(function(e){
								var userVotes = $.parseJSON( $(this).attr('alt') );
								var voteMessage = '';
								if( userVotes.posSummary ) {
									voteMessage += "<p>The following people like this hotel:<br />" + userVotes.posSummary + "</p>";
								}
								if( userVotes.negSummary ) {
									voteMessage += "<p>The following people do not like this hotel:<br />" + userVotes.negSummary + "</p>";
								}
								
								hotelsdotcom.showMessageBox('spVotesList',voteMessage,false,e.pageX,e.pageY,false,false);
								$(this).css("cursor","help");
							});
							$(userVotes[k]).mouseout(function(e){
								$('#messageBoxspVotesList').remove();
								$(this).css("cursor","default");
							});
						});
					}
				}else{
					
					var hotelsP 		= document.createElement('P');
					hotelsP.className	= 'no-results';
					hotelsP.innerHTML	= 'Vote for your favourites by clicking the thumbs up sign by each hotel.';
					
					$("#hotelsList > div.loader").addClass("hide");
					$("#hotelsListResults").append(hotelsP);
				}
			}	
		});
		
	},
	
	/**
 	* sets up the comments form	
 	*/
	innitChatForm : function(){
		if($("#chatForm")){
			$("#ChatChatText").focus(function(){
				var msg = $("#ChatChatText").val();
				if(msg=="Message"){
					$("#ChatChatText").val("");
				}
			});
			$("#ChatChatText").blur(function(){
				var msg = $("#ChatChatText").val();
				if(!msg.length){
					$("#ChatChatText").val("Message");
				}
			});
		}
	},
	
	/**
 	* creates some error text to be sent to someone
 	*/
	createErrorText : function(func,data){
		var errorStr = '';
		errorStr += "navigator.platform=" + navigator.platform;
		errorStr += "&navigator.appCodeName=" + navigator.appCodeName;
		errorStr += "&navigator.userAgent = " + navigator.userAgent;
		errorStr += "&navigator.appName = " + navigator.appName;
		errorStr += "&navigator.appVersion = " + navigator.appVersion;
		errorStr += "&navigator.cookieEnabled = " + navigator.cookieEnabled;
		errorStr += "&function = " + func;
		if(data['status']) errorStr += "&status = " + data['status'];
		if(data['statusText']) errorStr += "&statusText = " + data['statusText'];
		if(data['responseText']) errorStr += "&responseText = " + data['responseText'];
		if(data['responseXML']) errorStr += "&responseXML = " + data['responseXML'];
		$.ajax({
			type: "POST",
			url: "/services/clientError/ajax/",
			data: errorStr,
			error: function(){
				try{
  					console.log("error on sending error");
				}catch(e){}			
			},
			success: function(data){
				try{
  					console.log("ok sending error");
				}catch(e){}	
			}
		});
	},
	
	/**
 	* posts a comment
 	*/
	postComment : function(){
		var msg = $("#ChatChatText").val();
		if(!msg.length||msg=="Message"){
			if($("p#comment-error")) $("p#comment-error").remove();
			var error			= document.createElement('P');
			error.id			= "comment-error";
			error.style.display	= "none";
			error.className		= "form-error";
			error.innerHTML		= "You must enter a comment";
			$("#chatForm").prepend(error);
			$("#comment-error").fadeIn("slow");
			return;
		}
		if(msg.length>200){
			if($("p#comment-error")) $("p#comment-error").remove();
			var error			= document.createElement('P');
			error.id			= "comment-error";
			error.style.display	= "none";
			error.className		= "form-error";
			error.innerHTML		= "Please limit your comments to 200 characters";
			$("#chatForm").prepend(error);
			$("#comment-error").fadeIn("slow");
			return;
		}
		if($("p#comment-error")) $("p#comment-error").remove();
		$.ajax({
			type: "POST",
			url: "/chats/addChat/",
			data: '&data[Chat][chatText]=' + $("#ChatChatText").val(),
			error: function(data){
				hotelsdotcom.createErrorText('hotelsdotcom.postComment',data);
				if($("p#comment-error")) $("p#comment-error").remove();
				var error			= document.createElement('P');
				error.id			= "comment-error";
				error.style.display	= "none";
				error.className		= "form-error";
				error.innerHTML		= "Sorry, we've hit a problem. Please try again later.";
				$("#chatForm").prepend(error);
				$("#comment-error").fadeIn("slow");
				return;
			},
			success: function(data){
				$("#ChatChatText").val("Message");
				hotelsdotcom.displaySPCommentsList(0,data);
				
				pageTracker._trackPageview('/action/message');
			}
		});
	},
	
	/**
 	* deletes a comment
 	*/
	deleteComment : function(id){
		$.prompt('<p>Are you sure you want to delete this comment?</p>',{ 
			buttons: { Yes: true, No: false }, 
			focus: 0, 
			opacity: 0.5, 
			overlay: "fast", 
			promptspeed: "fast", 
			show: "fadeIn", 
			callback: function(v,m){
				if(v){
					$.ajax({
						type: "GET",
						url: "/chats/deleteChat/"+id,
						error: function(data){
							hotelsdotcom.createErrorText('hotelsdotcom.deleteComment',data);
							var error		= document.createElement('P');
							error.className	= "form-error";
							error.innerHTML	= "Sorry, we've hit a problem. Please try again later.";
							$("#chatForm").prepend(error);
							return;
						},
						success: function(data){
							hotelsdotcom.displaySPCommentsList(0,data);
						}
					});
				}
			}
		});
	},
	
	/**
 	* gets the list of comments for side panel	
 	*/
	getSPCommentsList : function(page){
		// clear any old stuff, ready for new list or error
		if($("#commentsListResults").children()) $("#commentsListResults").empty();
		// show loader
		$("#commentsList > div.loader").removeClass("hide");
		
		var page = (page)? page:0;
		$.ajax({
			type: "GET",
			url: "/chats/getChats/"+page,
			error: function(data){
				hotelsdotcom.createErrorText('hotelsdotcom.getSPCommentsList',data);
				var chatsP 			= document.createElement('P');
				chatsP.className	= 'ajax-error';
				chatsP.innerHTML	= 'Sorry, we are unable to retrieve your comments list at the moment.';
				
				$("#commentsList > div.loader").addClass("hide");
				$("#commentsList").append(chatsP);
			},
			success: function(data){
				hotelsdotcom.displaySPCommentsList(page,data);
			}
		});
	},

	/**
 	* writes out the comments list for side panel
 	*/
	displaySPCommentsList : function(page,data){
		// clear any old stuff, ready for new list or error
		if($("#commentsListResults").children()) $("#commentsListResults").empty();
		// show loader
		$("#commentsList > div.loader").removeClass("hide");
		
		var page = (page)? page:0;
		
		var data = $.parseJSON(data);
		
		// got chats?
		if(data["chats"].length>0){
				
			var chats 	= data["chats"];
		
			var chatsUL = document.createElement('UL');
			
			$.each(chats, function(i){
				
				var chatLI 			= document.createElement('LI');
				chatLI.className	= ((i+1)==chats.length)? 'last':'';
				
				var chatDL 			= document.createElement('DL');
				
				var chatDT 			= document.createElement('DT');
				
				if(chats[i].ownChat){
					var chatDIV 		= document.createElement('DIV');
					chatDIV.className 	= "delete";

					var chatA 			= document.createElement('A');
					chatA.innerHTML 	= "X";
					chatA.title 		= "delete this comment";
					chatA.href 			= "javascript:hotelsdotcom.deleteComment("+chats[i].id+");";

					chatDIV.appendChild(chatA);
					
					chatDT.appendChild(chatDIV);
				}
				
				var chatSTRONG 			= document.createElement('STRONG');
				chatSTRONG.innerHTML	= chats[i].username;
				
				chatDT.appendChild(chatSTRONG);
				
				var chatSPAN 			= document.createElement('SPAN');
				chatSPAN.innerHTML		= "&nbsp;" + chats[i].timeago;
				
				chatDT.appendChild(chatSPAN);
				
				var chatDD 			= document.createElement('DD');
				chatDD.innerHTML 	= chats[i].text;
				
				chatDL.appendChild(chatDT);
				chatDL.appendChild(chatDD);
				chatLI.appendChild(chatDL);
				
				chatsUL.appendChild(chatLI);
				
				$("#commentsList > div.loader").addClass("hide");
				$("#commentsListResults").append(chatsUL);
				
			});
			
			// clear
			var chatsClear 			= document.createElement('DIV');
			chatsClear.className	= 'clear';	
			
			$("#commentsList").append(chatsClear);		
			if(data["earlierPage"]!==false||data["laterPage"]!==false){
				var chatsPaginationUL		= document.createElement('UL');
				chatsPaginationUL.className	= "chats-pagination";	
				
				var chatsPaginationLI		= document.createElement('LI');	
				chatsPaginationLI.className	= "later";
				var chatsPaginationA		= document.createElement('A');	
				if(data["laterPage"]!==false){
					chatsPaginationA.innerHTML	= "&lt; later";	
					chatsPaginationA.href		= "javascript:hotelsdotcom.getSPCommentsList("+data['laterPage']+");";	
				}
				chatsPaginationLI.appendChild(chatsPaginationA);
				chatsPaginationUL.appendChild(chatsPaginationLI);
				
				var chatsPaginationLI		= document.createElement('LI');	
				chatsPaginationLI.className	= "latest";	
				var chatsPaginationA		= document.createElement('A');	
				if(page!=0){
					chatsPaginationA.innerHTML	= "latest";
					chatsPaginationA.href		= "javascript:hotelsdotcom.getSPCommentsList(0);";	
				}
				chatsPaginationLI.appendChild(chatsPaginationA);
				chatsPaginationUL.appendChild(chatsPaginationLI);
				
				var chatsPaginationLI		= document.createElement('LI');	
				chatsPaginationLI.className	= "earlier";	
				var chatsPaginationA		= document.createElement('A');	
				if(data["earlierPage"]!==false){
					chatsPaginationA.innerHTML	= "earlier &gt;";
					chatsPaginationA.href		= "javascript:hotelsdotcom.getSPCommentsList("+data['earlierPage']+");";	
				}
				chatsPaginationLI.appendChild(chatsPaginationA);
				chatsPaginationUL.appendChild(chatsPaginationLI);
				
				$("#commentsListResults").append(chatsPaginationUL);	
			
				$("#commentsListResults").append(chatsClear);	
			
			}
			
		}else{
			var chatsP 		= document.createElement('P');
			chatsP.className	= 'no-results';
			chatsP.innerHTML	= '<span>0</span> comments at the moment';
			
			$("#commentsList > div.loader").addClass("hide");
			$("#commentsListResults").append(chatsP);
		}
	
	},
	
	/**
 	* checks an email address
 	*/
	checkEmail : function (sEmail) {
		var at							= "@";
		var dot							= ".";
		var lat							= sEmail.indexOf(at);
		var lstr						= sEmail.length;
		var ldot						= sEmail.indexOf(dot);
		if (sEmail.indexOf(at) == -1) {return false;}
		if (sEmail.indexOf(at) == -1 || sEmail.indexOf(at)==0 || sEmail.indexOf(at)==lstr) {return false;}
		if (sEmail.indexOf(dot) == -1 || sEmail.indexOf(dot)==0 || sEmail.indexOf(dot)==lstr) {return false;}
		if (sEmail.indexOf(at,(lat+1)) != -1) {return false;}
		if (sEmail.substring(lat-1,lat) == dot || sEmail.substring(lat+1,lat+2)==dot) {return false;}
		if (sEmail.indexOf(dot,(lat+2)) == -1) {return false;}
		if (sEmail.indexOf(" ")!=-1) {return false;}
		return true;
	},
	
	/**
 	* initialises a passed carousel (received an id of a div containing the carousel)
	* will no doubt need editing to make more generic if we use it outside the popup box
 	*/
	innitCarousel : function(obj,alterImage){
		$("#" + obj + " .pics").jCarouselLite({
			btnNext: "#" + obj + " .next",
			btnPrev: "#" + obj + " .prev",
			afterEnd: function(e){
				var first 	= parseInt(e[0].className)+1;
				var last 	= parseInt(e[3].className)+1;
				$("#" + obj + " > div.buttons > div.buttons-info > span.current > span.current-min").html(first);
				$("#" + obj + " > div.buttons > div.buttons-info > span.current > span.current-max").html(last);
			}
		});
		$("#" + obj + " > div.buttons > button").focus(function(){
			this.blur();
		});
		if(alterImage){
			$("#" + obj + " > div.pics > ul > li > span > span > a > img").click(function(){
				var src = (this.src).split("_t.jpg")[0];
				$("#largePic > span").html(hotelsdotcom.adjustImage(src + "_b.jpg",350,236,false,true));
			});
		}else{
			$("#" + obj + " > div.pics > ul > li > span > span > a > img").click(function(){
				$("#largePic > span").html(hotelsdotcom.adjustImage($(this).attr("src"),350,236,false,true));
			});	
		}
		if(!ie6){
			$("#product-hotels-pics > .buttons").removeClass("hide");
		}
		$("#product-hotels-pics").removeClass("toggleHotelPics");
	},
	
	
	/**
 	* gets the hotel results
	* obviously temp until it's decided how we're gonna grab these
 	*/
	getHotelResults : function(page){
		$("#bookmark-us").hide();
		// clear any old stuff, ready for new list or error
		if($("#hotel-results-list").children()) $("#hotel-results-list").empty();
		// show loader
		$("#hotel-results > div.loader").removeClass("hide");
		
		var page = (page)? page:0;
		$.ajax({
			type: "GET",
			url: "/products/getRankedProducts/"+page,
			error: function(data){
				hotelsdotcom.createErrorText('hotelsdotcom.getHotelResults',data);
				var hotelsP 			= document.createElement('P');
				hotelsP.className	= 'ajax-error';
				hotelsP.innerHTML	= 'Sorry, we are unable to retrieve our hotels at the moment.';
				
				$("#hotel-results > div.loader").addClass("hide");
				$("#hotel-results-list").append(hotelsP);
			},
			success: function(data){
				hotelsdotcom.displayHotelResults(page,data);
			}
		});
	},
	
	/**
 	* displays the hotel results
 	*/
	displayHotelResults : function(page,data){
		
		var page = (page)? page:0;
		
		var data = $.parseJSON(data);        
		
		// got results?
		if(data["products"].length>0){
			
			var topLevel = data;
			data = data["products"];
			
			// create and set sliders
			if($(".slider").children()) $(".slider").empty();
			for(i=1;i<$(".slider").length+1;i++){
				var sliderDiv = document.createElement("DIV");
				sliderDiv.id = "slider"+i;
				sliderDiv.innerHTML = '<div id="s'+i+'" class="ui-slider-handle"><img src="/img/slider/handle.gif" alt="" /></div>';
				$(".slider")[i-1].appendChild(sliderDiv);
			}
			var slider1Value = (topLevel["sliders"]["1"])? topLevel["sliders"]["1"]:0;
			$('#slider1').slider({
				stepping: 10,
				min: -50, 
				max: 50,
				startValue: slider1Value, 
				change: function(e, ui){
					hotelsdotcom.sendSliderRequest(ui.handle[0].id,ui.value);
					$("#save-sliders").parent().parent().addClass("twoLinks");
					$("#save-sliders").removeClass("hide");
				}
			});
			$("#s1").css("visibility","visible");
			var slider2Value = (topLevel["sliders"]["2"])? topLevel["sliders"]["2"]:0;
			$('#slider2').slider({
				stepping: 10,
				min: -50, 
				max: 50,
				startValue: slider2Value,
				change: function(e, ui){
					hotelsdotcom.sendSliderRequest(ui.handle[0].id,"+"+ui.value);
					$("#save-sliders").parent().parent().addClass("twoLinks");
					$("#save-sliders").removeClass("hide");
				}
			});
			$("#s2").css("visibility","visible");
			
			
			
			var count = 1;
			
			$.each(data, function(i){
				
				// container div
				var hotelItemDiv 					= document.createElement("DIV");
				hotelItemDiv.className 				= "hotel-item";
				if(count==5) hotelItemDiv.className	+= " row-end";
				hotelItemDiv.id 					= "hotel" + data[i]['id'];
				
				// icons list
				var hotelIconsUl 			= document.createElement("UL");
				hotelIconsUl.className		= "hotel-icons";
					// recommended icon - if set in supply array
                    if (data[i]['showRecommendedIcon']) {
                      var hotelIconsLi 		= document.createElement("LI");
                      hotelIconsLi.className 	= "recommended-icon";
                      hotelIconsLi.title 		= "Recommended";
                      hotelIconsLi.innerHTML 	= '<img src="/img/results/recommended.png" alt="Recommended" />';
                      $(hotelIconsUl).append(hotelIconsLi);
                    }
					
					/********************************
					/* ELEVATOR ICON STUFF
					/* THERE'S ANOTHER BIT BELOW TOO, FOR THE KEY
					/********************************/
					// elevator icon
					var hotelIconsLi 		= document.createElement("LI");
					hotelIconsLi.className 	= "elevator-icon";
					if(data[i]['matchQuality'] != undefined){
                	if(data[i]['matchQuality'] >= 5 &&  data[i]['matchQuality'] < 50){ var elevatorKey = 1; var elevatorIconTitle='Worth A Look'; }
						else if(data[i]['matchQuality'] >= 50 &&  data[i]['matchQuality'] < 95){ var elevatorKey = 2; var elevatorIconTitle='Good Fit'; }
						else if(data[i]['matchQuality'] >= 95) { var elevatorKey = 3; var elevatorIconTitle='Perfect Match!'; }
						else { var elevatorKey = false; }
					}
					
					if( elevatorKey ){
						hotelIconsLi.innerHTML 	= '<a href="#hotelKey" class="elevatorKey"><img src="/img/results/elevator_' + elevatorKey + '.png" alt="'+elevatorIconTitle+'" /></a>';
						$(hotelIconsUl).append(hotelIconsLi);
					}
					
					var hotelIconsLi 		= document.createElement("LI");
					hotelIconsLi.className 	= "more-icon";
					hotelIconsLi.innerHTML 	= '<a href="#" title="More information about this hotel" class="hotel' + data[i]["id"] + '-trigger"><img src="/img/results/more.png" alt="More" /></a>';
					$(hotelIconsUl).append(hotelIconsLi);
				// add icons list
				$(hotelItemDiv).append(hotelIconsUl);
				
				// polaroid container				
				var hotelPolaroidDiv 					= document.createElement("DIV");
				hotelPolaroidDiv.className 				= "hotel-polaroid";

					// hotel pic
					var hotelPicDiv 					= document.createElement("DIV");
					hotelPicDiv.className 				= "hotel-pic hotel" + data[i]['id'] + "-trigger";
					hotelPicDiv.innerHTML				= "<span>" + hotelsdotcom.adjustImage(data[i]['photos'][0]['full'],139,139,false,true) + "</span>";
					$(hotelPolaroidDiv).append(hotelPicDiv);
					
					// hotel polaroid text
					var hotelPolaroidTextDiv 			= document.createElement("DIV");
					hotelPolaroidTextDiv.className 		= "hotel-polaroid-text";
					// hotel min height fix
					var hotelMinHeightFixDiv 			= document.createElement("DIV");
					hotelMinHeightFixDiv.className 		= "hotel-min-height-fix";
					hotelMinHeightFixDiv.innerHTML		= "&nbsp;";
					$(hotelPolaroidTextDiv).append(hotelMinHeightFixDiv);
					// hotel info
					var hotelInfoDiv 					= document.createElement("DIV");
					hotelInfoDiv.className 				= "hotel-info";
					
					var hotelName = data[i]['name'];
					var classString = '';
					if(hotelName.length>60){
						classString = ' class="longName"';
					}
					hotelInfoDiv.innerHTML 				= '<h4 title="' + data[i]['name']  + '"'+classString+'>' + hotelName  + ' <span style="display: none; position: absolute; z-index: 5000; top: 1px; left: 40px; font-size: 9px; color: #666;">(r: ' + data[i]['rankingScore'] + ')</span></h4>';
						
					// add hotel info
					$(hotelPolaroidTextDiv).append(hotelInfoDiv);
					// clear
					var hotelClear 						= document.createElement("DIV");
					hotelClear.className 				= "clear";
					$(hotelPolaroidTextDiv).append(hotelClear);
					$(hotelPolaroidDiv).append(hotelPolaroidTextDiv);
				
				// add polaroid container	
				$(hotelItemDiv).append(hotelPolaroidDiv);
				
				// hotel details container				
				var hotelDetailsDiv 					= document.createElement("DIV");
				hotelDetailsDiv.className 				= "hotel-details";

					if(data[i]['hotelLocation']){
						// hotel location
						var hotelLocation = data[i]['hotelLocation'];
						var locationClass = '';
						if(hotelLocation.length>33){
							hotelLocation = hotelLocation.substring(0,33) + "...";
						}
						if(hotelLocation.length>30){
							locationClass = "xsmall";
						}
						var hotelDetailsLocationDiv 			= document.createElement("DIV");
						hotelDetailsLocationDiv.className 		= "hotel-location";
						hotelDetailsLocationDiv.innerHTML 		= "<p class=\""+locationClass+"\">" + hotelLocation + "</p>";
						$(hotelDetailsDiv).append(hotelDetailsLocationDiv);
						// clear
						var hotelClear 						= document.createElement("DIV");
						hotelClear.className 				= "clear";
						$(hotelDetailsDiv).append(hotelClear);
					}
					
					// hotel price
					var hotelDetailsLeftDiv 			= document.createElement("DIV");
					hotelDetailsLeftDiv.className 		= "hotel-details-left";
					hotelDetailsLeftDiv.innerHTML 		= "<p class=\"price\"><span>From</span> &pound;" + data[i]['fromPrice'] + "</p>";
					$(hotelDetailsDiv).append(hotelDetailsLeftDiv);
					// hotel stars
					var hotelDetailsRightDiv 			= document.createElement("DIV");
					hotelDetailsRightDiv.className 		= "hotel-details-right";
					hotelDetailsRightDiv.innerHTML 		= "";
					var starRating = data[i]['starRating'];
					var starRatingRound = Math.floor(starRating);
					for(x=0;x<5;x++){
						var img = '';
						if(x==starRatingRound){
							if(hotelsdotcom.isFloat(starRating)){
								img = "half-"	
							}else{
								img = "no-"	
							}
						}
						if(x>starRatingRound){
							img = "no-"
						}
						hotelDetailsRightDiv.innerHTML	+= '<img alt="star" src="/img/products/'+img+'star.gif"/>';
					}
					$(hotelDetailsDiv).append(hotelDetailsRightDiv);
					// horizontal rule
					var hotelHr = document.createElement("DIV");
					hotelHr.className 					= "hr";
					hotelHr.innerHTML 					= "<hr />";
					$(hotelDetailsDiv).append(hotelHr);
					// hotel rating
					var hotelDetailsRatingDiv 			= document.createElement("DIV");
					hotelDetailsRatingDiv.className 		= "hotel-details-rating";
					var reviewsTotal = data[i]['ratingCount'];
					reviewsTotal = (reviewsTotal==1)? reviewsTotal + " review":reviewsTotal + " reviews";

					hotelDetailsRatingDiv.innerHTML 		= "<p><span class=\"title\">Guest Rating</span> "+data[i].guestRating+" <span class=\"reviewsTotal\">("+reviewsTotal+")</span></p>";
					$(hotelDetailsDiv).append(hotelDetailsRatingDiv);
					// clear
					var hotelClear 						= document.createElement("DIV");
					hotelClear.className 				= "clear";
					$(hotelDetailsDiv).append(hotelClear);
					
					// hotel voting buttons
					var hotelVotesDl 				= document.createElement("DL");
					hotelVotesDl.className 			= "hotel-votes";
					hotelVotesDl.id 			= "votecount" + data[i]['id'];
					hotelVotesDl.innerHTML 			= '<dt title="I like this"><img title="I like this" alt="' + data[i]['id'] + '" class="vote-up" src="/img/results/vote-up.png" /></dt>';                    
                    var posVotes = '&nbsp;';
                    if ((data[i]['votes']['positive'].length)>0) {
                      posVotes = '+' + data[i]['votes']['positive'].length;
                    } else if ((data[i]['votes']['negative'].length)>0) {
                      posVotes = '0';
                    }
					var posUserVoteNames = new Array();
					if( posVotes ) {
						$(data[i]['votes']['positive']).each( function(j){
							if(data[i]['votes']['positive'][j]['userDisplayName'] != null){ posUserVoteNames.push(data[i]['votes']['positive'][j]['userDisplayName']); }
						});
						hotelVotesDl.innerHTML 			+= '<dd class="voteCounterPos" alt="' + posUserVoteNames.join(', ') + '">' + posVotes + '</dd>';
					}
					else {
						hotelVotesDl.innerHTML 			+= '<dd class="voteCounterPos">' + posVotes + '</dd>';
					}
					hotelVotesDl.innerHTML 			+= '<dt title="I don\'t like this"><img title="I don\'t like this" alt="' + data[i]['id'] + '" class="vote-down" src="/img/results/vote-down.png" /></dt>';
					var negVotes = '';
                    if ((data[i]['votes']['negative'].length)>0) {
                      negVotes = '-' + data[i]['votes']['negative'].length;
                    } else if ((data[i]['votes']['positive'].length)>0) {
                      negVotes = '0';
                    }
                    var negUserVoteNames = new Array();
					if( negVotes ) {
						$(data[i]['votes']['negative']).each( function(j){
							if(data[i]['votes']['negative'][j]['userDisplayName'] != null){ negUserVoteNames.push(data[i]['votes']['negative'][j]['userDisplayName']); }
						});
						hotelVotesDl.innerHTML 			+= '<dd class="voteCounterNeg" alt="' + negUserVoteNames.join(', ') + '">' + negVotes + '</dd>';
					}
					else {
						hotelVotesDl.innerHTML 			+= '<dd class="voteCounterNeg">' + negVotes + '</dd>';
					}
					//$(hotelDetailsDiv).append(hotelVotesDl);
					// clear
					var hotelClear 					= document.createElement("DIV");
					hotelClear.className 			= "clear";
					$(hotelDetailsDiv).append(hotelClear);
					
				// add hotel details container	
				$(hotelItemDiv).append(hotelDetailsDiv);

				// add everything
				$("#hotel-results > div.loader").addClass("hide");
				$("#hotel-results-list").append(hotelItemDiv);
				
				// 'popup window' container
				var hotelPopDiv = document.createElement("DIV");
				hotelPopDiv.className = "jqmWindow";
				hotelPopDiv.id = "hotel" + data[i]['id'] + "-detail";
				hotelPopDiv.innerHTML = '<div class="jqmWindow-loading"><img src="/img/general/large-loader-on-white.gif" alt="loading..." /></div>';
				
				// add 'popup window' container
				$("#hotel-results-list").append(hotelPopDiv);
				
				if(count==4){
					count = 1;
				}else{
					count++;
				}
				
				var windowID = data[i]['id'];
				
				$(document).ready(function() {
					var extraParam = (document.body && typeof document.body.style.maxHeight == "undefined")? '/ie6':'';
					$('#hotel'+windowID+'-detail').jqm({ajax: '/products/getProductDetails/'+windowID+extraParam, trigger: '.hotel'+windowID+'-trigger'});
					//$('#hotel'+windowID+'-detail').jqDrag();
				});
				
			});
			
			// pagination
			if(topLevel["prevPage"]!==false||topLevel["nextPage"]!==false){
			
				var paginationDiv = document.createElement("DIV");
				paginationDiv.className = "hotelPagination";
				
				var paginationUl = document.createElement("UL");
				
				if(topLevel["nextPage"]!==false){
					var paginationLi = document.createElement("LI");
					paginationLi.className = "next";
					paginationLi.innerHTML = '<a href="#resultsHeader" onclick="javascript:hotelsdotcom.getHotelResults('+topLevel["nextPage"]+')" title="next page">next</a>';
					paginationUl.appendChild(paginationLi);
				}
				
				if(topLevel["prevPage"]!==false){
					var paginationLi = document.createElement("LI");
					paginationLi.className = "prev";
					paginationLi.innerHTML = '<a href="#resultsHeader" onclick="javascript:hotelsdotcom.getHotelResults('+topLevel["prevPage"]+')" title="previous page">prev</a>';
					paginationUl.appendChild(paginationLi);
				}
				
				if(page!=0){
					var paginationLi = document.createElement("LI");
					paginationLi.className = "first";
					paginationLi.innerHTML = '<a href="#resultsHeader" onclick="javascript:hotelsdotcom.getHotelResults(0)" title="first page">first</a>';
					paginationUl.appendChild(paginationLi);
				}
				
				var hotelClear 						= document.createElement("DIV");
				hotelClear.className 				= "clear";
				$("#hotel-results-list").prepend(hotelClear.cloneNode(true));
				
				paginationDiv.appendChild(paginationUl);
				paginationDiv.appendChild(hotelClear);
				$("#hotel-results-list").prepend(paginationDiv.cloneNode(true));
				
				$("#hotel-results-list").append(hotelClear);
				
				$("#hotel-results-list").append(paginationDiv);
			}else{
				// add space for the pagination anyway to keep things consistant
				var paginationDiv = document.createElement("DIV");
				paginationDiv.className = "hotelPagination";
				paginationDiv.innerHTML = "&nbsp;";
				
				var hotelClear 						= document.createElement("DIV");
				hotelClear.className 				= "clear";
				$("#hotel-results-list").prepend(hotelClear.cloneNode(true));
				
				$("#hotel-results-list").prepend(paginationDiv.cloneNode(true));
				
				$("#hotel-results-list").append(hotelClear);
				
				$("#hotel-results-list").append(paginationDiv);
				
			}
			
			/********************************
			/* ELEVATOR ICON STUFF
			/* THERE'S ANOTHER BIT ABOVE TOO
			/********************************/
			// the key
			$("#hotel-results-list").append(hotelClear);
				
			var hotelKey 		= document.createElement("div");
			hotelKey.id 		= "hotelKey";
			hotelKey.innerHTML	= "<img src=\"/img/results/elevator_key.gif\" alt=\"key\" />";
			
			$("#hotel-results-list").append(hotelKey);
			
			
			$("#bookmark-us").show();
			
		
		}else{
			var hotelsP 		= document.createElement('P');
			hotelsP.className	= 'no-results';
			hotelsP.innerHTML	= '<span>0</span> hotel results at the moment';
			
			$("#hotel-results > div.loader").addClass("hide");
			$("#hotel-results-list").append(hotelsP);
		}
		
		// add the events for the positive vote icons
		var posVotes = $("img.vote-up"); 
		$.each(posVotes,function(i){
			$(posVotes[i]).click(function(e){
				$.ajax({
					type: "GET",
					url: "/votes/makeVote/"+$(posVotes[i]).attr('alt')+"/+1",
					// NEED ACTIONS
					error: function(data){
						hotelsdotcom.createErrorText('hotelsdotcom.displayHotelResults.posVotes',data);
						hotelsdotcom.showMessageBox($(posVotes[i]).attr('alt'),"<p>Sorry, we were unable to register your vote. Please try again.</p>",2000,e.pageX,e.pageY,true,false);
					},
					success: function(data){
						var data = $.parseJSON(data);
						if(data["errorMessage"]){
							hotelsdotcom.showMessageBox($(posVotes[i]).attr('alt'),"<p>"+ data['errorMessage'] + "</p>",2000,e.pageX,e.pageY,true,false);
							return;
						}
						var voteText = $(posVotes[i]).parent().next();
						var currentVote = parseInt($(voteText).html());
						var newVote = currentVote + 1;
						newVote = (newVote!==0)? "+"+newVote:newVote;
						$(voteText).html("" + data['positives'] + "");
						var siblings = $(posVotes[i]).parent().siblings()[2];
						$(siblings).html( "" + data['negatives'] + "" );
						
						//update the user vote places
						posUserVoteNames = new Array();
						$(data['positiveUsers']).each( function(j){
							if(data['positiveUsers'][j]['userDisplayName'] != null){ posUserVoteNames.push(data['positiveUsers'][j]['userDisplayName']); }
						});
						negUserVoteNames = new Array();
						$(data['negativeUsers']).each( function(j){
							if(data['negativeUsers'][j]['userDisplayName'] != null){ negUserVoteNames.push(data['negativeUsers'][j]['userDisplayName']); }
						});
						$(voteText).attr("alt", posUserVoteNames.join(', '));
						$(siblings).attr("alt", negUserVoteNames.join(', '));
						
						hotelsdotcom.showMessageBox($(posVotes[i]).attr('alt'),"<p>Thank you, your positive vote has been counted.</p>",2000,e.pageX,e.pageY,true,false);
						hotelsdotcom.getSPHotelsList();
						
						pageTracker._trackPageview('/action/vote/pos');
					}
				});
			});
		});
		var posVoteCounter = $("dl.hotel-votes .voteCounterPos");
		$.each(posVoteCounter,function(i){
			$(posVoteCounter[i]).mouseover(function(e){
				// the data should be already set in the page
				if( $(posVoteCounter[i]).attr('alt') != 'undefined' && $(posVoteCounter[i]).attr('alt') != '' ) {
					hotelsdotcom.showMessageBox('userVoteShow' + i,"<p>The following people like this hotel:<br /><br />" + $(posVoteCounter[i]).attr('alt') + "</p>",false,e.pageX,e.pageY,false,false);
					$(this).css("cursor","help");
				}
				return;
			});
			$(posVoteCounter[i]).mouseout(function(e){
				$('#messageBoxuserVoteShow'+i).remove();
				$(this).css("cursor","default");
				return;
			});
		});
		
		// add the events for the negative vote icons
		var negVotes = $("img.vote-down"); 
		$.each(negVotes,function(i){
			$(negVotes[i]).click(function(e){
				$.ajax({
					type: "GET",
					url: "/votes/makeVote/"+$(negVotes[i]).attr('alt')+"/-1",
					// NEED ACTIONS
					error: function(){
						hotelsdotcom.createErrorText('hotelsdotcom.displayHotelResults.negVotes',data);
						hotelsdotcom.showMessageBox($(posVotes[i]).attr('alt'),"<p>Sorry, we were unable to register your vote. Please try again.</p>",2000,e.pageX,e.pageY,true,false);
					},
					success: function(data){
						var data = $.parseJSON(data);
						if(data["errorMessage"]){
							hotelsdotcom.showMessageBox($(posVotes[i]).attr('alt'),"<p>"+ data['errorMessage'] + "</p>",2000,e.pageX,e.pageY,true,false);
							return;
						}
						var voteText = $(negVotes[i]).parent().next();
						var currentVote = parseInt($(voteText).html());
						var newVote = currentVote - 1;
						$(voteText).html("" + data['negatives'] + "");
						var siblings = $(posVotes[i]).parent().siblings()[0];
						$(siblings).html( "" + data['positives'] + "" );
						
						//update the user vote places
						posUserVoteNames = new Array();
						$(data['positiveUsers']).each( function(j){
							if(data['positiveUsers'][j]['userDisplayName'] != null){ posUserVoteNames.push(data['positiveUsers'][j]['userDisplayName']); }
						});
						negUserVoteNames = new Array();
						$(data['negativeUsers']).each( function(j){
							if(data['negativeUsers'][j]['userDisplayName'] != null){ negUserVoteNames.push(data['negativeUsers'][j]['userDisplayName']); }
						});
						$(voteText).attr("alt", negUserVoteNames.join(', '));
						$(siblings).attr("alt", posUserVoteNames.join(', '));
						
						hotelsdotcom.showMessageBox($(posVotes[i]).attr('alt')+'neg',"<p>Thank you, your negative vote has been counted.</p>",2000,e.pageX,e.pageY,true,false);
						hotelsdotcom.getSPHotelsList();
						
						pageTracker._trackPageview('/action/vote/neg');
					}
				});
			});
		});
		var negVoteCounter = $("dl.hotel-votes .voteCounterNeg");
		$.each(negVoteCounter,function(i){
			$(negVoteCounter[i]).mouseover(function(e){
				// the data should be already set in the page
				if( $(negVoteCounter[i]).attr('alt') != 'undefined' && $(negVoteCounter[i]).attr('alt') != '' ) {
					hotelsdotcom.showMessageBox('userVoteShow' + i,"<p>The following people don't like this hotel:<br /><br />" + $(negVoteCounter[i]).attr('alt') + "</p>",false,e.pageX,e.pageY,false,false);
					$(this).css("cursor","help");
				}
				return;
			});
			$(negVoteCounter[i]).mouseout(function(e){
				$('#messageBoxuserVoteShow'+i).remove();
				$(this).css("cursor","default");
				return;
			});
		});
		
		var matchIcons = $("#hotel-results-list .hotel-item .hotel-icons .elevator-icon a.elevatorKey");
		$.each(matchIcons,function(i){
			$(matchIcons[i]).mouseover(function(e){
				hotelsdotcom.showMessageBox("elevatorIconKey"+i,"<img src=\"/img/results/elevator_key.gif\" alt=\"\" />",false,e.pageX,eval(e.pageY+20),false,208);
			});
			$(matchIcons[i]).mouseout(function(e){
				if($("#messageBoxelevatorIconKey" + i).length){
					$("#messageBoxelevatorIconKey" + i).remove();
				}
			});
		});
	},
	
	/**
 	* shows a message/alert box
	* id = string. unique identifier of the 'pop up'. can just be random number.
	* message = string. the message to display
	* time = integer || false. the time the box should stay on the screen. can be false if you want it to stay until another event
	* x = integer. the x coordinate of the event that fired this
	* y = integer. the y coordinate of the event that fired this
	* canClose = true || false. show the close button, or remove it and close the box some other way
	* width = integer || false. width of the message window. default is 200;
 	*/
	showMessageBox : function(id,message,time,x,y,canClose,width){
		
		//prevents 2 message boxes with same id from being opened
		if($('#messageBox' + id).length > 0) { return false; }
		
		// create and prepend message box
		var messageDiv = document.createElement("DIV");
		messageDiv.className = "messageBox";
		if(width){
			messageDiv.style.width = width + "px";
		}
		messageDiv.id = "messageBox" + id;
		messageDiv.innerHTML = "<span><a>X</a></span>";
		var closeButton = (canClose)? "X":"&nbsp";
		messageDiv.innerHTML = "<span><a>"+closeButton+"</a></span>";
		var messageDivInner = document.createElement("DIV");
		messageDivInner.className = "inner";
		messageDivInner.innerHTML = message;
		$(messageDiv).append(messageDivInner);
		$("div#container").prepend(messageDiv);
		// calculate good x and y coordinates
		var newX = x + 10;
		var newY = (y - $("#" + messageDiv.id).height()) - 30;
		$("#" + messageDiv.id).css("top",newY + "px");
		$("#" + messageDiv.id).css("left",newX + "px");
		if(canClose){
		// add a click event for the close button
			$("#" + messageDiv.id + " > span > a").click(function(){
				$("#" + messageDiv.id).hide();							 
			});
		}
		// fade it in, then fade it out, then remove it
		$("#" + messageDiv.id).fadeIn("slow", function(){
			if(time){
				 setTimeout(function() {
					$("#" + messageDiv.id).fadeOut("slow", function(){
						$("#" + messageDiv.id).remove();
					});
				}, time);	
			}
		});
	},

	/**
 	* attempts a login
 	*/
	doLogin : function(){
		var email 		= $("#loginEmail").val();
		var password 	= $("#loginPassword").val();
        var loginRemember = $("#loginRemember").val();
		if($("#hiddenTeamCreatedBy").length>0){
			var hiddenTeamCreatedBy = $("#hiddenTeamCreatedBy").val();
			var hiddenTeamName = $("#hiddenTeamName").val();
		}
		if(!email.length||!hotelsdotcom.checkEmail(email)){
			if($("p#login-error")) $("p#login-error").remove();
			var error				= document.createElement('P');
			error.id				= "login-error";
			error.style.display		= "none";
			error.className			= "form-error";
			error.innerHTML			= "You must enter a valid email address";
			$("#loginForm").prepend(error);
			$("#login-error").slideDown("slow");
			return;
		}
		if(!password.length){
			if($("p#login-error")) $("p#login-error").remove();
			var error				= document.createElement('P');
			error.id				= "login-error";
			error.style.display		= "none";
			error.className			= "form-error";
			error.innerHTML			= "You must enter a password";
			$("#loginForm").prepend(error);
			$("#login-error").slideDown("slow");
			return;
		}
		var dataToSend = '&data[Login][email]=' + $("#loginEmail").val() + '&data[Login][password]=' + $("#loginPassword").val() + '&data[Login][loginRemember]=' + ($("#loginRemember").is(':checked') ? '1' : '0');
		if($("#hiddenTeamId").length>0){
			dataToSend += '&data[Login][teamId]=' + $("#hiddenTeamId").val();
		}
		$.ajax({
			type: "POST",
			url: "/users/login",
			data: dataToSend,
			error: function(data){
				hotelsdotcom.createErrorText('hotelsdotcom.doLogin',data);
				if($("p#login-error")) $("p#login-error").remove();
				var error				= document.createElement('P');
				error.id				= "login-error";
				error.style.display		= "none";
				error.className			= "form-error";
				error.innerHTML			= "Sorry, we've hit a problem. Please try again later.";
				$("#loginForm").prepend(error);
				$("#login-error").slideDown("slow");
				return;
			},
			success: function(data){
				var data = $.parseJSON(data);
				if(data["errorMessage"]){
					if($("p#login-error")) $("p#login-error").remove();
					var error				= document.createElement('P');
					error.id				= "login-error";
					error.style.display		= "none";
					error.className			= "form-error";
					error.innerHTML			= data["errorMessage"];
					$("#loginForm").prepend(error);
					$("#login-error").slideDown("slow");
					return;
				}
				if(data["redirect"]){ 
                    window.location=data["redirect"];
					return;
                }
				if(data["ok"]){
					window.location.reload();
					return;
				}
			}
		});
	},
	
	/**
 	* attempts to register
 	*/
	doRegister : function(type){
		if(type=="save"){
			var firstName 	= $("#registerFirstName").val();
			var lastName 	= $("#registerLastName").val();
			var email 		= $("#registerEmail").val();
			var password 	= $("#registerPassword").val();
			var cPassword 	= $("#registerPasswordConfirm").val();
			var trip 		= $("#registerTripName").val();
		}
		var friends 	= $("#registerEmailAddresses").val();
		if(type=="save"){
			if(!firstName.length){
				if($("p#register-error")){
					$("p#register-error").remove();
					$("#registerError").hide();
				}
				var error		= document.createElement('P');
				error.id		= "register-error";
				error.innerHTML	= "You must enter your first name";
				$("#registerError").append(error);
				$("#registerError").slideDown("slow");
				return;
			}
			if(!lastName.length){
				if($("p#register-error")){
					$("p#register-error").remove();
					$("#registerError").hide();
				}
				var error		= document.createElement('P');
				error.id		= "register-error";
				error.innerHTML	= "You must enter your last name";
				$("#registerError").append(error);
				$("#registerError").slideDown("slow");
				return;
			}
			if(name.indexOf('&')!=-1){
				if($("p#register-error")){
					$("p#register-error").remove();
					$("#registerError").hide();
				}
				var error		= document.createElement('P');
				error.id		= "register-error";
				error.innerHTML	= "Please enter your name, omitting the '&amp;'."
				$("#registerError").append(error);
				$("#registerError").slideDown("slow");
				return;
			}
			if(!email.length||!hotelsdotcom.checkEmail(email)){
				if($("p#register-error")){
					$("p#register-error").remove();
					$("#registerError").hide();
				}
				var error		= document.createElement('P');
				error.id		= "register-error";
				error.innerHTML	= "You must enter a valid email address";
				$("#registerError").append(error);
				$("#registerError").slideDown("slow");
				return;
			}
			if(!password.length||!cPassword.length){
				if($("p#register-error")){
					$("p#register-error").remove();
					$("#registerError").hide();
				}
				var error		= document.createElement('P');
				error.id		= "register-error";
				error.innerHTML	= "You must enter and confirm a password";
				$("#registerError").append(error);
				$("#registerError").slideDown("slow");
				return;
			}
			if(password.length<6||password.length>10){
				if($("p#register-error")){
					$("p#register-error").remove();
					$("#registerError").hide();
				}
				var error		= document.createElement('P');
				error.id		= "register-error";
				error.innerHTML	= "Your password must be between 6 and 10 characters long";
				$("#registerError").append(error);
				$("#registerError").slideDown("slow");
				return;
			}
			if(password!=cPassword){
				if($("p#register-error")){
					$("p#register-error").remove();
					$("#registerError").hide();
				}
				var error		= document.createElement('P');
				error.id		= "register-error";
				error.innerHTML	= "The two passwords do not match";
				$("#registerError").append(error);
				$("#registerError").slideDown("slow");
				return;
			}
			pageTracker._trackPageview('/action/saveAndShare');
		}else{
			if(!friends.length){
				if($("p#register-error")){
					$("p#register-error").remove();
					$("#registerError").hide();
				}
				var error		= document.createElement('P');
				error.id		= "register-error";
				error.innerHTML	= "You must enter at least one email address";
				$("#registerError").append(error);
				$("#registerError").slideDown("slow");
				return;
			}
			pageTracker._trackPageview('/action/share');
		}
		if(type=="save"){
			var newsLetter = ($('#popUpRegisterForm input[id=registerNewsletter]:checked').val())? '1':'0';
			
			var postData = '&data[Register][email]=' + $("#registerEmail").val() + '&data[Register][firstName]=' + $("#registerFirstName").val() + '&data[Register][lastName]=' + $("#registerLastName").val() + '&data[Register][password]=' + $("#registerPassword").val() + '&data[Register][confirmPassword]=' + $("#registerPasswordConfirm").val() + '&data[Register][newsletterSignup]=' + newsLetter + '&data[Register][tripName]=' + $("#registerTripName").val() + '&data[User][inviteEmail]=' + $("#registerEmailAddresses").val();
		}else{
			var postData = '&data[User][inviteEmail]=' + $("#registerEmailAddresses").val().split("\n");
		}
		
		$.ajax({
			type: "POST",
			url: "/teams/submitSaveAndShare",
			data: postData,
			error: function(data){
				hotelsdotcom.createErrorText('hotelsdotcom.doRegister',data);
				if($("p#register-error")){
					$("p#register-error").remove();
					$("#registerError").hide();
				}
				var error		= document.createElement('P');
				error.id		= "register-error";
				error.innerHTML	= "Sorry, we've hit a problem. Please try again later.";
				$("#registerError").append(error);
				$("#registerError").slideDown("slow");
				return;
			},
			success: function(data){
				
				var data = $.parseJSON(data);
				if(data["errorMessage"]){
					if($("p#register-error")){
						$("p#register-error").remove();
						$("#registerError").hide();
					}
					var error		= document.createElement('P');
					error.id		= "register-error";
					error.innerHTML	= data["errorMessage"];
					$("#registerError").append(error);
					$("#registerError").slideDown("slow");
					return;
				}
				if(data["okMessage"]){
					if($("p#register-error")){
						$("p#register-error").remove();
						$("#registerError").hide();
					}
					$("#registerPopUpInner").children().remove();
					$(".intro").remove();
					$("#registerPopUpInner").removeClass("bg");
					$("#registerPopUpInner").html("<div class=\"okMessage\">" + data["okMessage"] + "<div class=\"clear\"></div></div>");
					$("#buttonSend").remove();
					$("#buttonContinue").removeClass("hide");
					
					return;
				}
			}
		});
	},
	
	/**
 	* sets up the module's demographic form	
 	*/
	innitDemographicForm : function(){ 
		// for IE's benefit
		var formLabels = $("div.answer-col > label")
		$.each(formLabels,function(i){
			$(formLabels[i]).click(function(){
				var obj = $(formLabels[i]).parent().children(".radio").children("input").attr("id");
				$('#profileContentForm input[id='+obj+']').attr("checked","checked");
			});
			$("#submitDemogButton > img").click(function(){
				hotelsdotcom.validateDemographicsForm();
			});
		});
	},
	
	/**
 	* validates module's demographic form	
 	*/
	validateDemographicsForm : function(){
		var p = $("#errorText");
		p.html("");
		p.hide("");
		var q1 = $('#profileContentForm input[name=demog-gender]:checked').val();
		var q2 = $('#profileContentForm input[name=data-trip-type]:checked').val();
		var q3 = $('#profileContentForm input[name=demog-ageRange]:checked').val();
		var q4 = document.getElementById("destination").value;
		if(!q1){
			p.html("Please select your gender");
			p.fadeIn("slow");
			return false;
		}
		if(!q2){
			p.html("Please tell us what kind of trip it is");
			p.fadeIn("slow");
			return false;
		}
		if(!q3){
			p.html("Please tell us your age");
			p.fadeIn("slow");
			return false;
		}
		if(q4.indexOf("--")!=-1){
			p.html("Please choose a destination option.");
			p.fadeIn("slow");
			return false;
		}
		if(q3.toLowerCase().indexOf("under")!=-1){
			if(demoSubmitCount==0){
				$.prompt('<p>As you\'re under 18 you won\'t be able to book hotels but you can see your feedback and recommended hotels just for fun. Continue?</p>',{ 
					buttons: { Yes: true, No: false }, 
					focus: 0, 
					opacity: 0.5, 
					overlay: "fast", 
					promptspeed: "fast", 
					show: "fadeIn", 
					callback: function(v,m){
						if(v){
							$('#profileContentForm').submit();
							return false;
						}else{
							demoSubmitCount = 0;
							return false;
						}
					}
				});
				demoSubmitCount = 1;
			}
		}else{
			pageTracker._trackPageview('/action/submitQuiz');
			$('#profileContentForm').submit();
		}
	},
	
	/**
 	* validates and sends forgotten password form
 	*/
	sendForgotPswdForm : function(){
		var email 		= $("#forgotPswdEmail").val();
		if(!email.length||!hotelsdotcom.checkEmail(email)){
			if($("p#pswd-error")){
				$("p#pswd-error").remove();
				$("#forgotPswdError").hide();
			}
			var error		= document.createElement('P');
			error.id		= "pswd-error";
			error.innerHTML	= "You must enter a valid email address";
			$("#forgotPswdError").append(error);
			$("#forgotPswdError").fadeIn("slow");
			return;
		}
		$.ajax({
			type: "POST",
			url: "/users/forgottenPassword",
			data: '&data[ForgottenPassword][email]=' + $("#forgotPswdEmail").val(),
			error: function(data){
				hotelsdotcom.createErrorText('hotelsdotcom.sendForgotPswdForm',data);
				if($("p#pswd-error")){
					$("p#pswd-error").remove();
					$("#forgotPswdError").hide();
				}
				var error		= document.createElement('P');
				error.id		= "pswd-error";
				error.innerHTML	= "Sorry, we've hit a problem. Please try again later.";
				$("#forgotPswdError").append(error);
				$("#forgotPswdError").fadeIn("slow");
				return;
			},
			success: function(data){
				var data = $.parseJSON(data);
				if(data["errorMessage"]){
					if($("p#pswd-error")){
						$("p#pswd-error").remove();
						$("#forgotPswdError").hide();
					}
					var error		= document.createElement('P');
					error.id		= "pswd-error";
					error.innerHTML	= data["errorMessage"];
					$("#forgotPswdError").append(error);
					$("#forgotPswdError").fadeIn("slow");
					return;
				}
				if(data["okMessage"]){
					if($("p#pswd-error")){
						$("p#pswd-error").remove();
						$("#forgotPswdError").hide();
					}
					var error		= document.createElement('P');
					error.id		= "pswd-error";
					error.innerHTML	= "<span class=\"okMessage\">" + data["okMessage"] + "</span>";
					$("#forgotPswdError").append(error);
					$("#forgotPswdError").fadeIn("slow");
					return;
				}
			}
		});
	},
	
	/**
 	* readies the create trip form
 	*/
	innitCreateTripForm : function(){
		if($("#createTripForm")){
			$("#createTripForm > a.button").click(function(){
				hotelsdotcom.sendCreateTripForm();
			});
		}
	},
	
	/**
 	* validates and sends create trip form
 	*/
	sendCreateTripForm : function(){
		var name 		= $("#createTripName").val();
		if(!name.length){
			if($("p#create-error")){
				$("p#create-error").remove();
				$("#createTripError").hide();
			}
			var error		= document.createElement('P');
			error.id		= "create-error";
			error.innerHTML	= "You must enter a name for this trip";
			$("#createTripError").append(error);
			$("#createTripError").fadeIn("slow");
			return;
		}
		alert("send");
	},
	
	/**
 	* validates and sends newsletter request form
 	*/
	sendNewsLetterForm : function(){
		var firstName 		= $("#newsLetterFirstName").val();
		var lastName 		= $("#newsLetterLastName").val();
		var email 		= $("#newsLetterEmail").val();
		var cEmail 		= $("#newsLetterEmailConfirm").val();
		if(!firstName.length){
			if($("p#register-error")){
				$("p#register-error").remove();
				$("#noDestError").hide();
			}
			var error		= document.createElement('P');
			error.id		= "register-error";
			error.innerHTML	= "You must enter a first name";
			$("#newsLetterError").append(error);
			$("#newsLetterError").fadeIn("slow");
			return;
		}
		if(!lastName.length){
			if($("p#register-error")){
				$("p#register-error").remove();
				$("#noDestError").hide();
			}
			var error		= document.createElement('P');
			error.id		= "register-error";
			error.innerHTML	= "You must enter a last name";
			$("#newsLetterError").append(error);
			$("#newsLetterError").fadeIn("slow");
			return;
		}
		if(firstName.indexOf('&')!=-1){
			if($("p#register-error")){
				$("p#register-error").remove();
				$("#noDestError").hide();
			}
			var error		= document.createElement('P');
			error.id		= "register-error";
			error.innerHTML	= "Please enter your first name, omitting the '&amp;'."
			$("#newsLetterError").append(error);
			$("#newsLetterError").fadeIn("slow");
			return;
		}
		if(lastName.indexOf('&')!=-1){
			if($("p#register-error")){
				$("p#register-error").remove();
				$("#noDestError").hide();
			}
			var error		= document.createElement('P');
			error.id		= "register-error";
			error.innerHTML	= "Please enter your last name, omitting the '&amp;'."
			$("#newsLetterError").append(error);
			$("#newsLetterError").fadeIn("slow");
			return;
		}
		if(!email.length||!hotelsdotcom.checkEmail(email)){
			if($("p#register-error")){
				$("p#register-error").remove();
				$("#newsLetterError").hide();
			}
			var error		= document.createElement('P');
			error.id		= "register-error";
			error.innerHTML	= "You must enter a valid email address";
			$("#newsLetterError").append(error);
			$("#newsLetterError").fadeIn("slow");
			return;
		}
		if(email!=cEmail){
			if($("p#register-error")){
				$("p#register-error").remove();
				$("#newsLetterError").hide();
			}
			var error		= document.createElement('P');
			error.id		= "register-error";
			error.innerHTML	= "Your email addresses do not match";
			$("#newsLetterError").append(error);
			$("#newsLetterError").fadeIn("slow");
			return;
		}
		$.ajax({
			type: "POST",
			url: "/users/signupNewsletter/",
			data: '&data[Signup][firstName]=' + $("#newsLetterFirstName").val() + '&data[Signup][lastName]=' + $("#newsLetterLastName").val() + '&data[Signup][email]=' + $("#newsLetterEmail").val() + '&data[Signup][confirmEmail]=' + $("#newsLetterEmailConfirm").val(),
			error: function(data){
				hotelsdotcom.createErrorText('hotelsdotcom.sendNewsLetterForm',data);
				if($("p#register-error")){
					$("p#register-error").remove();
					$("#newsLetterError").hide();
				}
				var error		= document.createElement('P');
				error.id		= "register-error";
				error.innerHTML	= "Sorry, we've hit a problem. Please try again later.";
				$("#newsLetterError").append(error);
				$("#newsLetterError").fadeIn("slow");
				return;
			},
			success: function(data){
				var data = $.parseJSON(data);
				if(data["errorMessage"]){
					if($("p#register-error")){
						$("p#register-error").remove();
						$("#newsLetterError").hide();
					}
					var error		= document.createElement('P');
					error.id		= "register-error";
					error.innerHTML	= data["errorMessage"];
					$("#newsLetterError").append(error);
					$("#newsLetterError").fadeIn("slow");
					return;
				}
				if(data["okMessage"]){
					if($("p#register-error")){
						$("p#register-error").remove();
						$("#newsLetterError").hide();
					}
					var error		= document.createElement('P');
					error.id		= "register-error";
					error.innerHTML	= "<span class=\"okMessage\">" + data["okMessage"] + "</span>";
					$("#newsLetterError").append(error);
					$("#newsLetterError").fadeIn("slow");
					return;
				}
				pageTracker._trackPageview('/action/joinNewsletter');
			}
		});
	},
	
	/**
 	* makes the book scrollable
 	*/
	createScrollPanal : function(){
		$("a#scrollPanelUp").mouseover(function(){
			hotelsdotcom.scrollPanelUp();
		});
		
		$("a#scrollPanelUp").mouseout(function(){
			clearTimeout(upVar)
		});
		
		$("a#scrollPanelDown").mouseover(function(){
			hotelsdotcom.scrollPanelDown();
		});
		
		$("a#scrollPanelDown").mouseout(function(){
			clearTimeout(downVar)
		});
	},
	
	/**
 	* scroll the book down
 	*/
	scrollPanelDown : function(){
		var speed 			= 	2;
		var crossobj		=	document.getElementById("scrollPanelInner");
		var contentheight	=	crossobj.offsetHeight;
		if(parseInt(crossobj.style.top) >= (contentheight*(-1)+100)){
			crossobj.style.top = parseInt(crossobj.style.top) - speed + "px";
		}
		downVar = setTimeout("hotelsdotcom.scrollPanelDown()", 20)
	},
	
	/**
 	* scroll the book up
 	*/
	scrollPanelUp : function(){
		var speed 			= 	2;
		var crossobj		=	document.getElementById("scrollPanelInner");
		var contentheight	=	crossobj.offsetHeight;
		
		if(parseInt(crossobj.style.top)<=0){
			crossobj.style.top = parseInt(crossobj.style.top) + speed + "px";
		}
		upVar = setTimeout("hotelsdotcom.scrollPanelUp()", 20);
	},
	
	/**
 	* makes the editorial bit scrollable (need to combine with above)
 	*/
	createScrollPanalTwo : function(){
		$("a#scrollPanelUpTwo").mouseover(function(){
			hotelsdotcom.scrollPanelUpTwo();
		});
		
		$("a#scrollPanelUpTwo").mouseout(function(){
			clearTimeout(upVarTwo)
		});
		
		$("a#scrollPanelDownTwo").mouseover(function(){
			hotelsdotcom.scrollPanelDownTwo();
		});
		
		$("a#scrollPanelDownTwo").mouseout(function(){
			clearTimeout(downVarTwo)
		});
	},
	
	/**
 	* scroll the editorial bit scrollable down (need to combine with above) 
 	*/
	scrollPanelDownTwo : function(){
		var speed 			= 	2;
		var crossobj		=	document.getElementById("editorialTextInner");
		var contentheight	=	crossobj.offsetHeight;
		if(parseInt(crossobj.style.top) >= (contentheight*(-1)+100)){
			crossobj.style.top = parseInt(crossobj.style.top) - speed + "px";
		}
		downVarTwo = setTimeout("hotelsdotcom.scrollPanelDownTwo()", 20)
	},
	
	/**
 	* scroll the editorial bit scrollable up (need to combine with above) 
 	*/
	scrollPanelUpTwo : function(){
		var speed 			= 	2;
		var crossobj		=	document.getElementById("editorialTextInner");
		var contentheight	=	crossobj.offsetHeight;
		if(parseInt(crossobj.style.top)<=0){
			crossobj.style.top = parseInt(crossobj.style.top) + speed + "px";
		}
		upVarTwo = setTimeout("hotelsdotcom.scrollPanelUpTwo()", 20);
	},
	
	/**
 	* sends slider details off
 	*/
	sendSliderRequest : function(id,value){
		var id = id.split("s")[1];
		$.ajax({
			type: "POST",
			url: "/products/adjustSliderInSession/" + id + "/" + value,
			error: function(data){
				hotelsdotcom.createErrorText('hotelsdotcom.sendSliderRequest',data);
			},
			success: function(data){
				var data = $.parseJSON(data);
				if(data=='{"ok":true}'){
					hotelsdotcom.getHotelResults();
				}
								
			}
		});
		pageTracker._trackPageview('/action/moveSlider/'+id+'/'+value);
	},
	
	/**
 	* resets sliders when user hit's "reset"
 	*/
	resetSliders : function(){
		$.ajax({
			type: "POST",
			url: "/products/resetSlidersInSession",
			error: function(){
			},
			success: function(data,e){
				var pagey = $("#sliders-buttons").offset().top;
				var pagex = $("#sliders-buttons").offset().left;
				var data = $.parseJSON(data);
				if(data=='{"ok":true}'){
					hotelsdotcom.getHotelResults();
				}else{
					hotelsdotcom.showMessageBox(Math.floor(Math.random()*101),"<p>Sorry, we were unable to reset your results. Please try again.</p>",2000,pagex,pagey,true,false);
				}
			}
		});
	},
	
	/**
 	* validates and sends the save-trip-after-slider-save
 	*/
	sendSaveSliders: function(){
		$("#save-sliders").click(function(){
			$.ajax({
				type: "POST",
				url: "/teams/saveSliders/",
				error: function(){
				},
				success: function(data){
					$("#save-sliders").addClass("hide");
				}
			});
		});
	},
	
	/**
 	* checks if an integer is a float
 	*/
	isFloat : function(s){
		return s.length>0 && !(/[^0-9.]/).test(s) && (/\.\d/).test(s);
	},
	
	/**
 	* initialises the slider instruction message
 	*/
	innitSliderMessage : function(){
		$("#what-is-this").mouseover(function(e){
			var messageBoxId = "messageBox" + this.id;
			if(!$("#"+messageBoxId).length>0)
				var text = "<p>We match hotels by your preferred style first, and then by star rating. So sometimes a pricey hotel might come first if we think it really matches your personal style... even if you're up for a lower cost option.</p>";
				var x = (e.pageX-450);
				hotelsdotcom.showMessageBox(this.id,text,false,x,e.pageY,false,"450");
		});
		$("#what-is-this").mouseout(function(){
			var messageBoxId = "messageBox" + this.id;
			if($("#"+messageBoxId).length>0)
				$("#"+messageBoxId).remove();
		});
		
		$("#toggleFeedback").click(function(){
			$("#toggleFeedback .controls").toggle();
			$("#top-panel").slideToggle();
		});
	},
	
	/**
 	* initialises the bookmarks instruction message
 	*/
	innitBookmarkMessage : function(){
		$("#what").mouseover(function(e){
			var messageBoxId = "messageBox" + this.id;
			if(!$("#"+messageBoxId).length>0)
				var text = "<p>Use these social bookmarking links to store, tag and share the Hotels.com Visualiser across the internet.</p>";
				var x = (e.pageX-325);
				hotelsdotcom.showMessageBox(this.id,text,false,x,e.pageY,false,"325");
		});
		$("#what").mouseout(function(){
			var messageBoxId = "messageBox" + this.id;
			if($("#"+messageBoxId).length>0)
				$("#"+messageBoxId).remove();
		});
	},
	
	/**
 	* grabs the flickr photos for the hotel popup
 	*/
	getFlickrPhotos : function(long, lat, totalToShow){
		$.ajax({
			type: "GET",
			url: "/thirdParty/getFlickrImages/?long="+long+"&lat="+lat,
			error: function(){
				// lets not show an error. if we can't display them, no probs
			},
			success: function(data){
				var response = $.parseJSON(data);
				if(response.photos.total>0){
					var totalPics = (response.photos.total>totalToShow)? totalToShow:response.photos.total;
					var photo = response.photos.photo;
					var flickrUL = document.createElement("UL");
					for(i=0;i<totalPics;i++){
						var flickrLI = document.createElement("LI");
						$(flickrLI).attr("class",i);
						$(flickrLI).html('<span><span><a href="javascript:void(0)">'+hotelsdotcom.adjustImage('http://farm'+ photo[i].farm +'.static.flickr.com/'+ photo[i].server +'/'+ photo[i].id +'_'+ photo[i].secret +'.jpg',78,48,false,true)+'</a></span></span>');
						$(flickrUL).append($(flickrLI));
					}
					$("#flickr-pics-container").append($(flickrUL));
					hotelsdotcom.innitCarousel("product-flickr-pics",false)
					$('#product-flickr-pics').removeClass("flickr-toggle");
					var currentMax = 4;
					if(totalPics<currentMax){
						currentMax = totalPics;	
					}
					$("#flickr-current-max").html(currentMax);
					$("#flickr-total").html(totalPics);
				}
			}
		});
	},
	
	/**
 	* deals with the voting in the 'popup'
 	*/
	popupVoting: function( productId ){
		$($("#votes dt")[0]).click(function(e){
				$.ajax({
					type: "GET",
					url: "/votes/makeVote/"+ productId +"/+1",
					// NEED ACTIONS
					error: function(data){
						hotelsdotcom.createErrorText('hotelsdotcom.popupVoting.positive',data);
						hotelsdotcom.showMessageBox(productId,"<p>Sorry, we were unable to register your vote. Please try again.</p>",2000,e.pageX,e.pageY,true,false);
					},
					success: function(data){
						var data = $.parseJSON(data);
						if(data["errorMessage"]){
							hotelsdotcom.showMessageBox(productId,"<p>"+ data['errorMessage'] + "</p>",2000,e.pageX,e.pageY,true,false);
							return;
						}
						var posVoteText = $(e.target).parent().siblings()[0];
						var negVoteText = $(e.target).parent().siblings()[2];
						
						$(posVoteText).html("" + data['positives'] + "");
						$(negVoteText).html("" + data['negatives'] + "");
						hotelsdotcom.showMessageBox(productId,"<p>Thank you, your positive vote has been counted.</p>",2000,e.pageX,e.pageY,true,false);
						
						//update the user votes
						posUserVoteNames = new Array();
						$(data['positiveUsers']).each( function(j){
							if(data['positiveUsers'][j]['userDisplayName'] != null){ posUserVoteNames.push(data['positiveUsers'][j]['userDisplayName']); }
						});
						negUserVoteNames = new Array();
						$(data['negativeUsers']).each( function(j){
							if(data['negativeUsers'][j]['userDisplayName'] != null){ negUserVoteNames.push(data['negativeUsers'][j]['userDisplayName']); }
						});
						
						//do the updates on the results grid
						$($("#votecount" + productId).children()[1]).html("" + data['positives'] + "");
						$($("#votecount" + productId).children()[3]).html("" + data['negatives'] + "");
						$($("#votecount" + productId).children()[1]).attr('alt', posUserVoteNames.join(', '));
						$($("#votecount" + productId).children()[3]).attr('alt', negUserVoteNames.join(', '));
						hotelsdotcom.getSPHotelsList();
						
						pageTracker._trackPageview('/action/vote/pos');
						
						return;
					}
				});
		});
		$($("#votes dt")[1]).click(function(e){
				$.ajax({
					type: "GET",
					url: "/votes/makeVote/"+ productId +"/-1",
					// NEED ACTIONS
					error: function(data){
						hotelsdotcom.createErrorText('hotelsdotcom.popupVoting.negative',data);
						hotelsdotcom.showMessageBox(productId,"<p>Sorry, we were unable to register your vote. Please try again.</p>",2000,e.pageX,e.pageY,true,false);
					},
					success: function(data){
						var data = $.parseJSON(data);
						if(data["errorMessage"]){
							hotelsdotcom.showMessageBox(productId,"<p>"+ data['errorMessage'] + "</p>",2000,e.pageX,e.pageY,true,false);
							return;
						}
						
						var posVoteText = $(e.target).parent().siblings()[1];
						var negVoteText = $(e.target).parent().siblings()[2];
						
						$(posVoteText).html("" + data['positives'] + "");
						$(negVoteText).html("" + data['negatives'] + "");
						hotelsdotcom.showMessageBox(productId,"<p>Thank you, your negative vote has been counted.</p>",2000,e.pageX,e.pageY,true,false);
					
						//update the user votes
						posUserVoteNames = new Array();
						$(data['positiveUsers']).each( function(j){
							if(data['positiveUsers'][j]['userDisplayName'] != null){ posUserVoteNames.push(data['positiveUsers'][j]['userDisplayName']); }
						});
						negUserVoteNames = new Array();
						$(data['negativeUsers']).each( function(j){
							if(data['negativeUsers'][j]['userDisplayName'] != null){ negUserVoteNames.push(data['negativeUsers'][j]['userDisplayName']); }
						});
					
						//do the updates on the results grid
						$($("#votecount" + productId).children()[1]).html("" + data['positives'] + "");
						$($("#votecount" + productId).children()[3]).html("" + data['negatives'] + "");
						$($("#votecount" + productId).children()[1]).attr('alt', posUserVoteNames.join(', '));
						$($("#votecount" + productId).children()[3]).attr('alt', negUserVoteNames.join(', '));
						hotelsdotcom.getSPHotelsList();
					
						pageTracker._trackPageview('/action/vote/neg');
					
						return;
					}
				});
			});
		$($("#votes dd")[0]).mouseover(function(e){
			if($(this).attr('alt') != undefined && $(this).attr('alt') != ''){
				hotelsdotcom.showMessageBox('PopupVotesPos',"<p>The following people like this hotel:<br />" + $(this).attr('alt') + "</p>",false,e.pageX,e.pageY,false,false);
				$(this).css("cursor","help");
			}
			return;
		});
		$($("#votes dd")[1]).mouseover(function(e){
			if($(this).attr('alt') != undefined && $(this).attr('alt') != ''){
				hotelsdotcom.showMessageBox('PopupVotesNeg',"<p>The following people don't like this hotel:<br />" + $(this).attr('alt') + "</p>",false,e.pageX,e.pageY,false,false);
				$(this).css("cursor","help");
			}
			return;
		});
		$($("#votes dd")[0]).mouseout(function(e){
			//close the messageBox
			$('#messageBoxPopupVotesPos').remove();
			$(this).css("cursor","default");
			return;
		});
		$($("#votes dd")[1]).mouseout(function(e){
			$('#messageBoxPopupVotesNeg').remove();
			$(this).css("cursor","default");
			return;
		});
	},
	
	/**
 	* notifies the server of a click event
 	*/
	adtrackerAddClickEvent: function( cssSelector, trackerUrl, redirectUrl ){
		$(cssSelector).click(function(e){
			$.ajax({
				type: "GET",
				url: trackerUrl,
				error: function(data){
					return true; //don't stop the clickthrough
				},
				success: function(data){
					return true;
				}
			});
		});

	},
	
	
	/**
 	* deals with the drop downs changing in the editorial bit
 	*/
	initMagicCarpet: function( teamId ){
		$("#magicCarpetDistricts").change(function(e){
			var url = '/teams/show/' + teamId + '/' + e.target.value;
			pageTracker._trackPageview('/action/changeDistrict/'+e.target.value);
			document.location = url;
			return;
		});
		$("#magicCarpetCities").change(function(e){
			var url = '/teams/changeMarketName/' + teamId + '/' + e.target.value;
			pageTracker._trackPageview('/action/changeCity/'+escape(e.target.value));			
			document.location = url;
			return;
		});
	},
	
	/**
 	* resizes and crops an image to passed size
 	*/
	
	adjustImage: function(src,width,height,bordered,dofix){
		var img = new Image();
		img.src = src;
		var imgW = img.width;
		var imgH = img.height;
		var size, tempHeight, tempWidth;
		
		var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
		if(!IE6){
            var loopCount = 0;
			while(imgW==0 && loopCount < 500){
				img = new Image();
				img.src = src;
				imgW = img.width;
				imgH = img.height;
                loopCount++;
			}	
		}
		
		if(dofix){
			if(bordered){
				width = width + 2;
				height = height + 2;
			}
			// image hasn't preloaded so all we can do is do a straight resize
			if(imgW==0||imgH==0){
				size = 'height="'+height+'" width="'+width+'"';	
			}else{
				// calculate the smallest dimension, and resize it
				if(imgW<=imgH){
					tempHeight = height;
				}else{
					tempWidth = width;
				}
				// check to see if the resulting opposite dimension is ok
				if(imgW<=imgH){
					if(hotelsdotcom.getVirtualImageSize(imgW, imgH, "height", tempHeight)<width){
						size = 'width="'+width+'"';	
					}else{
						size = 'height="'+height+'"';	
					}
				}else{
					if(hotelsdotcom.getVirtualImageSize(imgW, imgH, "width", tempWidth)<height){
						size = 'height="'+height+'"';	
					}else{
						size = 'width="'+width+'"';	
					}
				}
			}
			style = "clip:rect(0 "+width+"px "+height+"px 0);";
			if(bordered){
				style = "clip:rect(1px "+(width-1)+"px "+(height-1)+"px 1px); top: -1px; left: -1px;"
			}
			var image = '<img rel="'+imgW+'-'+imgH+'" src="'+img.src+'" '+size+' style="'+style+'" />';
			return image;
		}else{
			var image = '<img rel="'+imgW+'-'+imgH+'" src="'+img.src+'" />';
			return image;
		}
	},
	
	/**
 	* calculates the resulting dimenion of an image when you resize he alternate dimension
	* in othe words, if i resize the width of an image, keeping the same ration, what would the resulting height be
	* width = integer. the original width of the image
	* height = integer. the original height of the image
	* newSizeType = string. do you already know the "width" or the "height"?
	* newSize = integer. the integer value of the dimension passed in newSizeType
 	*/
	getVirtualImageSize: function(width, height, newSizeType, newSize){
		var newSizeDiff, resultingSize;
		if(newSizeType=="width"){
			if(width>newSize){
				newSizeDiff = parseInt("-" + (width - newSize));
			}else if(newSize>width){
				newSizeDiff = newSize - width;
			}else{
				newSizeDiff = 0;
			}
			resizeRatio = newSizeDiff/(width/100)
			resultingSize = parseInt((height+((height/100)*resizeRatio))+1);
		}else{
			if(height>newSize){
				newSizeDiff = parseInt("-" + (height - newSize));
			}else if(newWidth>width){
				newSizeDiff = newSize - height;
			}else{
				newSizeDiff = 0;
			}
			resizeRatio = newSizeDiff/(height/100)
			resultingSize = parseInt((width+((width/100)*resizeRatio))+1);
		}
		return resultingSize;
	},
	
	/**
	* inline editing
 	*/
	clickToEdit: function(){
		var img = new Image;
		img.src = "/img/general/text-loader.gif";
		$("#resultsHeader .inplaceClick").editable('/teams/inlineSaveTeam', {
			style : 'inherit',
			tooltip   : 'Click to edit...',
			indicator : img,
			onblur: 'submit',
			callback: function(value,settings){
				if($("#activeTripLink").html()!==value){
					$("#activeTripLink").html(value);
				}
			}
		});
		$("#resultsHeader .edit").click(function(){
			$("#resultsHeader .inplaceClick").click();
		});
	},
	
	popup : function (href, params){
		// Defaults (don't leave it to the browser)
		var defaultParams = {
			"width":       "700",   // Window width
			"height":      "400",   // Window height
			"top":         "50",     // Y offset (in pixels) from top of screen
			"left":        "50",     // X offset (in pixels) from left side of screen
			"directories": "no",    // Show directories/Links bar?
			"location":    "no",    // Show location/address bar?
			"resizeable":  "yes",   // Make the window resizable?
			"menubar":     "no",    // Show the menu bar?
			"toolbar":     "no",    // Show the tool (Back button etc.) bar?
			"scrollbars":  "yes",   // Show scrollbars?
			"status":      "no"     // Show the status bar?
		};
	
		var windowName = params["windowName"] || "new_window";
	
		var i, useParams = "";
	
		// Override defaults with custom values while we construct the params string
		for (i in defaultParams){
			useParams += (useParams === "") ? "" : ",";
			useParams += i + "=";
			useParams += params[i] || defaultParams[i];
		}
	
		return window.open(href, windowName, useParams);
	},
	
	getPopUpLinks : function(){
	// Apply this code to each link with class="popup"
		$("#bookmark-us > ul > li > a").each(function (i){
			$(this).click(function(event) {
				event.preventDefault();
				var params = $(this).data("popup") || {};            
				if ($(this).attr("target")){
					params.windowName = $(this).attr("target");
				}
				var windowObject = hotelsdotcom.popup(this.href, params);
				$(this).data("windowObject", windowObject);
			});
		});
	},
	
	fireAdvivaClickthruEvent : function(id){
		var ans_timestamp = (new Date()).getTime();
		var i = new Image();
		i.src="http://ads.adviva.net/track/v=4;m=1;t="+id+"ts=" + ans_timestamp + "\" width=\"1\" height=\"1\" border=\"0\" />";
    
        pageTracker._trackPageview('/action/checkAvailability');
		return;
	}

}