if( typeof(Shadowbox) != "undefined" )
{
	Shadowbox.loadSkin('classic', '/scripts/shadowbox-2.0/src/skin'); // use the "classic" skin
	Shadowbox.loadLanguage('en', '/scripts/shadowbox-2.0/src/lang'); // use the English language
	Shadowbox.loadPlayer(['flv', 'img'], '/scripts/shadowbox-2.0/src/player'); // Loads players
}

window.addEvent('domready', function() {
	/* Prettify any dates on the page (For shoptotv really) */

	$$("span.nicetimestamp").each( function(item) {
		item.set( "text", prettyDate(item.get("text")) );
	});

	/* initialise mouseovers ... */

	// For pre-fetching images ...
	var imgTemp = new Array();

	// This should work but doesn't ...
	// $$('img[shopto\:hsrc]').each( function(img) {

	$$('img').each( function(img) {
		var hsrc = img.get('shopto:hsrc');

		if( hsrc )
		{
			// Create an image to pre-fetch the needed graphic.
			imgTemp.push(new Element('img',{'src':hsrc}));

			// Store the real src.
			img.out_src = img.get('src');

			// Add events to swap them on over and out.
			img.addEvent('mouseover', function(ev){
				this.set('src', this.get('shopto:hsrc'));
			});

			img.addEvent('mouseout', function(ev){
				this.set('src', this.out_src);
			});
		}
	});

	// Setup the menu animations ...

	var menu = $('menu');

	menu.active_submenu = false;

	// Stop the click event from bubbling so that it stops
	// the irritating box that appears around them.
	menu.getElements('a').each(function(link) {
		link.addEvent("mousedown", function(ev) {
			new Event(ev).stop();
		});
	});

	menu.getElements('div.platforms a').each(function(link) {
		if( link.get('shopto:popup') )
		{
			var href = link.get('href');
			var parts = href.split('/');
			var domain = parts[0] + '//' + parts[2];
			var platform = parts[3];

			if( platform=='' )
			{
				platform='shoptotv';
			}

			// Create the drop down menu.

			link.submenu = $(link.get('shopto:popup')).clone()
				.grab(
					new Element('div',{'class': 'heading'}).adopt(
						new Element('a',{}).adopt(
							new Element('h2',{}).set('text',link.childNodes[0].get('alt') + ' Home')
						)
					),
					'top'
				)
				.set('class','submenu');
//				.set('class','submenu ' + platform.toLowerCase().replace('%20',''));

			$('submenus').adopt(link.submenu);

			link.submenu.getElements('div.heading a').each(function(sublink) {
				sublink.set('href', href);
			});

			switch( link.get('shopto:popup') )
			{
				case 'movies-submenu':
					href = href.replace('/MOVIES','');

					// NO BREAK

				case 'shoptotv-submenu':
				case 'wall-submenu':
					// The current href on each link needs to have the platform pre-pended.
					// So store the current href before we change it.

					link.submenu.getElements('div.content a').each(function(sublink) {
						sublink.set('href', href + sublink.get('href').replace('#',''));
					});
					break;

				default:
					// The current href on each link needs to have the platform pre-pended.
					// So store the current href before we change it.

					link.submenu.getElements('ul.category a').each(function(sublink) {
						var count = sublink.getParent().get('shopto:'+platform.replace('%20',''));

						if( count==null && !sublink.getParent().get('shopto:all') )
						{
							sublink.getParent().removeChild(sublink);
						} else {
							sublink.set('href', href + sublink.get('href').replace('#',''));

/*
							if( count!=null )
							{
								sublink.set('text',sublink.get('text') + ' (' + count + ')');
							}
*/
						}
					});

					// http://www.shopto.lan/page.php?page=search&amp;genre=STRATEGY

					link.submenu.getElements('ul.genre a').each(function(sublink) {
						var count = sublink.getParent().get('shopto:'+platform.replace('%20',''));

						if( count==null && !sublink.getParent().get('shopto:all') )
						{
							sublink.getParent().removeChild(sublink);
						} else {
							sublink.set('href', domain + '/page.php?page=search&platform=' + platform + '&genre=' + sublink.get('href').replace('#',''));

/*
							if( count!=null )
							{
								sublink.set('text',sublink.get('text') + ' (' + count + ')');
							}
*/
						}
					});
					break;
			}

			link.submenu.mouseover = false;
			link.submenu.expanded = false;
			link.submenu.parent_link = link;

			// The submenu animation function

			var linkpos = link.getPosition();

			link.submenu.sizer = new Fx.Morph(link.submenu, {
				transition: Fx.Transitions.Sine.easeIn,
				duration: 200
			}).set({
				'opacity':0
			});

			// Functions to make the submenu go in or out.

			link.submenu.expand = function() {
				search_text.blur();

				// Make sure it's on the screen

				var linkpos = link.getPosition();

				this.sizer.set({
					'left':  (linkpos.x+link.submenu.getSize().x>(window.getSize().x-25) ? linkpos.x + link.getSize().x - link.submenu.getSize().x : linkpos.x) + 'px'
//					'left':  (linkpos.x>650 ? linkpos.x + link.getSize().x - link.submenu.getSize().x : linkpos.x) + 'px'
				});

				// The submenu animation function

				this.sizer.cancel().start ({
					'opacity': [1]
				});

				this.parent_link.addClass("active");

				this.expanded = true;
			}

			link.submenu.contract = function() {
				if( menu.active_submenu==this )
				{
					menu.active_submenu = false;
				}

				this.expanded = false;

				this.sizer.cancel().start({
					'opacity': 0
				}).chain(function(){
					link.submenu.parent_link.removeClass("active");
				});
			}

			link.submenu.addEvent( "mouseover", function(ev) {
				new Event(ev).stop();

				this.mouseover = true;
			});

			link.submenu.addEvent( "mouseout", function(ev) {
				new Event(ev).stop();

				this.mouseover = false;

				// Clear any previous mouse out.
				$clear(this.delayed_hide);

				this.delayed_hide = function() {
					// If the menu was moused over during the delay this
					// flag will have been reset.
					if( link.submenu.mouseover==false && link.submenu.expanded )
					{
						link.submenu.contract();
					}
				}.delay(200);
			});

/*
			link.submenu.getElements('a').each(function(sublink) {
				sublink.set('href', link.get('href') + sublink.get('category'));

				var popup = link.get('shopto:popup');
				var platform = sublink.get('shopto:platform');

				if( platform )
				{
					sublink.setStyle('display',(popup==platform ? 'inline' : 'none'));
				} else {
					sublink.setStyle('display',(sublink.get('shopto:no-' + popup)=='true' ? 'none' : 'inline'));
				}
			});
*/

			// Attach the mouseover event.

			link.addEvent( "mouseover", function(ev) {
				new Event(ev).stop();

				if( menu.active_submenu!=false && menu.active_submenu!=link.submenu )
				{
					menu.active_submenu.contract();
				}

				menu.active_submenu = link.submenu;
/*
				if( menu.active_link!=false )
				{
					menu.active_link.removeClass("active");
				}
*/

//				menu.active_link = link;

				link.submenu.mouseover = true;
//				link.addClass("active");

/*
				link.submenu.getElements('a').each(function(sublink) {
					sublink.set('href', link.get('href') + sublink.get('category'));

					var popup = link.get('shopto:popup');
					var platform = sublink.get('shopto:platform');

					if( platform )
					{
						sublink.setStyle('display',(popup==platform ? 'inline' : 'none'));
					} else {
						sublink.setStyle('display',(sublink.get('shopto:no-' + popup)=='true' ? 'none' : 'inline'));
					}
				});
*/

				this.delayed_open = function() {
					// If the menu was moused over during the delay this
					// flag will have been reset.
					if( link.submenu.mouseover && !link.submenu.expanded && menu.active_submenu==link.submenu ) {
						link.submenu.expand();
					}
				}.delay(250);

/*
				if( !link.submenu.expanded ) {
					link.submenu.expand();
				}
*/
			});

			// Hide the submenu a short delay after a mouseout, assuming the mouse has
			// not gone back over and the menu has not already been hidden...

			link.addEvent( "mouseout", function(ev) {
				new Event(ev).stop();

				link.submenu.mouseover = false;

				// Clear any previous mouse out.
				$clear(link.submenu.delayed_hide);

				link.submenu.delayed_hide = function() {
					// If the menu was moused over during the delay this
					// flag will have been reset.
					if( link.submenu.mouseover==false && link.submenu.expanded )
					{
						link.submenu.contract();
					}
				}.delay(500);
			});
		}
	});

	/* REFORMAT THE SEARCH DROP-DOWN */

/*
	var real_combo = $('search-filter');
	var fake_value, fake_label;

	var fake_combo = new Element('div', {'class':'fake-combo'}).adopt (
		fake_value = new Element('input',{'type':'hidden','id':'search-filter','name':real_combo.get('name')}).set('value',real_combo.value),
		fake_label = new Element('div',{'class':'select'}).set('text',real_combo[real_combo.selectedIndex].get('text')),
		real_combo.clone()
	).inject(document.documentElement.getElement('body')); // .replaces(real_combo);

	fake_combo.getElements('option').each(function(item) {
		var li = new Element('li').adopt (
			new Element('a',{'href':item.value}).set('text',item.get('text')).addEvent('click', function(ev) {
				new Event(ev).stop();
				fake_value.value = this.get('href');
				fake_label.set('text',this.get('text'));
			})
		).replaces(item);

		item.getChildren().each(function (subitem) {
			subitem.inject(li);
		});
	});

	fake_combo.getElements('select, optgroup').each(function(item) {
		var ul = new Element('ul').replaces(item);

		switch( item.nodeName )
		{
			case 'OPTGROUP':
				if( item.get('label') )
				{
					new Element('li').set('text',item.get('label')).inject(ul,'before');
				}
				break;

			case 'SELECT':
				ul.setAttribute('class','drop-down');
				break;
		}

		item.getChildren().each(function (subitem) {
			subitem.inject(ul);
		});
	});
*/

	/* DO THE SEARCH BAR */

//	var search_div = $$("div#menu div.search")[0];

	var search_div = $('searchbar').getElement('div.search'); // $$("div#menu div.menus")[0];

	var search_filter = $('search-filter'); // $$("div#menu div.search form #search-filter")[0];
	var search_text = search_div.getElement('form input.text'); //  $$("div#menu div.search form input.text")[0];
	var search_submit = search_div.getElement('form a.submit'); //  $$("div#menu div.search form a.submit")[0];

	// Add a search results box to the bottom of the search form.
	var search_results = new Element("div",{id:"search-results"}).inject(search_div);

	// Functions to make the search results go in or out.

	search_results.fx = new Fx.Morph(search_results, {
		transition: Fx.Transitions.Expo.easeInOut,
		duration: 200
	}).set({
		'opacity': 0
	});

	search_results.expand = function() {
		if( !this.expanded && this.get('text')!='' ) {
			this.expanded = true;

			if( search_results.selected )
			{
				search_results.selected.firstChild.removeClass('hover');
				search_results.selected = null;
			}

			this.fx.cancel().start({
				'opacity': 1
			});
		}
	}

	search_results.contract = function() {
		if( this.expanded ) {
			this.expanded = false;

			if( search_results.selected )
			{
				search_results.selected.firstChild.removeClass('hover');
				search_results.selected = null;
			}

			this.fx.cancel().start({
				'opacity': 0
			});
		}
	}

	search_results.do_search = function() {
		var text = search_text.value;

		if( text.length>1 )	{
			var filter = search_filter.value.split(",");
			var url = "/SEARCH/JSON/" + filter[0] + "/" + filter[1] + "/" + text;
//			var url = "/SEARCH/JSON/SPECIAL/ALL-PRODUCTS/" + text;

			search_results.go = function() {
				new Request.JSON({
					method: 'get',
					url: url,
					urlEncoded: true,
/*
					onRequest: function() {
					},
*/
					onComplete: function(results) {
						var ul = new Element('ul');

						if( results!=null && results.length>0 ) {
							results.each(function(result){
								new Element('li').adopt(
									new Element('a',{'class':result.platform.replace(' ','').toLowerCase(),'href':result.url}).set('text',result.name)
								).inject(ul);
							});

							search_results.set('text','');
							ul.inject(search_results);

							search_results.expand();
						}
					},

					onFailure: function() {
						search_results.set('text','');
						search_results.expand();
					}
				}).send();

				search_results.go = null;
			}.delay(500);
		}
	}

	// Stop IE and Firefox suggesting entries for the search field.
	search_text.set('autocomplete','off');

	search_text.addEvent("blur", function(ev) {
		search_results.contract();
	});

	search_text.addEvent("focus", function(ev) {
		if( search_text.value!="" )
		{
			search_results.expand();
		}
	});

	search_text.addEvent("keydown", function(ev) {
		switch( ev.code )
		{
			case 38: // Arrow up.
				if( search_results.selected!=null )
				{
					if( search_results.selected.previousSibling!=null )
					{
						search_results.selected.firstChild.removeClass('hover');
						search_results.selected = search_results.selected.previousSibling;
					}
				} else {
					search_results.selected = search_results.getElements('li').pop(); //  $$('div#search-results li').pop();
				}

				if( search_results.selected!=null )
				{
					search_results.selected.firstChild.addClass('hover');

					// Return so a search doesn't run.
					return;
				}
				break;

			case 40: // Arrow down.
				if( search_results.selected!=null )
				{
					if( search_results.selected.nextSibling!=null )
					{
						search_results.selected.firstChild.removeClass('hover');
						search_results.selected = search_results.selected.nextSibling;
					}
				} else {
					search_results.selected = search_results.getElement('li'); // $$('div#search-results li')[0];
				}

				if( search_results.selected!=null )
				{
					search_results.selected.firstChild.addClass('hover');

					// Return so a search doesn't run.
					return;
				}
				break;

			case 13: // Enter
				// On enter navigate to the selected item.
				window.location = search_results.selected.firstChild.get('href');

				// And stop the event so the form doesn't also submit.
				new Event(ev).stop();

				// Return so a search doesn't run.
				return;
		}

		if( search_results.go ) {
			$clear(search_results.go);
		}
		search_results.contract();
	});

	search_text.addEvent("keyup", function(ev) {
		if( search_results.selected==null )
		{
			search_results.do_search();
		}
	});

/*
	search_filter.addEvent("change", function(ev) {
		if( search_results.go ) {
			$clear(search_results.go);
		}

		search_results.contract();

		search_results.do_search();
	});
*/

	/* Do shadowbox ... this is slow because it loads extra scripts */

	if( typeof(Shadowbox) != "undefined" )
	{
		Shadowbox.init();
	}

	/* Add popup help */

	// I'm only going to generate this when someone mouses over
	// the menu to keep things faster on pages when it's not needed.
	var popup_help = null;

	if( $('footerlinks') )
	{
		$('popup-help').addEvent('mouseover',function(ev) {
			if( popup_help==null )
			{
				// Duplicate the list items from the footer ...
				var ul = new Element('ul',{'id':'popup-help-list'});

				$('footerlinks').getElements('a').each(function(link) {
					new Element('li').adopt(
						link.clone()
					).inject(ul)
				});

				// Create a div and inject it into the html body.
				popup_help = new Element('div',{'id':'popup-help-links'}).adopt(ul).inject($$('html body')[0]);

				popup_help.fx = new Fx.Morph(popup_help, {
					transition: Fx.Transitions.Expo.easeInOut,
					duration: 200
				}).set({
					'opacity': 0
				});

				popup_help.expanded = false;

				popup_help.expand = function() {
					if( !this.expanded && this.get('text')!='' ) {
						this.expanded = true;

						this.fx.cancel().start({
							'opacity': 1
						});
					}
				}

				popup_help.contract = function() {
					if( this.expanded ) {
						this.expanded = false;

						this.fx.cancel().start({
							'opacity': 0
						});
					}
				}
			}

			popup_help.expand();

			$('popup-help').addEvent('mouseout',function(ev) {
				$clear(popup_help.timer);
				popup_help.timer = function(){
					popup_help.contract();
				}.delay(250);
			});

			$('popup-help-list').addEvent('mouseover',function(ev) {
				$clear(popup_help.timer);
			});

			$('popup-help-list').addEvent('mouseout',function(ev) {
				$clear(popup_help.timer);
				popup_help.timer = function(){
					popup_help.contract();
				}.delay(250);
			});
		});
	} else {
		// There are no footer links so hide the popup help (this is on the forum currently).
		$('popup-help').setStyle('display','none');
	}
});

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time)
{
	var now = new Date();
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," "));
	var diff = ((now.getTime() - date.getTime()) / 1000);

	if( !isNaN(diff) && diff<86400 )
	{
		return diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			true && Math.floor( diff / 3600 ) + " hours ago";
	}

	var day_diff = Math.floor(diff / 86400);

	if( !isNaN(day_diff) && day_diff>0 && day_diff<=31 )
	{
		return day_diff == 1 && "yesterday" ||
			day_diff < 7 && day_diff + " days ago" ||
			day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
	}

/*
	var month_diff = ((now.getMonth() - date.getMonth()) + 12) % 12;

	if( !isNaN(month_diff) && month_diff>0 && month_diff<=31 )
	{
		return month_diff == 1 && "Last month" ||
			month_diff + " months ago";
	}

	var year_diff = (now.getFullYear() - date.getFullYear());

	return year_diff == 1 && "last year" ||
		year_diff + " years ago";
*/

	var months = ['January','February','March','April','May','June',
		'July','August','September','October','November','December'];

	return( months[date.getMonth()] + " " + date.getFullYear() );
}

function RenderComment(comment)
{
	var div = new Element('div', {'class':'video-comment'}).adopt (
		new Element('div').adopt (
			new Element('small').set('text', prettyDate(comment.timestamp) + ' - ' ).adopt( new Element('a', { 'href':'/SHOPTOTV/HOME/'+comment.owner_id, 'text': comment.owner_name}) ),
			new Element('hr'),
			new Element('p').set('text', comment.text)
		)
	);

	if( comment.avatar )
	{
		new Element('img', {
			'class':'avatar',
			'src': comment.avatar,
			'alt':'avatar of ' + comment.owner_name,
			'events': {
				'load': function(){
					// When the image loads set the container to make sure it fits
					div.setStyle('min-height', this.getSize().y);
				}
			}
		}).inject(div, 'top');
	}

	return( div );
}

function useBorderRadius()
{
	if( typeof useBorderRadius.supported != "undefined" )
	{
		return( useBorderRadius.supported );
	}

	var prop = [
		'borderTopRightRadius',
		'webkitBorderTopRightRadius',
		'MozBorderTopRightRadius',
		'mozBorderTopRightRadius',
		'oBorderTopRightRadius',
		'msBorderTopRightRadius',
		'mozBorderRadiusTopright',
		'MozBorderRadiusTopright'
	];

	var m = new Element('css3test');
	m.style.cssText = "border-top-right-radius: 10px; "+
		"-webkit-border-top-right-radius: 10px; "+
		"-moz-border-top-right-radius: 10px; "+
		"-o-border-top-right-radius: 10px; "+
		"-ms-border-top-right-radius: 10px;"+
		"-moz-border-radius-topright: 10px";

	for (var i=0; i<prop.length ; ++i) {
		if ($defined(m.style[prop[i]])) {
			return( useBorderRadius.supported=true );
		}
	}

	return( useBorderRadius.supported=false );
}

function RenderCssWhiteBox(content,width,height)
{
	if( useBorderRadius() ){
		return new Element('div', {'class': 'white-box'}).adopt(content);
	} else {
		return new Element('table', {'class':'white-box','width':width,'cellpadding':'0','cellspacing':'0','border':'0'}).adopt (
			new Element('tr', {}).adopt (
				new Element('td', {'class':'tl'}),
				new Element('td', {'class':'tc'}),
				new Element('td', {'class':'tr'})
			),
			new Element('tr', {}).adopt (
				new Element('td', {'class':'cl'}),
					new Element('td', {'align':'center','valign':'middle','style':'background:white;position:relative;'}).adopt(content),
				new Element('td', {'class':'cr'})
			),
			new Element('tr', {}).adopt (
				new Element('td', {'class':'bl'}),
				new Element('td', {'class':'bc'}),
				new Element('td', {'class':'br'})
			)
		);
	}
}

function setTelCode(code)
{
	$('tel_code').value = code;
	$('cel_code').value = code;
}

function byeSanta()
{
	var today = new Date();
	var expire = new Date(today.getTime() + (3600000*24));
//	expire.setTime(today.getTime() + 3600000*24*1);
	document.cookie = "byeSanta=1; expires=" + expire.toGMTString();
}

function logVideoView(video_id)
{
	return new Request({
		method: 'get',
		url: '/SHOPTOTV/LOGVIEW/JSON/' + video_id,
		urlEncoded: true
	}).send();
}

function playVideo(container, url, image_url, original_width, original_height, full_width)
{
	/*
	 * When the player is ready it will trigger "playerReady"
	 */
	function maxSize()
	{
		var screen_width = parseInt($(container).setStyles({'width':'', 'height':''}).getStyle('width'));

		var width = screen_width;
		var height = parseInt((screen_width * original_height) / original_width);

		if( height > 400 )
		{
			// Cap the video size at 400px high.
			height = 400;

			if( full_width=="undefined" || full_width==false )
			{
				width = parseInt((height * original_width) / original_height)
			}
		}

		// Allow height for the controls.
		height += 22;

		return( [width, height] );
	}

	var size = maxSize();
	var cookie = Cookie.read('autostart');
	var video_name = url.split('/').pop();

	if( cookie==null )
	{
		cookie = '';
	}

	var autostart = (cookie.indexOf(video_name)==-1);

	$(container).set('text','').setStyles({'width':'', 'height':''}).adopt(
		new Swiff('/scripts/longtail/jwplayer-v5.swf', {
			id: 'player',
			width: size[0],
			height: size[1],
			params: {
				'allowfullscreen': 'true',
				'wMode': 'opaque',
				'quality': 'best'
				/* 'allowscriptaccess' : 'always' */
				/* 'allownetworking' : 'all'*/
			},
			vars: {
				'file': url,
				'image': image_url,
				'autostart': false,
				'smoothing': 'true',
				'resizing': 'true',
				/*'plugins' : 'viral-1'*/
				'skin': '/scripts/longtail/v5skin-five.swf'
/*
				'logo': 'http://images.shopto.lan/shopto/misc/santaoverlay6.png'
*/
			}
		})
	);

	Cookie.write('autostart', cookie + " " + video_name);

	if( autostart )
	{
		logVideoView(parseInt(video_name));
	}

	window.addEvent("resize", function(){
		size = maxSize();

		try{
			$('player').setStyles({
				'width': size[0],
				'height': size[1]
			});
		} catch(e) {
			// IE doesn't like resizing flash so simply
			// re-create the flash object on resize.
			// We need the delay because resize events fire fast
			// as the browser is resized.
			if( typeof playVideo.waiting!='undefined' )
			{
				$clear(playVideo.waiting);
			}  
	
			playVideo.waiting = playVideo.delay(1000, this, [container, url, image_url, original_width, original_height, full_width]);
		}
	});

/*
.setStyles({
		"display": "block",
		"margin": "auto",
		"width": width,
		"height": height,
		"border": "1px solid #B9BAC1"
	});
*/

/*
	$('player').setStyles({
		"display": "block",
		"margin": "auto"
	});
*/
};
