// This file relies on having the version functions loaded in versionfunc.vtl

	var origTop;
	var origLeft;
		
	var oldUserRating = null;

	var clipTop = 0;
	var clipWidth = 500;
	var clipBottom = 0;
	var topper = 450;
	var lyrheight = 0;
	var pictureArray = new Array();
	var curImg;
	var curPhotoIndex = 0;
	var rating = 0;

        var loginURL = 'http://login.kayak.com/';
        var cancelShare = 0;

        var globalShareType;
        var globalObjID;
        var globalSendURL;
	
	/*
	** Used to set intial coord of content div
	*/
	function setInitialCoord()
	{
	        // No longer clipping to given height
	        return;
		var contentdiv = document.getElementById('divContent');
		origTop = contentdiv.style.top;
		origLeft = contentdiv.style.left;
		setDivHeight('divContent', false)
		setExpandLink();
		clipDiv('divContent');
		contentdiv.style.visibility = 'visible';
		
	}
	
	/*
	** Sets up photo area based on # of photos
	*/
	function initPhotos(hotelid)
	{
		if (pictureArray.length > 0) {
			curPhotoIndex = 0;
			//if ( pictureArray[0].thumburl != "/photocomingsoon.gif") {
			//	document.getElementById('imageFullLink').href = "/h/hotel/hotelphotos.vtl?photoidx=" + curPhotoIndex + "&hid=" + hotelid;
			//}
			document.getElementById('displayImage').src = pictureArray[0].thumburl;
			document.getElementById('displayImage').border = 1;
		}
		/* Arrows are gone
		if (pictureArray.length > 1) {
			document.getElementById('nextPhoto').style.visibility = 'visible';
			document.getElementById('prevPhoto').style.visibility = 'visible';
			document.getElementById('photoText').style.visibility = 'visible';
		}
		*/
	}

	/*
	** Used to set rating area visuals based on rating - this is a long float, fix up
	*/
	function initRating()
	{
		if ((rating - 0) > 0 ) {
                    document.getElementById("hotelRating").src = '/images/orangestars-' + rating + '.gif';
                    document.getElementById("hotelRating").style.visibility='visible';
                }
	}
	
	/*
	** Used to changed thumbnail photo with link displayed.
	*/
	function nextPhoto(increment, hotelid)
	{
		curPhotoIndex += increment;
		if (curPhotoIndex >= pictureArray.length) {
			curPhotoIndex = 0;
		} else if (curPhotoIndex < 0) {
			curPhotoIndex =  (pictureArray.length - 1);
		}
		document.getElementById('curPhotoID').innerHTML = (curPhotoIndex + 1);
		document.getElementById('imageFullLink').href = getProductVersionURI() + "/h/hotel/hotelphotos.vtl?photoidx=" + curPhotoIndex + "&hid=" + hotelid;
		document.getElementById('displayImage').src = pictureArray[curPhotoIndex].thumburl;
	}
	
	/*
	** Used to change full size photo being displayed.
	*/
	function nextFullPhoto(increment)
	{
		curPhotoIndex += increment;
		if (curPhotoIndex >= pictureArray.length) {
			curPhotoIndex = 0;
		} else if (curPhotoIndex < 0) {
			curPhotoIndex =  (pictureArray.length - 1);
		}
		document.getElementById('curPhotoID').innerHTML = (curPhotoIndex + 1);
		document.getElementById('displayImage').src = pictureArray[curPhotoIndex].url;
		document.getElementById('sourcetext').innerHTML = pictureArray[curPhotoIndex].source;
	}
	
	/*
	** Sets height of contentdiv
	*/
	function setDivHeight(name, isHidden)
	{
		var contentdiv = document.getElementById(name);
		if (isHidden != null && isHidden) {
			contentdiv.style.display = 'block';
		}
		
		if (document.layers)
		{
			lyrheight = contentdiv.style.clip.bottom;
			lyrheight += 20;
		} else if (document.getElementById || document.all) {
			lyrheight = contentdiv.offsetHeight;
		}
		if (isHidden != null && isHidden) {
			contentdiv.style.display = 'none';
		}
	}		
	/*
	** Sets display/text of expand/collapse link for content div
	*/
	function setExpandLink()
	{
		// Only show expand link if we need to
		if (lyrheight < clipBottom) {
			document.getElementById('sizeControlLink').style.visibility = 'hidden';
		} else {
			document.getElementById('sizeControlLink').style.visibility = 'visible';
			document.getElementById('sizeControlLink').innerHTML = 'Expand';
		}
	}
	/*
	** Changes content of contentdiv when tab is clicked
	*/
	function changeContent(section)
	{
		var contentdiv = document.getElementById('divContent');
		if (section == 'description') {
			//setDivHeight('descriptionDiv', true);
			contentdiv.innerHTML = document.getElementById('descriptionDiv').innerHTML;
		} else if (section == 'amenities') {
			//setDivHeight('amenitiesDiv', true);
			contentdiv.innerHTML = document.getElementById('amenitiesDiv').innerHTML;
		} else if (section == 'policies') {
			//setDivHeight('policiesDiv', true);
			contentdiv.innerHTML = document.getElementById('policiesDiv').innerHTML;
		} else if (section == 'roomtypes') {
			//setDivHeight('roomTypesDiv', true);
			contentdiv.innerHTML = document.getElementById('roomTypesDiv').innerHTML;
		}
		setSelectedTab(section);
                contentdiv.style.display = 'block';
                contentdiv.style.visibility = 'visible';
		//contentdiv.style.height = clipBottom;
		//clipDiv('divContent');
		setExpandLink();
	}
	/*
	** Sets style of selected tab
	*/
	function setSelectedTab(section)
	{
		document.getElementById('tabDescription').className = (section == 'description') ? 'tabHeadingTDSelected' : 'tabHeadingTD';
		document.getElementById('tabAmenities').className = (section == 'amenities') ? 'tabHeadingTDSelected' : 'tabHeadingTD';
		document.getElementById('tabPolicies').className = (section == 'policies') ? 'tabHeadingTDSelected' : 'tabHeadingTD';
		//document.getElementById('tabRoomTypes').className = (section == 'roomtypes') ? 'tabHeadingTDSelected' : 'tabHeadingTD';
	
	}
	/*
	** Sets style of highlighted tab
	*/
	function highlightHeading(section)
	{
		if (section.className == 'tabHeadingTD') {
			section.className = 'tabHeadingTDOver'

			if (isIE5dotX()) {
			    section.style.cursor = 'hand';
			} else {
			    section.style.cursor = 'pointer';
			}
		}
	}
	/*
	** Unhighlights highlighted tab
	*/
	function unHighlightHeading(section)
	{
		if (section.className == 'tabHeadingTDOver') {
			section.className = 'tabHeadingTD'
			section.style.cursor = 'default';
		}
	}
	/*
	** Clip div to defined settings
	*/
	function clipDiv(name) {

		var contentdiv = document.getElementById(name);
		if (document.layers)
		{
			contentdiv.style.clip.top = clipTop;
			contentdiv.style.clip.left = 0;
			contentdiv.style.clip.right = clipWidth;
			contentdiv.style.clip.bottom = clipBottom;
			contentdiv.style.height = clipBottom;
			contentdiv.style.top = topper;
		} else if (document.getElementById || document.all) {
			contentdiv.style.height = clipBottom;
			contentdiv.style.top = topper;
			contentdiv.style.clip = 'rect('+clipTop+' '+clipWidth+' '+clipBottom+' 0)'
		}
	}
	
	/*
	** Called to expand/collapse content div
	*/
	function scrollContentDiv()
	{
		var theDiv = document.getElementById('divContent');
		var sizeLink = document.getElementById('sizeControlLink');
		if (theDiv.style.height == 'auto') {
			//clipDiv('divContent');
			//sizeLink.innerHTML = 'Expand';
			theDiv.style.height = 0;
			sizeLink.innerHTML.style.visbility = 'hidden';
		} else {
			if (clipBottom < lyrheight) {
				theDiv.style.height = 'auto';
				sizeLink.innerHTML = 'Collapse';
			}
		}
	}
	// Mouseover on rating td
	function uro(obj)
	{
		if (obj.className == 'ratingTDSelected') return;

		obj.style.cursor = 'hand';
		obj.className = 'ratingTDHover';
	}
	
	// Mouseout on rating td
	function cur(obj)
	{
		if (obj.className == 'ratingTDSelected') return;
		obj.className = 'ratingTDUnselected';
	}
	
	function urc(obj, starnum, hotelid, sessionid)
	{
	        if (oldUserRating != null && oldUserRating.id == obj.id) return;

		//if (userRatingGiven) return;
		if (oldUserRating != null) {
		    oldUserRating.className = 'ratingTDUnselected';
		}
		oldUserRating = obj;
		obj.className = 'ratingTDSelected';

		var client = new R9HTTPXml();
                client.init(getProductVersionURI() + '/h/affinity?action=hotelrating&hid=' + hotelid + '&rating=' + starnum + "&sid=" + escape(sessionid), null, null);

		try {
			client.asyncGET(new pUserRating());
		} catch (e) {
			alert(e);
		}
	}

	function submitcommentnew()
	{
	    if (document.userForm["body"].value.length > 2) {
	        document.userForm.submit();
            } else {
                alert('Please enter some text before submitting your commment.');
            }
	}

	function submitcomment(commenttype, sessionid, theid, title)
	{
		if (document.userForm["feedbackText"].value.length > 2) {
			var postString = "";
			if (commenttype == "hotel") {
			    postString += "hid=" + theid;
			    postString += "&action=hotelcomment";
			} else if (commenttype == "city") {
			    postString += "ctid=" + theid;
			    postString += "&action=citycomment";
			}
			postString += '&sid=' + escape(sessionid);
			if (title != null) {
				postString += "&title=" + escape(title);
			} else {
				postString += "&title=";
			}
			postString += "&body=" + escapeForXML(document.userForm["feedbackText"].value);
			var client = new R9HTTPXml();
			client.init(getProductVersionURI() + '/h/affinity', postString, null);
			try {
				client.asyncGET(new pComment());
			} catch (e) {
				alert(e);
			}
		} else {
			alert('Please enter some text before submitting your commment.');
		}
	}

	// Called when answering y/n to member comment
	function rfback(sessionid, feedback, commentid, listid)
	{
		var postString="cid=" + escape(commentid);
		postString += "&action=feedback";
		postString += "&useful=" + feedback;
		postString += '&sid=' + escape(sessionid);

		var client = new R9HTTPXml();
		client.init(getProductVersionURI() + '/h/affinity', postString, null);
		try {
			client.asyncGET(new pCommentFBack());
		} catch (e) {
			alert(e);
		}
		
		// Hide the section
		var toHide = document.getElementById("con" + listid);
		var toShow = document.getElementById("coff" + listid);
		
		toHide.style.display = 'none';
		toShow.style.display = 'inline';
	}
	
	
	function allcomments(type)
	{
	    if (window.location.href.indexOf("?") >= 0) {
		window.location.href = window.location.href + "&" + type + "=true";
	    } else {
	        window.location.href = window.location.href + "?" + type + "=true";
	    }
	}
	
	function bookIt(url)
	{
		document.location.href = url;
	}
	
	function getXandY(objToFind)
	{
		//var objToFind = document.getElementById(objName);
		var top = objToFind.offsetTop;
		var left = objToFind.offsetLeft;
	
		for (objToFind=objToFind.offsetParent; objToFind != null; objToFind=objToFind.offsetParent) {
			top = objToFind.offsetTop + top;
			left = objToFind.offsetLeft + left;
		}
	
		//Package up return object
		var returnCoord = new Object();
		returnCoord.x = left;
		returnCoord.y = top;
		
		return returnCoord;

	}
	
	/*
	** Move an absolutely positined element next to another element and set display
	*/
	function moveNextToAndShow(positionNextTo, objectName)
	{
		var objectToMove = document.getElementById(objectName);
		var coord = getXandY(positionNextTo);
		
		// For now set 5 px below object
		objectToMove.style.left = coord.x;
		objectToMove.style.top = (coord.y + positionNextTo.offsetHeight + 5);
		
		// Display it
		objectToMove.style.display = '';
	}
	
	/*
	** Used as empty function for links to not do anything
	*/
	function noop()
	{
	}
	
	
// handle onreadystatechange event for user rating
function pUserRating() {
    this.onLoad = function(xmlobj) {
        // only if req shows "loaded"
        if (xmlobj.xmlhttp.readyState == 4) {
            // only if "OK"
            if (xmlobj.xmlhttp.status == 200) {
                document.getElementById('ratingSaved').style.visibility = 'visible';
                document.getElementById('keywordArea').style.display = 'block';
             } else {
                alert("There was a problem submitting your comment:\n" + xmlobj.xmlhttp.statusText);
             }
        }
    }
    this.onError = function(status,statusText) {
       alert("Sorry, we could not save your rating please try again later.");
    }

}

// handle onreadystatechange event for user comment
function pComment() {
    this.onLoad = function(xmlobj) {
        // only if req shows "loaded"
        //alert(xmlobj.getText());
        if (xmlobj.xmlhttp.readyState == 4) {
            // only if "OK"
            if (xmlobj.xmlhttp.status == 200) {
                if (xmlobj.getText().length > 5) {
                    alert(xmlobj.getText());
                } else {
                    window.location.replace(window.location.href);
                }
             } else {
                alert("There was a problem submitting your comment:\n" + xmlobj.xmlhttp.statusText);
             }
        }
    }
    this.onError = function(status,statusText) {
       alert("Sorry, we could not save your comment please try again later.");
    }
}

// handle onreadystatechange event for user comment
function session_cb() {

    this.onLoad = function(xmlobj) {
        // only if req shows "loaded"
        if (xmlobj.xmlhttp.readyState == 4) {
            // only if "OK"
            if (xmlobj.xmlhttp.status == 200) {
                if (xmlobj.getText().indexOf('bad') >= 0) {
                    document.location.href=(xmlobj.uservars.loginURL);
                } else {
                    shareLink(xmlobj.uservars.globalShareType, xmlobj.uservars.globalObjID, xmlobj.uservars.globalSendURL);
                }
             } else {
             }
        }
    }
    this.onError = function(status,statusText) {
       alert("Sorry, we could not process your request.");
    }

}


function checkSession(sessionid, url, share, objid, sendurl)
{
    var args = new Object();
    args.globalShareType = share;
    args.globalObjID = objid;
    args.globalSendURL = sendurl;
    args.loginURL = url;

    var client = new R9HTTPXml();
    client.init(getProductVersionURI() + '/h/affinity', "action=session&sid=" + escape(sessionid), args);

    try {
        client.asyncGET(new session_cb());
    } catch (e) {
        alert(e);
    }
}


function pCommentFBack()
{
    // ignore errors on this one
    this.onLoad = function(xmlobj) {}
    this.onError = function(status,statusText) {}
}

function shareLink(shareType, objid, sendurl)
{
   var url = '/h/comment/share.vtl?linktype=' + shareType + '&id=' + objid +
             '&url=' + escape(sendurl);
   openSmallerWindow('share', url);
}

function keywordCBack()
{
    this.onLoad = function(xmlobj) {
        // only if req shows "loaded"
        if (xmlobj.xmlhttp.readyState == 4) {
            // only if "OK"
            if (xmlobj.xmlhttp.status == 200) {
                document.getElementById('keywordSaved').style.display = 'inline';
                document.getElementById('commentArea').style.display = 'block';
             } else {
             }
        }
    }
    this.onError = function(status,statusText) {
        alert("There was a problem submitting your atmosphere rating:\n" + xmlobj.xmlhttp.statusText);
    }
}

function atmClick(clickedCbox, hid, sessionid)
{
    if (clickedCbox.checked) {
        // Make sure we don't have 4 now
        var clickedcnt = 0;
        for (var i=0; i<document.keywordForm.atmosphere.length;i++) {
            if (document.keywordForm.atmosphere[i].checked) clickedcnt++;
        }
        if (clickedcnt > 3) {
            clickedCbox.checked = false;
            alert('You many only select up to three attributes.  Please uncheck another one if you wish to set this one.');
            return;
        }
    }

    var client = new R9HTTPXml();
    var args = "action=setkeyword&keyword=" +  clickedCbox.value + "&sid=" + escape(sessionid) + '&keytoggle=' + ((clickedCbox.checked) ? 'true' : 'false');
    args += '&hid=' + hid;
    
    client.init(getProductVersionURI() + '/h/affinity', args, null);
    
    try {
        client.asyncGET(new keywordCBack());
    } catch (e) {
        alert(e);
    }
}
