// what makes it work
var linkShareStuffHost = 'http://www.justonehotel.com/templates/j1h-default/';
var linkSharerContainer = null;
var linkSharerCloseTimerId = false;
var linkSharerOpenTimerId = false;
var linkSharerIncludedStylesheet = false;
var linkSharerCurrentTargetElement = null;

// styling info
var linkSharerBorderColor = '#c0c0c0';
var linkSharerColor = '#1a6998';
var linkSharerHeadColor = '#1a6998';
var linkSharerHeadBgColor = '#dddddd';
var linkSharerContentBgColor = '#fafafa';

// include the stylesheet
includeStyleSheet();

function includeStyleSheet()
{
	// include the stylesheet if we havent already
	if ( !linkSharerIncludedStylesheet )
	{
		var headID = document.getElementsByTagName( 'head' )[0];
		var styleEl = document.createElement( 'link' );
		styleEl.type = 'text/css';
		styleEl.rel = 'stylesheet';
		styleEl.href = linkShareStuffHost + 'styles/user_link_share.css';
		styleEl.media = 'screen';
		headID.appendChild( styleEl );
		linkSharerIncludedStylesheet = true;
	}
}

function linkShareAddSlashes( str )
{
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,"\\'");
	str=str.replace(/\"/g,'\\"');
	return str;
}

// hotelId can be null if you fancy it as such
function openLinkSharer( targetElement, shareUrl, shareTitle, hotelId )
{
	// dont open if there is a readystate variable and it's not 'completed'
	// otherwise IE throws the error "Internet Explorer cannot open the Internet site: Operation Aborted"
	// only IE has the onreadystate thingy
	if ( document.readyState && document.readyState!='complete' )
	{
		return false;
	}
	
	if ( linkSharerContainer )
	{
		if ( linkSharerCurrentTargetElement!=targetElement )
		{
			// If the link sharer is already open for a different target element then close it.
			closeLinkSharer( true );
		}
		else
		{
			// If it's already open for this target element then don't bother trying to open it again.
			// But cancel any previous close request.
			cancelTimedCloseLinkSharer();
			return true;
		}
	}

	// create the link sharer div
	linkSharerContainer = document.createElement('div');
	linkSharerContainer.style.zIndex = 102;
	linkSharerContainer.style.position = 'absolute';
	linkSharerContainer.style.width = '200px';
	linkSharerContainer.id = 'linkSharerContainer';
	linkSharerContainer.onmouseover = function( e ) { cancelTimedCloseLinkSharer(); }
	linkSharerContainer.onmouseout = function( e ) { closeLinkSharer();	}
	linkSharerContainer.style.visibility = 'hidden';
	
	// give it some content
	html = getLinkSharerContent( shareUrl, shareTitle, hotelId );
	linkSharerContainer.innerHTML = html;

	// put it in the right place
	
	document.body.appendChild(linkSharerContainer);
	applyLinkSharerPosition( targetElement );	
	
	// annnnnnd make it visible
	linkSharerOpenTimerId = setTimeout( 'showLinkSharer()', 500 );
	
	return true;
}


function showLinkSharer()
{
	linkSharerContainer.style.visibility = 'visible';
}

function linkSharerIsVisible()
{
	return linkSharerContainer.style.visibility=='visible';
}

// returns an html string with link sharing html in it
function getLinkSharerContent( shareUrl, shareTitle, hotelId )
{
	// these variables are url encoded and then escaped for echoing to javascript
	var urlEscapedShareUrl = linkShareAddSlashes( encodeURIComponent( shareUrl ) );
	var urlEscapedShareTitle = linkShareAddSlashes( encodeURIComponent( shareTitle ) );
	var urlEscapedHotelId = '';
	if ( hotelId )
	{
		urlEscapedHotelId = linkShareAddSlashes( encodeURIComponent( hotelId ) );
	}
	
	// these variables are just escaped for echoing to javascript
	var escapedShareUrl = linkShareAddSlashes( shareUrl );
	var escapedShareTitle = linkShareAddSlashes( shareTitle );
	var escapedHotelId = '';
	if ( hotelId )
	{
		escapedHotelId = linkShareAddSlashes( hotelId );
	}
	html = '<div class="linkSharerContent" style="border-color:' + linkSharerBorderColor + '">';
	html += '<div class="linkSharerTitle" style="background-color:'+linkSharerHeadBgColor+';border-color:' + linkSharerBorderColor + ';color:'+linkSharerHeadColor+'">Bookmark &amp; Share</div><div class="linkSharerServices" style="background-color:'+linkSharerContentBgColor+';">';
	html += '<table cellpadding="0" cellspacing="2">';
	html += '<tr>';
	html += '<td style="width:50%">';
	html += '<a style="color:'+linkSharerColor+'" href="javascript:void(0)" \
		target="_blank" onclick="userLinkShareLog( \'favorites\', \'' + escapedShareUrl + '\', \'' + 
		escapedShareTitle + '\', \'' + escapedHotelId + '\' );linkShareBookmark(\'' + escapedShareTitle + '\', \'' + escapedShareUrl + '\');return false;">' + 
		'<img src="' + linkShareStuffHost + 'images/user_link_share/fave.png" ' + 
		' width="14" height="14"> <span>Bookmark</span></a><br>';
	html += '</td>';
	html += '<td>';
	html += '<a style="color:'+linkSharerColor+'" href="http://del.icio.us/post?url=' + urlEscapedShareUrl + '&title=' + urlEscapedShareTitle + '" target="_blank" \
		onclick="return userLinkShareLog( \'delicious\', \'' + escapedShareUrl + '\', \'' + 
		escapedShareTitle + '\', \'' + escapedHotelId + '\' );">' + 
		'<img src="' + linkShareStuffHost + 'images/user_link_share/deli.png" ' + 
		' width="14" height="14"> <span>Del.icio.us</span></a><br>';
	html += '</td>';
	html += '</tr>';
	html += '<tr>';
	html += '<td>';
	html += '<a style="color:'+linkSharerColor+'" href="http://www.facebook.com/sharer.php?u=' + urlEscapedShareUrl + '" target="_blank" \
		onclick="return userLinkShareLog( \'facebook\', \'' + escapedShareUrl + '\', \'' + 
		escapedShareTitle + '\', \'' + escapedHotelId + '\' );">' + 
		'<img src="' + linkShareStuffHost + 'images/user_link_share/face.png" ' + 
		' width="14" height="14"> <span>Facebook</span></a><br>';
	html += '</td>';
	html += '<td>';
	html += '<a style="color:'+linkSharerColor+'" href="http://www.justonehotel.com/feeds/atom" \
		target="_blank" onclick="return userLinkShareLog( \'feeds\', \'' + escapedShareUrl + '\', \'' + 
		escapedShareTitle + '\', \'' + escapedHotelId + '\' );">' + 
		'<img src="' + linkShareStuffHost + 'images/user_link_share/rss.png" ' + 
		' width="14" height="14"> <span>Feeds</span></a><br>';
	html += '</td>';
	html += '</tr>';
	html += '<tr>';
	html += '<td>';
	html += '<a style="color:'+linkSharerColor+'" href="http://www.google.com/bookmarks/mark?op=add&bkmk=' + 
		urlEscapedShareUrl + '&title=' + urlEscapedShareTitle + '" \
		target="_blank" onclick="return userLinkShareLog( \'google\', \'' + escapedShareUrl + '\', \'' + 
		escapedShareTitle + '\', \'' + escapedHotelId + '\' );">' + 
		'<img src="' + linkShareStuffHost + 'images/user_link_share/goog.png" ' + 
		' width="14" height="14"> <span>Google</span></a><br>';
	html += '</td>';
	html += '<td>';
	html += '<a style="color:'+linkSharerColor+'" href="http://favorites.live.com/quickAdd.aspx?url=' + 
		urlEscapedShareUrl + '&title=' + urlEscapedShareTitle + '&text=&" \
		target="_blank" onclick="return userLinkShareLog( \'live\', \'' + escapedShareUrl + '\', \'' + 
		escapedShareTitle + '\', \'' + escapedHotelId + '\' );">' + 
		'<img src="' + linkShareStuffHost + 'images/user_link_share/live.png" ' + 
		' width="14" height="14"> <span>Live</span></a><br>';
	html += '</td>';
	html += '</tr>';
	html += '<tr>';
	html += '<td>';
	html += '<a style="color:'+linkSharerColor+'" href="http://www.myspace.com/index.cfm?fuseaction=postto&t=' + 
		urlEscapedShareTitle + '&c=&u=' + urlEscapedShareUrl + '&l=" \
		target="_blank" onclick="return userLinkShareLog( \'myspace\', \'' + escapedShareUrl + '\', \'' + 
		escapedShareTitle + '\', \'' + escapedHotelId + '\' );">' + 
		'<img src="' + linkShareStuffHost + 'images/user_link_share/mysp.png" ' + 
		' width="14" height="14"> <span>MySpace</span></a><br>';
	html += '</td>';
	html += '<td>';
	html += '<a style="color:'+linkSharerColor+'" href="http://www.stumbleupon.com/submit?url=' + urlEscapedShareUrl + '" \
		target="_blank" onclick="return userLinkShareLog( \'stumbleupon\', \'' + escapedShareUrl + '\', \'' + 
		escapedShareTitle + '\', \'' + escapedHotelId + '\' );">' + 
		'<img src="' + linkShareStuffHost + 'images/user_link_share/stup.png" ' + 
		' width="14" height="14"> <span>StumbleUpon</span></a><br>';
	html += '</td>';
	html += '</tr>';
	html += '<tr>';
	html += '<td>';
	html += '<a style="color:'+linkSharerColor+'" href="http://twitter.com/timeline/home?status=' + urlEscapedShareUrl + '" \
		target="_blank" onclick="return userLinkShareLog( \'twitter\', \'' + escapedShareUrl + '\', \'' + 
		escapedShareTitle + '\', \'' + escapedHotelId + '\' );">' + 
		'<img src="' + linkShareStuffHost + 'images/user_link_share/twit.png" ' + 
		' width="14" height="14"> <span>Twitter</span></a><br>';
	html += '</td>';
	html += '<td>';
	html += '<a style="color:'+linkSharerColor+'" href="http://bookmarks.yahoo.com/toolbar/savebm?t=' + 
		urlEscapedShareTitle + '&u=' + urlEscapedShareUrl + '" \
		target="_blank" onclick="return userLinkShareLog( \'yahoo\', \'' + escapedShareUrl + '\', \'' + 
		escapedShareTitle + '\', \'' + escapedHotelId + '\' );">' + 
		'<img src="' + linkShareStuffHost + 'images/user_link_share/yaho.png" ' + 
		' width="14" height="14"> <span>Yahoo</span></a><br>';
	html += '</td>';
	html += '</tr>';
	html += '</table>';
	html += '</div>';
	html += '</div>';

	return html;
}



// closes the link sharer after a small period of time
// unless immediate is true or the linksharer isnt visible in which case it clsoes immediatly
function closeLinkSharer( immediate )
{
	if ( linkSharerContainer )
	{
		cancelTimedCloseLinkSharer();
		if ( immediate || !linkSharerIsVisible() )
		{
			if ( linkSharerOpenTimerId )
			{
				weeid = clearTimeout( linkSharerOpenTimerId );
				linkSharerOpenTimerId = false;
			}
			document.body.removeChild( linkSharerContainer );
			linkSharerContainer = null;
		}
		else
		{
			linkSharerCloseTimerId = setTimeout( 'closeLinkSharer(true)', 500 );
		}
	}
	return true;
}



// cancels a timed close of the link sharer
function cancelTimedCloseLinkSharer()
{
	if ( linkSharerCloseTimerId )
	{
		clearTimeout( linkSharerCloseTimerId );
		linkSharerCloseTimerId = false;
	}
}




function applyLinkSharerPosition( targetElement )
{
	// reset the position first
	linkSharerContainer.style.top = '0px';
	linkSharerContainer.style.left = '0px';
	
	// we get the top and left edge co-ordindates
	var top = targetElement.offsetTop;
	var left = targetElement.offsetLeft;
	var currentElement = targetElement;
	while ( currentElement = currentElement.offsetParent )
	{
		top += currentElement.offsetTop;
		left += currentElement.offsetLeft;
	}
	
	// now get the width and height of the target element
	var width = targetElement.offsetWidth;
	var height = targetElement.offsetHeight;

	// using these to work out the classname
	var linkSharerClassVertical = 'Top';
	var linkSharerClassHorizontal = 'Left';
	
	// now we need to work out how big the linkSharerDiv is going to be
	var linkSharerWidth = linkSharerContainer.offsetWidth;
	var linkSharerHeight = linkSharerContainer.offsetHeight;
	
	// by default, the pop tip will go under the target element in the middle
    var linkSharerLeft = left + ( ( width - linkSharerWidth ) / 2 ); // link sharer in middle of targetElement
    //var linkSharerLeft = left; // link sharer to left of targetElement
	var linkSharerTop = top + height + 2;

	// we need to know the size of the windae
	if ( typeof( window.innerWidth ) == 'number' )
	{
		windowWidth = window.innerWidth;
		windowHeight = window.innerHeight;
	}
	else if ( document.documentElement 
		&& ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
	{
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	}
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
	{
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
	
	// we also need ot know how much we've scrolled down
	// default it to 0
	var yScroll = 0;
	if( typeof( window.pageYOffset ) == 'number' )
	{
		yScroll = window.pageYOffset;
	}
	else if( document.body && document.body.scrollTop )
	{
		yScroll = document.body.scrollTop;
	}
	else if( document.documentElement && document.documentElement.scrollTop )
	{
		yScroll = document.documentElement.scrollTop;
	}
	
	
	// let's add a little safety margin on to the width to account for scrollbars and shit,
	// and also increase the allowed height to account fo scrolling
	windowWidth -= 20;
	windowHeight -= 20;
	windowHeight += yScroll;
	
	// the linkSharer will be below the target element with the same 'left' value
	// but perhaps this will make it overlap the bottom or right of the screen :(
	// in these cases, we must adjust
	if ( linkSharerLeft + linkSharerWidth > windowWidth )
	{
		linkSharerLeft -= linkSharerWidth;
	}
	
	if ( linkSharerTop + linkSharerHeight > windowHeight )
	{
		linkSharerTop -= ( linkSharerHeight + height + 5 );
	}

	// dont let it go above or to the left of the screen
	linkSharerLeft = Math.max( linkSharerLeft, 0 );
	linkSharerTop = Math.max( linkSharerTop, 0 );

	linkSharerContainer.style.top = linkSharerTop + 'px';
	linkSharerContainer.style.left = linkSharerLeft + 'px';
}

function userLinkShareLog( serviceCode, shareUrl, title, hotelId )
{	
	// now send the ajax
	var url = '/user_link_share.php';
	var method = 'POST';
	var contentType = 'application/x-www-form-urlencoded';

	// these variables are url encoded and then escaped for echoing to javascript
	var urlEscapedShareUrl = linkShareAddSlashes( encodeURIComponent( shareUrl ) );
	var urlEscapedShareTitle = linkShareAddSlashes( encodeURIComponent( title ) );
	var urlEscapedHotelId = '';
	if ( hotelId )
	{
		urlEscapedHotelId = linkShareAddSlashes( encodeURIComponent( hotelId ) );
	}
	var qString = 'url=' + urlEscapedShareUrl + '&service_code=' + serviceCode + '&title=' + urlEscapedShareTitle;
	if ( hotelId )
	{
		qString += '&hotel_id=' + urlEscapedHotelId;
	}

	// create request object
	var req = false;
	if (window.XMLHttpRequest)
	{
		 // Mozilla, Safari,...
		req = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{ 
		// IE
		try
		{
			req = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				req = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				// ALWAYS return true
				// we dont want to not send the customer to the link
				return true;
			}
		}
	}
	
	// send! send! send!
	req.open( method, url, true );
	req.setRequestHeader( 'Content-Type', contentType );
	req.send( qString );
	
	return true;
}

function linkShareBookmarkAndLog( shareUrl, title, hotelId )
{
	userLinkShareLog( 'favorites', shareUrl, title, hotelId );
	linkShareBookmark( title, shareUrl );
}

function linkShareBookmark( title, url )
{	
	/***********************************************
	* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
	* This notice MUST stay intact for legal use
	* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
	***********************************************/
	if ( window.sidebar )
	{
		// firefox
		window.sidebar.addPanel(title, url, "");
	}
	else if( window.opera && window.print )
	{ 
		// opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if( document.all )
	{
		// ie
		window.external.AddFavorite( url, title );
	}
	else
	{
		alert('Your browser does not support this action - please bookmark this page manually.'); 
	}
}
