/**
* Assign the view handler
*/

viewHandler = Media;

/**
* Creates a new object with methods used by the Media page
*
* @author				Matt Gifford
* @copyright			2008 Timeshifting Interactive Limited
*/
function Media()
	{
	// Step 1. Define Properties
	var _instance = this;

	// listings entry and scrolling vars
	var _scrollbarGrabberSize = 0;
	var _scrollbarGrabberRange = 0;
	_grabberBeingDragged = false;		// global



	// Step 2. Define Public Methods

	/**
	* Sets up the initial page state and event handlers
	*/
	this.init = function()
		{
		// Call generic page init method
		this.base.init.call(this);

		this.initUserAgentBooleans();

		// Initialize listings scrolling
		this.initListingsScrolling();
		}


	/**
	* Sets up user agent booleans
	*/
	this.initUserAgentBooleans = function()
		{
		this.renderingEngine = '';
		var ua = navigator.userAgent.toLowerCase();
		var macintosh = (ua.indexOf("macintosh") != -1 || ua.indexOf("powerpc") != -1 || ua.indexOf("mac os x") != -1) ? 1 : 0;

		// Opera
		if (this.isPresto = !!window.opera)
			{
			this.renderingEngine = 'presto';
			}
		// Safari, Apple WebKit, Konqueror, etc
		if (this.isWebKit = (ua.indexOf('applewebkit') != -1))
			{
			this.renderingEngine = 'webkit';
			}
		// Netscape, Mozilla, Firefox, etc
		if (this.isGecko = (ua.indexOf('gecko') != -1 && ua.indexOf('khtml') == -1))
			{
			this.renderingEngine = 'gecko';
			}
		// Internet Explorer for Windows
		if (this.isTrident = !!(window.attachEvent && !window.opera))
			{
			this.renderingEngine = 'trident';
			}

		// Macintosh
		this.isMac = macintosh;
		// Internet Explorer 5 for Windows
		this.isTrident5 = (this.isTrident && ua.indexOf('msie 5') != -1) ? 1 : 0;
		// Internet Explorer 6 for Windows
		this.isTrident6 = (this.isTrident && ua.indexOf('msie 6') != -1) ? 1 : 0;
		// Internet Explorer 7 for Windows
		this.isTrident7 = (this.isTrident && ua.indexOf('msie 7') != -1) ? 1 : 0;
		// Safari
		this.isSafari = (this.isWebKit && (ua.indexOf('safari') != -1));
		// Safari 3
		this.isSafari3 = (this.isWebKit && (ua.indexOf('safari') != -1) && window.devicePixelRatio && (ua.indexOf('mobile') == -1));
		// Mobile Safari
		this.isMobileSafari = (this.isWebKit && (ua.indexOf('safari') != -1) && window.devicePixelRatio && (ua.indexOf('mobile') != -1));
		// Firefox
		this.isFirefox = (this.isGecko && (navigator.vendor == "Firefox" || ua.indexOf('firefox') != -1)) ? 1 : 0;
		// Firefox 1.x
		this.isFirefox1 = (this.isGecko && navigator.vendor == "Firefox") ? 1 : 0;
		}


	/**
	* Initializes the scrollbar for the video listings
	*/
	this.initListingsScrolling = function()
		{
		// Add global event handlers
		document.onmousemove = __eventHandlerScrollBarGrabberMove;
		document.onmouseup = __eventHandlerScrollBarGrabberUp;

		// Calculate content size and range
		_listingsContentHeight = parseInt(document.getElementById('listingsContainer').offsetHeight);
		_listingsContentRange = (_listingsContentHeight - 227) < 0 ? 0 : (_listingsContentHeight - 227);

		// Calculate the grabber size and range
		var pages = _listingsContentHeight / 227;
		pages = (pages < 1 ? 1 : pages);
		_scrollbarGrabberSize = parseInt(173 / pages);
		_scrollbarGrabberRange = 173 - _scrollbarGrabberSize;

		// Add event handler to grabber
		document.getElementById('listingsScrollbarGrabber').onmousedown = __eventHandlerScrollBarGrabberDown;

		// Set the grabber size and position
		document.getElementById('listingsScrollbarGrabber').style.top = '0px';
		document.getElementById('listingsScrollbarGrabber').style.height = _scrollbarGrabberSize + 'px';
		xhtml.grabberY = 0;
		xhtml.previousMouseY = 0;

		// Set the current location
		document.getElementById('listingsContainer').style.top = '0px';
		}


	/**
	* Scrolls the listings entry up
	*/
	this.listingsScrollUp = function()
		{
		xhtml.grabberY -= 10;
		this.listingsScrollMove();
		}


	/**
	* Scrolls the listings entry down
	*/
	this.listingsScrollDown = function()
		{
		xhtml.grabberY += 10;
		this.listingsScrollMove();
		}


	/**
	* Updates the location of the scrollbar grabber and listings content
	*/
	this.listingsScrollMove = function()
		{
		if (_scrollbarGrabberRange == 0)
			{
			return;
			}

		// Range check grabber
		if (xhtml.grabberY < 0)
			{
			xhtml.grabberY = 0;
			}
		if (_scrollbarGrabberRange < xhtml.grabberY)
			{
			xhtml.grabberY = _scrollbarGrabberRange;
			}

		// Move the grabber
		document.getElementById('listingsScrollbarGrabber').style.top = xhtml.grabberY + 'px';

		// Move the content
		document.getElementById('listingsContainer').style.top = (parseInt((xhtml.grabberY / _scrollbarGrabberRange) * _listingsContentRange) * -1) + 'px';
		}



	// Step 3. Define Private Methods

	/**
	* Starts the drag of the grabber
	*
	* @param		event		The browser event object
	*/
	function __eventHandlerScrollBarGrabberDown(event)
		{
		if (_grabberBeingDragged == true)
			{
			return;
			}
		else
			{
			_grabberBeingDragged = true;
			}

		// Get the event object if necessary
		event = !!event ? event : window.event;

		// Get the mouse location
		if(xhtml.isTrident == true)
			{
			xhtml.previousMouseY = window.event.clientY;
			}
		else
			{
			xhtml.previousMouseY = event.pageY;
			}

		// update the div position
		document.getElementById('listingsScrollbarGrabber').style.top = parseInt(xhtml.grabberY) + 'px';
		}



	/**
	* Starts the drag of the grabber
	*
	* @param		event		The browser event object
	*/
	function __eventHandlerScrollBarGrabberMove(event)
		{
		if (_grabberBeingDragged == false)
			{
			return;
			}

		// Get the event object if necessary
		event = !!event ? event : window.event;

		// Get the mouse location
		if(xhtml.isTrident == true)
			{
			var mouseY = window.event.clientY;
			}
		else
			{
			var mouseY = event.pageY;
			}

		// calculate offset and update div location vars
		xhtml.grabberY = (((mouseY * 1) - (xhtml.previousMouseY * 1)) * 1) + (xhtml.grabberY * 1);

		// update the stored mouse location
		xhtml.previousMouseY = mouseY;

		// move the grabber and the container
		xhtml.listingsScrollMove();
		}


	/**
	* End the drag of the grabber
	*/
	function __eventHandlerScrollBarGrabberUp()
		{
		_grabberBeingDragged = false;
		}
	}



WebPage.prototype.share = {

	// The current url and title
	currentTitle: ((document.getElementsByTagName('title')[0] && document.getElementsByTagName('title')[0].firstChild) ? encodeURIComponent(document.getElementsByTagName('title')[0].firstChild.nodeValue) : ''),
	currentUrl: encodeURIComponent(window.location.toString()),
	currentDesc: '',
	isTrident6: (!!(window.attachEvent && !window.opera) && (navigator.userAgent.toLowerCase()).indexOf('msie 6') != -1) ? true : false,


	/**
	* Returns a function that calls the method in the context of the object specified
	*
	* @param		obj				The object that the method belongs to
	* @param		method			The method to call
	* @return		function		The bound function
	*/
	bind: function(obj, method)
		{
		return function()
			{
			return method.apply(obj, arguments);
			}
		},


	/**
	* Opens the share box
	*
	* @param		obj		The share link clicked on
	*/
	open: function(obj)
		{
		// Close any other share boxes
		this.close();

		// Save the share url and title
		try { var defaultTitle = encodeURIComponent(document.getElementsByTagName('title')[0].firstChild.nodeValue); } catch (e) { var defaultTitle = ''; }
		this.currentTitle = (!!obj.getAttribute('title') ? encodeURIComponent(obj.getAttribute('title')) : defaultTitle);
		this.currentUrl = (!!obj.getAttribute('rel') ? encodeURIComponent(obj.getAttribute('rel')) : encodeURIComponent(window.location.toString()));
		this.currentDesc = (!!obj.getAttribute('desc') ? encodeURIComponent(obj.getAttribute('desc')) : this.currentTitle);

		// If IE6 hide any selects
		if (this.isTrident6 == true)
			{
			var selects = document.getElementsByTagName('select');
			for (var x = selects.length-1; 0 <= x; x--)
				{
				selects[x].className += ' hidden';
				}
			}

		// Add/update the overlay
		this._updateOverlay();

		// Add the share box
		this._buildNode(obj);
		},


	/**
	* Closes the share box
	*/
	close: function()
		{
		// Remove the share container
		if (document.getElementById('sharePageContainer'))
			{
			document.body.removeChild( document.getElementById('sharePageContainer') );
			}

		// Hide the overlay
		if (document.getElementById('sharePageOverlay'))
			{
			document.getElementById('sharePageOverlay').className = 'hidden';
			}

		// If IE6 reshow any selects
		if (this.isTrident6 == true)
			{
			var selects = document.getElementsByTagName('select');
			for (var x = selects.length-1; 0 <= x; x--)
				{
				selects[x].className = selects[x].className.replace(/\s?hidden/g, '');
				}
			}
		},


	/**
	* Launches social web link for the current page
	*
	* @param		network		The social media network
	*/
	social: function(network)
		{
		// Select the correct url to throw
		switch (network)
			{
			case 'blinklist':
				var url = 'http://blinklist.com/index.php?Action=Blink/addblink.php&Url=%url%&Title=%title%';
				break;

			case 'delicious':
				var url = 'http://del.icio.us/post?url=%url%&title=%title%';
				break;

			case 'digg':
				var url = 'http://digg.com/submit?phase=2&url=%url%&title=%title%&bodytext=%desc%';
				break;

			case 'facebook':
				var url = 'http://www.facebook.com/sharer.php?u=%url%&t=%title%';
				break;

			case 'furl':
				var url = 'http://furl.net/storeIt.jsp?u=%url%&t=%title%';
				break;

			case 'google':
				var url = 'http://www.google.com/bookmarks/mark?op=edit&bkmk=%url%&title=%title%';
				break;

			case 'magnolia':
				var url = 'http://ma.gnolia.com/bookmarklet/add?url=%url%&title=%title%';
				break;

			case 'netscape':
				var url = 'http://www.netscape.com/submit/?U=%url%&T=%title%';
				break;

			case 'newsvine':
				var url = 'http://www.newsvine.com/_wine/save?u=%url%&h=%title%';
				break;

			case 'reddit':
				var url = 'http://reddit.com/submit?url=%url%&title=%title%';
				break;

			case 'stumbleupon':
				var url = 'http://www.stumbleupon.com/submit?url=%url%&title=%title%';
				break;

			case 'tailrank':
				var url = 'http://tailrank.com/share/?link_href=%url%&title=%title%';
				break;

			case 'technorati':
				var url = 'http://www.technorati.com/faves?add=%url%';
				break;

			case 'windowslive':
				var url = 'https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url=%url%&title=%title%&top=1';
				break;

			case 'yahoomyweb':
				var url = 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u=%url%&t=%title%';
				break;

			default:
				return;
			}

		// Configure the url
		url = url.replace('%url%', this.currentUrl);
		url = url.replace('%title%', this.currentTitle);
		url = url.replace('%desc%', this.currentDesc);

		// Throw the url
		window.open(url, '_blank');

		// Close the share box
		this.close();
		},


	/**
	* Emails a link to the current page
	*/
	email: function()
		{
		// Check for blank input
		var obj = document.getElementById('sharePageContainer');
		var inputs = obj.getElementsByTagName('input');
		for (var x = 0; x < 3; x++)
			{
			if (inputs[x].value == '')
				{
				obj.getElementsByTagName('label')[0].className = 'missing';
				return;
				}
			}

		// Check for valid email addresses
		var regex = /^[a-z0-9_+-.]+@[a-z0-9_-]*\.?[a-z0-9_-]*\.?[a-z0-9_-]*\.[a-z]+$/i;
		if (regex.test(inputs[0].value) == false || regex.test(inputs[2].value) == false)
			{
			obj.getElementsByTagName('label')[0].className = 'missing';
			return;
			}

		// Send the request
		var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
		request.open("POST", "/sharepage.ajax.php", true);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		request.send( this._buildFormParams() );

		// Update the share box
		obj.getElementsByTagName('label')[0].className = 'hidden';
		obj.getElementsByTagName('label')[1].className = 'sending';
		obj.getElementsByTagName('fieldset')[0].className = 'hidden';

		// Close the share box
		setTimeout("xhtml.share.close();", 750);
		},


	/**
	* Builds the share dialog and returns the completed node
	*
	* @param		obj		The object to align to
	*/
	_buildNode: function(obj)
		{
		var containerTemplate = [];
		containerTemplate.push("<div class=\"social\">");
		containerTemplate.push("<h3>Social Web</h3>");
		containerTemplate.push("<ul class=\"list1\">");
		containerTemplate.push("<li><a class=\"blinklist\" href=\"javascript:;\" onclick=\"xhtml.share.social('blinklist');\">BlinkList</a></li>");
		containerTemplate.push("<li><a class=\"delicious\" href=\"javascript:;\" onclick=\"xhtml.share.social('delicious');\">del.icio.us</a></li>");
		containerTemplate.push("<li><a class=\"digg\" href=\"javascript:;\" onclick=\"xhtml.share.social('digg');\">Digg</a></li>");
		containerTemplate.push("<li><a class=\"facebook\" href=\"javascript:;\" onclick=\"xhtml.share.social('facebook');\">Facebook</a></li>");
		containerTemplate.push("<li><a class=\"furl\" href=\"javascript:;\" onclick=\"xhtml.share.social('furl');\">Furl</a></li>");
		containerTemplate.push("<li><a class=\"google\" href=\"javascript:;\" onclick=\"xhtml.share.social('google');\">Google Bookmarks</a></li>");
		containerTemplate.push("<li><a class=\"magnolia\" href=\"javascript:;\" onclick=\"xhtml.share.social('magnolia');\">ma.gnolia</a></li>");
		containerTemplate.push("<li><a class=\"netscape\" href=\"javascript:;\" onclick=\"xhtml.share.social('netscape');\">Netscape</a></li>");
		containerTemplate.push("</ul>");
		containerTemplate.push("<ul class=\"list2\">");
		containerTemplate.push("<li><a class=\"newsvine\" href=\"javascript:;\" onclick=\"xhtml.share.social('newsvine');\">Newsvine</a></li>");
		containerTemplate.push("<li><a class=\"reddit\" href=\"javascript:;\" onclick=\"xhtml.share.social('reddit');\">reddit</a></li>");
		containerTemplate.push("<li><a class=\"stumbleupon\" href=\"javascript:;\" onclick=\"xhtml.share.social('stumbleupon');\">StumbleUpon</a></li>");
		containerTemplate.push("<li><a class=\"tailrank\" href=\"javascript:;\" onclick=\"xhtml.share.social('tailrank');\">Tailrank</a></li>");
		containerTemplate.push("<li><a class=\"technorati\" href=\"javascript:;\" onclick=\"xhtml.share.social('technorati');\">Technorati</a></li>");
		containerTemplate.push("<li><a class=\"windowslive\" href=\"javascript:;\" onclick=\"xhtml.share.social('windowslive');\">Windows Live</a></li>");
		containerTemplate.push("<li><a class=\"yahoomyweb\" href=\"javascript:;\" onclick=\"xhtml.share.social('yahoomyweb');\">Yahoo! My Web</a></li>");
		containerTemplate.push("</ul>");
		containerTemplate.push("</div>");
		containerTemplate.push("<a class=\"close\" href=\"javascript:;\" onclick=\"xhtml.share.close();\">close</a>");

		// Build the container
		var node = document.createElement('div');
		node.id = 'sharePageContainer';
		node.innerHTML = containerTemplate.join("\n");

		// Add the classes
		var classes = ['blinklist', 'delicious', 'digg', 'facebook', 'furl', 'google', 'magnolia', 'netscape', 'newsvine', 'reddit', 'stumbleupon', 'tailrank', 'technorati', 'windowslive', 'yahoomyweb'];


		// Position the container
		var position = this._positionContainer(obj);
		node.style.left = position.left + 'px';
		node.style.top = position.top + 'px';

		// Add the container to the document
		document.body.appendChild( node );
		},


	/**
	* Finds the absolute position of an object on the page
	*
	* @param		obj				The object to find the position of
	*
	* @return		Object with 'x' and 'y' proprieties for the object's location absolute on the page
	*/
	_getObjectPosition: function(obj)
		{
		var x = 0;
		var y = 0;

		do
			{
			if (obj.offsetLeft)
				{
				x += obj.offsetLeft;
				}
			if (obj.offsetTop)
				{
				y += obj.offsetTop;
				}
			}
		while ( obj = obj.offsetParent );

		// Return an object
		return {x : (x * 1), y : (y * 1)}
		},


	/**
	* Calculates the position of the share container
	*
	* @param		obj		The node to align to
	* @return		The new position
	*/
	_positionContainer: function(obj)
		{
		var position = this._getObjectPosition(obj);
		var left = (position.x - 250);
		var top = (position.y - 125);

		// Bound top left
		if (left < 40)
			{
			left = 40;
			}
		if (top < 40)
			{
			top = 40;
			}

		// Bound bottom right
		if ( (document.body.offsetWidth - 540) < left)
			{
			left = (document.body.offsetWidth - 540);
			}
		if ( (document.body.offsetHeight - 300) < top)
			{
			top = (document.body.offsetHeight - 300);
			}

		// Return the position
		return {left : left, top : top}
		},



	/**
	* Updates the position and sizing of the overlay (and creates it if it doesn't exist)
	*/
	_updateOverlay: function()
		{
		// Add the overlay if it doesn't already exist
		if (!document.getElementById('sharePageOverlay'))
			{
			var overlay = document.createElement('div');
			overlay.id = 'sharePageOverlay';
			overlay.style.position = 'absolute';
			overlay.style.left = '0px';
			overlay.style.top = '0px';
			overlay.style.background = '#000';
			overlay.style.zIndex = 500;
			overlay.style.opacity = 0.6;
			overlay.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=60)';
			document.body.appendChild( overlay );
			}

		// Resize the overlay
		var overlay = document.getElementById('sharePageOverlay');
		overlay.className = 'hidden';
		overlay.style.width = document.body.offsetWidth + 'px';
		overlay.style.height = (document.documentElement.clientHeight < document.body.offsetWidth ? document.body.offsetWidth : document.documentElement.clientHeight) + 'px';
		overlay.className = '';
		},


	/**
	* Builds the params for the ajax email request
	*/
	_buildFormParams: function()
		{
		var params = [];

		// Add the share information
		params.push( 'url=' + this.currentUrl );
		params.push( 'title=' + this.currentTitle );

		// Add the user information
		var inputs = document.getElementById('sharePageContainer').getElementsByTagName('input');
		for (var x = 0; x < 3; x++)
			{
			params.push( encodeURIComponent(inputs[x].name) + '=' + encodeURIComponent(inputs[x].value) );
			}

		// Return the built params
		return params.join('&');
		}
	}
