// Find the URL from the currently loading script block so that we can force
// loads from the same url! (This works because the scripts are loaded as
// they are found in the HTML source so the current script is always the
// last on the page!)

var myScript, myScriptURL;
var myLanguage = 'en_GB';

try {
	// (getElements doesn't return a true Array so I'm casting to use pop!)
	myScript = Array.prototype.slice.call(document.getElementsByTagName('script')).pop();
	myScriptURL = myScript.src.replace(/(\/\/[^\/]+)\/.*$/,'$1');
} catch(ev) {
	myScript = '';
	myScriptURL = '';
}

if( typeof(Shadowbox) != "undefined" )
{
	Shadowbox.loadSkin('classic', myScriptURL + '/scripts/shadowbox-2.0/src/skin'); // use the "classic" skin
	Shadowbox.loadLanguage('en', myScriptURL + '/scripts/shadowbox-2.0/src/lang'); // use the English language
	Shadowbox.loadPlayer(['flv', 'img', 'html', 'swf', 'iframe'], myScriptURL + '/scripts/shadowbox-2.0/src/player'); // Loads players
    // For Shadowbox 3 testing. Previous lines do not seem work with version 3.
//    Shadowbox.init({
//        language:   "en",
//        players:    ["flv", "html", "iframe", "img", "swf"]
//    });
}

function minibasket_animate(result)
{	
	header = $('mini_basket').get('site:basket-title');

	var new_mini_basket = new Element('div',{'class':'side-panel-box'}).adopt(
		new Element('h4').set('text',header),
		new Element('div',{'class':'body'}).set('html',result.minibasket)
	);

	var container = $('mini_basket').getParent().getParent();

	if(container.get('tag') == 'tr')
	{
		container = container.getParent().getParent();
	}

	var myEffects = new Fx.Morph(container, {
		duration: 500,
		transition: Fx.Transitions.Sine.easeOut
	}).set({
		'overflow':'hidden'
	});

	myEffects.start({
		'height': 1
	}).chain(function(){

		new_mini_basket.setStyle('visibility','hidden').inject($("left"));

		var height = new_mini_basket.getSize().y;

		var myEffects = new Fx.Morph(new_mini_basket, {
			duration: 500,
			transition: Fx.Transitions.Sine.easeOut
		}).set({
			'height':'0px',
			'overflow':'hidden'
		});

		new_mini_basket.replaces(container);

		myEffects.set({
			'visibility':'visible'
		}).start({
			'height': height
		});

		$('mini_basket').getElements('a.delete_button').each(function(button){
			button.addEvent('click', minibasket_delete);
		});
	});

	for( var i in result.order_details )
	{
		if($(i)!=null)
		{
			$(i).set('html',result.order_details[i]);
		}
	}

	return;
}

function minibasket_delete(ev)
{
	new Event(ev).stop();

	new Request.JSON({
		method: 'post',
		url: '/feeds/basket.php',
		urlEncoded: true,
		data:
		{
			'action':'delete',
			'quantity':'1',
			'codart': ev.target.getAttribute('site:codart'),
			'location': 'mini_basket'
		},

		onComplete: function(result) {
			if( result.basket_data != false && result.basket_data.count != undefined )
			{
				displayMiniBasketTopBarIcon(result.basket_data.count, result.basket_data.total, result.basket_data.currency, 'basket');
			}
			
			//minibasket_animate(result);
		}
/*
		onFailure: function() {
			alert('Sorry but the service is temporary unavailable...');
		}
*/
	}).send();
};

function minibasket_add(ev)
{
	new Event(ev).stop();
//console.log(ev);
	new Request.JSON({
		method: 'post',
		url: '/feeds/basket.php',
		urlEncoded: true,
		data:
		{
			'action':'add',
			'quantity':'1',
			'codart':ev.target.getProperty('codart'),
			'location':ev.target.getProperty('location')
		},
		onComplete: function(result){
			if (result == 'undefined' || result['result'] == false)
			{
				ev.target.notice.showNotice(result['msg'], 'error');
			} else {
				
				if( result.basket_data != false && result.basket_data.count != undefined )
				{
					displayMiniBasketTopBarIcon(result.basket_data.count, result.basket_data.total, result.basket_data.currency);
					getMiniBasketTopBar();
					
					(function() {
						if( $('mini-basket-table') != undefined )
						{
							$('mini-basket-table').set('tween', {duration: 'long'}).tween('opacity',1,0);
						}
					}).delay(3000);
					
					if( $('mini-basket-table') != undefined )
					{
						$('mini-basket-table').destroy();
					}
				}
				
				//minibasket_animate(result['result']);
				ev.target.notice.showNotice(result['msg'], 'ok');
			}
		}
	}).send();
}

function removeFromMiniBasket(codart)
{
	new Request.JSON({
		method: 'post',
		url: '/feeds/basket.php',
		urlEncoded: true,
		data:
		{
			'action':'delete',
			'quantity':'1',
			'codart': codart
		},
		onComplete: function(){
			
			getMiniBasketTopBar();
		}
	}).send();
}

function displayMiniBasketTopBarIcon(basket_items_count, basket_value, basket_currency, location)
{	
	if( basket_currency == 'EUR' )
	{
		basket_currency = '&euro;';
	
	} else {
		
		basket_currency = '&pound;';
	}
	
	if( $('mini-basket-table') != undefined )
	{
		$('mini-basket-table').empty();
	}
	
	if( $('mini-basket-totals') )
	{
		$('mini-basket-totals').destroy();
	}
	
	
	if( basket_items_count > 0 )
	{
		basket = 'full';
		
	} else {
		
		basket = 'empty';
	}
	
	if( location == 'basket' )
	{
		basket_holder = 'mini-basket-wrapper-no-click';
	
	} else {
		
		basket_holder = 'mini-basket-wrapper';
		
		$('mini-basket-wrapper').addClass('rotate-right');
		
		(function () {
			$('mini-basket-wrapper').removeClass('rotate-right');
		}).delay(75)
	}
	
	if( $(basket_holder) != undefined )
	{
		img_path = String.from($('mini-basket-trolley').get('src'));
		
		if( img_path.contains(String.from(basket)) == false )
		{
			if( basket == 'full' )
			{
				img_path = img_path.replace('empty', 'full');
				
			} else {
				
				img_path = img_path.replace('full', 'empty');
			}
		}

		$('mini-basket-trolley').set('src', String.from(img_path));
	}
	
	if( basket=='empty' )
	{
		basket_msg = '&nbsp;&nbsp;';
	
	} else {
	
		//basket_msg = basket_currency + basket_value.toFixed(2) + '&nbsp;&nbsp;' + basket_items_count;
		basket_msg = basket_items_count + '&nbsp;&nbsp;&nbsp;' + basket_currency + basket_value.toFixed(2);
	}
	
	var insert_msg = new Element('span', {'id':'mini-basket-totals'}).set('html', basket_msg);	
	insert_msg.inject($(basket_holder), 'top');

	return;
}


function getMiniBasketTopBar()
{
	if( $$('.mini-basket-table') != undefined )
	{
		$$('.mini-basket-table').each(function(el) {
			el.destroy();
		});
	}
	
	new Request.JSON({
		method: 'post',
		url: '/feeds/basket.php',
		urlEncoded: true,
		data:
		{
			'action':'show'
		},
		onComplete: function(result)
		{
			if( result.status == 'OK' )
			{
				//console.log(result);
				displayMiniBasketTopBarIcon(result.count, result.total, result.currency);
				
				if( $('mini-basket-wrapper') != undefined )
				{
					wrapper = new Element('div', {'class':'mini-basket-table', 'id':'mini-basket-table'}).addEvent('mouseleave', function(ev) {
						this.destroy();
					});

					if( result.currency == 'EUR' )
					{
						currency = '&euro';
				
					} else {
					
						currency = '&pound';
					}
					
					if( result.count > 0 )
					{
						/*build the header*/
						/*
						wrapper.adopt(
							new Element('div',{'class':'mini-basket-item'}).adopt(
								new Element('span', {'class':'mini-basket-gamename'}).set('styles', {'font-weight':'bold','font-size':'15px'}).set('text', 'Product'),
								new Element('span', {'class':'mini-basket-price'}).set('styles', {'font-weight':'bold','font-size':'15px'}).set('html', 'Price'),
								new Element('span', {'class':'mini-basket-qty'}).set('styles', {'font-weight':'bold','font-size':'15px'}).set('html', 'Qty')
							)
						);
						*/
					
						var items = $each(result.items, function(item, id) {
							wrapper.adopt(
								new Element('div',{'class':'mini-basket-item'}).adopt(
									//new Element('img', {'class':'mini-basket-packshot', 'src':item.img, 'alt':item.name}),
									new Element('span', {'class':'mini-basket-gamename'}).set('text', item.name),
									new Element('span', {'class':'mini-basket-qty'}).set('html', 'Qty: ' + item.qty),
									new Element('span', {'class':'mini-basket-price'}).set('html', currency + item.price),
									new Element('img', {'class':'mini-basket-delimg', 'src': result.del_icon}).addEvent('click', function(delEv) {
										new Event(delEv).stop();
										removeFromMiniBasket(id);
									}),
									new Element('hr')//, {'class': 'hr-with-falloff'})
								)
							)
						});

						wrapper.adopt(
							new Element('div',{'class':'mini-basket-item-sub'}).adopt(
								new Element('div').adopt(
									new Element('span', {'class':'mini-basket-sub-qty'}).set('html', 'Quantity: ' + result.count),
									new Element('span', {'class':'mini-basket-sub-total'}).set('html', 'Total: ' + currency + result.total)
								),
								new Element('br'),
								new Element('a', {'class':'mini-basket-view', 'href':'/page.php?page=basket'}).adopt(
									new Element('button', {'class':'shopto_button red', 'id':'GoToCheckout'}).set('styles', {'color':'white', 'font-size':'16px'}).set('text', 'Go To Checkout')
								)
							)
						);
						
						if(Browser.ie8)
						{
							wrapper.getElementById('GoToCheckout').set('onClick', 'redirect_to_checkout()').set('styles', {'background-color':'#830909'});
						}
					
					} else {
					
						wrapper.adopt(
							new Element('div',{'class':'mini-basket-item'}).adopt(
								new Element('div').set('text', 'Basket is empty.')
							)
						);
					}
					
					wrapper.inject($('mini-basket-wrapper'));
					
					var wrapper_height = (wrapper.getHeight() - 25);
					
					var myEffects = new Fx.Morph(wrapper, {
						duration: 600,
						transition: Fx.Transitions.Bounce.easeOut
					}).set({
						//'opacity':'0',
						'height':'0px',
						'overflow':'hidden'
					});

					myEffects.start({
						'height': wrapper_height,
						//'opacity':'1',
						'overflow':'visible'
					});
				}
			}
		}
	}).send();
}

function redirect_to_checkout()
{
	window.location = 'http://www.shopto.net/page.php?page=basket';
}

window.addEvent('domready', function()
{
	
	/* Notice on page*/
	var priority_alert = $(document.body).get('site:alert');
	if (priority_alert != null)
	{
		alert(priority_alert);
	}
	
	/* Mini Basket on TopBar */
	if( $('mini-basket-wrapper') != undefined )
	{
/*		$('mini-basket-trolley').addEvent('mouseenter', function(ev) {
			new Event(ev).stop();
			getMiniBasketTopBar();
		});
		
		$('mini-basket-totals').addEvent('mouseenter', function(ev) {
			new Event(ev).stop();
			getMiniBasketTopBar();
		});
*/		
		//var m_b_trolley = $('mini-basket-trolley');
		//var m_b_totals = $('mini-basket-totals');

		if( Browser.ie )
		{
			var m_b_trolley = $('mini-basket-trolley');
			
			if( m_b_trolley.addEventListener )
			{
				m_b_trolley.addEventListener('click',getMiniBasketTopBar,false);
			} else if( m_b_trolley.attachEvent ) {
				m_b_trolley.attachEvent('onclick',getMiniBasketTopBar);
			}
		} else {
				//$('mini-basket-trolley').addEvent('click', function(ev1) {
					//new Event(ev1).stop();
					//getMiniBasketTopBar();
				//});
				
				$('mini-basket-trolley').addEvents({
					click: function(ev1) {
						new Event(ev1).stop();
						getMiniBasketTopBar();
					},
					mouseover: function(ev1) {
						new Event(ev1).stop();
						getMiniBasketTopBar();
					}
				});
		}
		
/*
		m$('mini-basket-totals').addEvent('click', function(ev2) {
			new Event(ev2).stop();
			getMiniBasketTopBar();
		});
*/
	}

	/* Prettify any dates on the page (For shoptotv really) */

	$$("span.nicetimestamp").each( function(item) {
		item.set( "text", prettyDate(item.get("text")) );
	});

	/* Add the buy events (basket version, then version for everywhere else*/
	$$("a.buy_button").each( function(buy_button){
		buy_button.addEvent('click',function(ev){
			new Event(ev).stop();
//console.log(this.getProperty('codart'));
			var notice = new Element('div',{'class':'button_notice'});
			// hmm...
			this.notice = notice;

			var button_pos = buy_button.getPosition();
			var button_size = buy_button.getSize();
			var button_center = button_pos;
			button_center.x = button_pos.x + (button_size.x/2);
			button_center.y = button_pos.y + (button_size.y/2);

			notice.set('morph',{duration:'250', transition:Fx.Transitions.Sine.easeInOut});
//			document.body.adopt(notice);
			notice.inject($$('html body')[0]);

			notice.setStyles({
				'left': (button_center.x) - (notice.getSize().x/2),
				'top': (button_center.y) - (notice.getSize().y/2)
			});

			notice.set('morph',{duration:'250', transition:Fx.Transitions.Sine.easeInOut});
			document.body.adopt(notice);

			notice.showNotice = function(msg, classname)
			{
				this.adopt(new Element('p').set('html',msg))
					.addClass("button_notice")
					.addClass(classname)
					.setStyle('opacity','0')
					.morph({
						'opacity': 1,
						//'height': 50,
						'onComplete': function(){
							notice.hideNotice.delay( ( classname=='error' ? 2500 : 1000 ), notice);
						}
					});

				return( this );
			}

			notice.hideNotice = function()
			{
				return notice.morph({
					'opacity': 0
				});
			}

			if(this.getProperty('location')== 'basket')
			{
				new Request.JSON({
					method: 'post',
					url: '/feeds/basket.php',
					urlEncoded: true,
					data: {
							'action':'add',
							'codart':this.getProperty('codart'),
							'location':this.getProperty('location')
						},
					onComplete: function(result){
						if (result.result == false)
						{
							notice.showNotice(result.msg, 'error');
						}
						else
						{
							getMiniBasketTopBar();
							
							/*
							var container = $(document.body).getElement('table.basket_item_list');
							var product_html = new Element('tr').adopt(new Element('td').set('html',result.html));
							//console.log(product_html);
							var product_html_height = product_html.getStyle('height');
							product_html.setStyles({
									'visibility':'hidden',
									'height':'0px',
									'overflow':'hidden'
								});

							container.getChildren('tbody').adopt(product_html);

							var myEffects = new Fx.Morph(product_html, {
									duration: 1000,
									transition: Fx.Transitions.Sine.easeOut
								}).set({
									'opacity':'0',
									'height':'0px',
									'overflow':'hidden'
								});

							for( var i in result.order_details )
							{
								if($(i)!=null)
								{
									$(i).set('html',result.order_details[i]);
									$(i).getElements('.shopto_button').each( function(shopto_button){
										ieBorderRadius(shopto_button);
									});
								}
							}

							myEffects.start({
								'height': product_html_height,
								'opacity':'1',
								'overflow':'visible'
							});
							*/
						}
					}
				}).send();
			}
			else
			{
				// The target seems to be wrong on this event!
				if(ev.target.hasClass('shopto_button'))
				{
					ev.target = ev.target;
				} else {
					ev.target = ev.target.getParent();
				}
				minibasket_add(ev);
			}
		});
	});

	$$("a.buy_now_button").each( function(buy_now_button){
		buy_now_button.addEvent('click',function(ev){
			new Event(ev).stop();
				window.open(this.getProperty('one_click_location')+'/one_click_checkout.php?action=buy&codart='+this.getProperty('codart'), '', 'height=250,width=400,resizable=yes,scrollbars=yes');
		});
	});

	$$("a.preorder_button").each( function(preorder_button){
		preorder_button.addEvent('click',function(ev){

			var notice = new Element('div',{'class':'button_notice'});
			var button_pos = preorder_button.getPosition();
			var button_size = preorder_button.getSize();
			var button_center = button_pos;

			button_center.x = button_pos.x + (button_size.x/2);
			button_center.y = button_pos.y + (button_size.y/2);
			notice.set('morph',{duration:'250', transition:Fx.Transitions.Sine.easeInOut});
//			document.body.adopt(notice);
			notice.inject($$('html body')[0]);

			notice.setStyles({
				'left': (button_center.x) - (notice.getSize().x/2),
				'top': (button_center.y) - (notice.getSize().y/2)
			});

			notice.set('morph',{duration:'250', transition:Fx.Transitions.Sine.easeInOut});
			document.body.adopt(notice);

			notice.showNotice = function(msg, classname)
			{
				this.adopt(new Element('p').set('text',msg))
					.addClass("button_notice")
					.addClass(classname)
					.setStyle('opacity','0')
					.morph({
						'opacity': 1,
						//'height': 50,
						'onComplete': function(){
							notice.hideNotice.delay( ( classname=='error' ? 2500 : 1000 ), notice);
						}
					});


				return( this );
			}

			notice.hideNotice = function()
			{
				return notice.morph({
					'opacity': 0
				});
			}

			new Event(ev).stop();
			new Request.JSON({
				method: 'post',
				url: '/feeds/preorders.php',
				urlEncoded: true,
				data:{
					'codart' : this.getProperty('codart'),
					'action' : 'basket_preorder'
				},
				onComplete: function(result){
					if( result.status=="OK" )
					{
						if( result.redirect_url!=null )
						{
							var form = new Element('form', { 'id' : 'preorder_redirection', 'name' : 'preorder_redirection',  'method' : 'POST', 'action' : result.redirect_url });

							$each(result.redirect_data, function(value, key){
								form.adopt(new Element('input',{ 'type' : 'hidden', 'name' : key, 'value' : value }));
							});

							form.inject($$('html body')[0]).submit();
							
						} else {
							
							if( $('ShopToCardBottom-preorder')!=undefined )
							{
								if( ($('ShopToCardBottom-preorder').getChildren().length-1) >= 5 )
								{
									$('ShopToCardBottom-preorder').getLast().getPrevious().destroy();
								}
								
								var total_preorder_value = ($('ShopToCardBottom-preorder').getLast().getLast().getPrevious().getChildren().getLast().get('text').toFloat()+(result.price*1.2)).toFixed(2);
								var total_preorder_number = $('ShopToCardBottom-preorder').getLast().getFirst().getChildren().getLast().get('text').toInt() + 1;
								
								$('ShopToCardBottom-preorder').getLast().getLast().getPrevious().getChildren().getLast().set('text', total_preorder_value);
								$('ShopToCardBottom-preorder').getLast().getFirst().getChildren().getLast().set('text', total_preorder_number);
								
								var new_preorder = new Element('a', {'href':result.link}).adopt( new Element('img', {'src':result.boxart}) );
								new_preorder.inject($('ShopToCardBottom-preorder'), 'top');
							}

							showShopToCard();
							notice.showNotice('Product placed on preorder', 'ok');
							
							/*
							
							var preorder_mini_basket = $('preorder_mini_basket').getParent().getParent();
							var preorder_mini_basket_header = $('preorder_mini_basket').get('site:po_minibasket');
							
							if(Browser.ie8)
							{
								new_preorder_mini_basket = new Element('div',{'class':'side-panel-box'}).adopt(
										new Element('h4').set('text',preorder_mini_basket_header),
										new Element('div',{'class':'body'}).set('html',result.preorder_mini_basket)
									);
								new_preorder_mini_basket.replaces(preorder_mini_basket);					
							}else{
							
								var myEffects = new Fx.Morph(preorder_mini_basket, {
									duration: 500,
									transition: Fx.Transitions.Sine.easeOut
								}).start({
									'opacity':0
								}).chain(function(){

									new_preorder_mini_basket = new Element('div',{'class':'side-panel-box'}).adopt(
										new Element('h4').set('text',preorder_mini_basket_header),
										new Element('div',{'class':'body'}).set('html',result.preorder_mini_basket)
									);

									new_preorder_mini_basket.setStyle('visibility','hidden').inject($("left"));

									var height = new_preorder_mini_basket.getSize().y;

									var myEffects = new Fx.Morph(new_preorder_mini_basket, {
										duration: 1500,
										transition: Fx.Transitions.Sine.easeOut
									}).set({
										'visibility':'0'
									});

									new_preorder_mini_basket.replaces(preorder_mini_basket);

									myEffects.start({
										'opacity':1
									});

									notice.showNotice('Product placed on preorder', 'ok');
								});
							}
							*/
						}
					} else {
						notice.showNotice(result.msg, 'error');
					}
				}
			}).send();
		});
	});

/*
	if( $('mini_basket')!=null )
	{
		$('mini_basket').getElements('a.delete_button').each(function(button){
			button.addEvent('click', minibasket_delete);
		});
	}
*/
	/* rollover effects for related products tiles */
	$$('div.small_tile').each(function(element){
		element.original_width = element.getSize().x;
		element.image = element.getChildren('div.small_tile_image');
		element.textbox = element.getChildren('div.small_tile_text');
		element.smallsize = 124;

		element.fx = new Fx.Morph(element, {
			transition: Fx.Transitions.Bounce.easeOut,
			duration: 500
		}).set({
			'width': element.smallsize+'px',
			'overflow': 'hidden'
		});

		//Wait 50 milliseconds, then call myFunction and bind myElement to it.
		element.enlarge = function()
		{
			if (this.getSize() != this.smallsize+2)
			{
				this.fx.cancel().start({
					'width': this.original_width+'px'
				});

				this.textbox.setStyles({
					'display':'block'
				});
			}

			return( this );
		}

		element.shrink = function()
		{
			this.textbox.setStyles({
				'display':'none'
			});

			this.fx.cancel().start({
				'width': this.smallsize+'px',
				'overflow': 'hidden'
			});

//				'padding': '0px',

			return( this );
		}

		element.addEvent('mouseenter',function(ev) {
			$clear(this.shrink);
			this.enlarge.delay(500, this);
		});

		element.addEvent('mouseleave',function(ev) {
			$clear(this.enlarge);
			this.shrink.delay(500, this);
		});
	});

	/* 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('site: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('site:hsrc'));
			});

			img.addEvent('mouseout', function(ev){
				this.set('src', this.out_src);
			});
		}
	});

	/* Do IE Button Functions */
	$$('.shopto_button').each( function(shopto_button){
			ieBorderRadius(shopto_button);
		});

	// Setup the menu animations ...

	var menuX = $('menu');

	menuX.active_submenu = false;

	// Stop the click event from bubbling so that it stops
	// the irritating box that appears around them.
	menuX.getElements('a').each(function(link) {
		link.addEvent("mousedown", function(ev) {
			new Event(ev).stop();
		});
	});

	menuX.getElements('div.platforms a').each(function(link) {
		if( link.get('site: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('site: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('site:popup') )
			{
				case 'movies-submenu':
					href = href.replace('/MOVIES','');
					link.submenu.getElements('ul.charts a').each(function(sublink) {
						var count = sublink.getParent().get('site:'+platform.replace('%20',''));
						sublink.set('href', 'CHARTS/'+ sublink.get('href').replace('#',''));
					});

					// 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('site:'+platform.replace('%20',''));

						if( count==null && !sublink.getParent().get('site:all') )
						{
							sublink.getParent().removeChild(sublink);
						} else {
							sublink.set('href', href + sublink.get('href').replace('#',''));

/*
							if( count!=null )
							{
								sublink.set('text',sublink.get('text') + ' (' + count + ')');
							}
*/
						}
					});

					link.submenu.getElements('ul.genre a').each(function(sublink) {
						var count = sublink.getParent().get('site:'+platform.replace('%20',''));

						if( count==null && !sublink.getParent().get('site: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 + ')');
							}
*/
						}
					});

					link.submenu.getElements('ul.charts a').each(function(sublink) {
						var count = sublink.getParent().get('site:'+platform.replace('%20',''));

						if( sublink.getParent().get('site:all') )
						{
							sublink.getParent().removeChild(sublink);
						} else {
							sublink.set('href', domain + '/CHARTS/' + platform.toUpperCase() + 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( menuX.active_submenu==this )
				{
					menuX.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('site:popup');
				var platform = sublink.get('site:platform');

				if( platform )
				{
					sublink.setStyle('display',(popup==platform ? 'inline' : 'none'));
				} else {
					sublink.setStyle('display',(sublink.get('site:no-' + popup)=='true' ? 'none' : 'inline'));
				}
			});
*/

			// Attach the mouseover event.

			link.addEvent( "mouseover", function(ev) {
				new Event(ev).stop();

				if( menuX.active_submenu!=false && menuX.active_submenu!=link.submenu )
				{
					menuX.active_submenu.contract();
				}

				menuX.active_submenu = link.submenu;
/*
				if( menuX.active_link!=false )
				{
					menuX.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('site:popup');
					var platform = sublink.get('site:platform');

					if( platform )
					{
						sublink.setStyle('display',(popup==platform ? 'inline' : 'none'));
					} else {
						sublink.setStyle('display',(sublink.get('site: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 && menuX.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.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.trim();

		if( search_results.go ) {
			$clear(search_results.go);
			search_results.go = null;
		}

		if( text.length>2 )	{
			var filter = search_filter.value.split(",");
			var url = "/SEARCH/JSON/" + filter[0] + "/" + filter[1] + "/" + text.toUpperCase() + "/10";
//			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().replace('3ds','ddds'),'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();
			}.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;
		}

		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','class':'popup-help-links'}).adopt(ul).inject($$('html body')[0]);

				// Inject it into the container of the help link.
				popup_help = new Element('div',{'id':'popup-help-links','class':'popup-help-links'}).adopt(ul).inject($('popup-help').getParent());

				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 && ul.get('html')!='' ) {
						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');
	}

	var tips = new Tips({showDelay: 600});

	$$('.MooTip').each(function(element){
		var content = element.get('title').split(' :: ');
		element.store('tip:title', content[0]);
		element.store('tip:text', content[1]);
		tips.attach(element);
	});


	// Add input type validation to force entry of only basic ASCII characters.
	$$('input.ascii').each(function(element){
		element.addEvent('keypress',function(ev){
			//console.log('keydown');
			//console.log(ev);

			// Allow all basic ASCII.
			// (backspace=8 && tab=9 and enter=13 move the cursor they don't enter the value to the field).
			if( ev.code!=8 && ev.code!=9 && ev.code!=13 && (ev.code<32 || ev.code>127) )
			{
				alert('Sorry, you cannot enter the character "' + String.fromCharCode(ev.code) + '" in this field.');
				return( false );
			}
		});

		// Replace all non ascii on change - user should not be able to type
		// the character so this is just to handle if they copy paste.
		element.addEvent('change',function(ev){
			//console.log('change');

			var txt = ev.target.value;

            var new_txt = "";

			for( i=0 ; i<txt.length ; ++i )
			{
				if( txt.charCodeAt(i)>=32 && txt.charCodeAt(i)<=127 )
				{
					// Do not use txt[i] here because it doesn't work in IE.
					new_txt += txt.charAt(i);
				}
			}

			ev.target.value = new_txt;

			if( txt!=new_txt )
			{
				alert('Sorry, some characters cannot be used in this field and have been removed.');
				return( false );
			}
		});
	});


	// Add "hint" text to input fields.
	// Off in IE7 as casing js problems.
	
	if( !Browser.ie7 && !Browser.ie8 )
	{
		$$('input[site:hint]').each(function(element){
			element.ispassword = (element.get('type')=='password');

			if( element.value=='' )
			{
				element.value = element.get('site:hint');
				element.addClass('hint');

				if( element.ispassword )
				{
					element.set('type', 'text');
				}
			}

			element.addEvent('blur',function(ev){
				if( element.value=='' )
				{
					element.value = element.get('site:hint');
					element.addClass('hint');

					if( element.ispassword )
					{
						element.set('type', 'text');
					}
				}
			});

			element.addEvent('focus',function(ev){
				if( element.value==element.get('site:hint') )
				{
					element.value = '';
					element.removeClass('hint');

					if( element.ispassword )
					{
						element.set('type', 'password');
					}
				}
			});
		});
	
	} else {
		
		if( $('user') != undefined && $('pass') != undefined )
		{
			$('user').addEvents({
				mouseenter: function(){
					if( this.get('value') == '<USERNAME/EMAIL>' )
					{
						this.set('value', '');
					}
				},
				mouseleave: function(){
					if( this.get('value')=='' )
					{
						this.set('value', '<USERNAME/EMAIL>');
					}
				}
			});
			
			$('pass').addEvents({
				mouseenter: function(){
					if( this.get('value') == 'PASSWORD' )
					{
						this.set('value', '');
					}
				},
				mouseleave: function(){
					if( this.get('value')=='' )
					{
						this.set('value', 'PASSWORD');
					}
				}
			});
		}
	}
});

// 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" ||
			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 RenderProductComment(comment,config_image_host,deleteable, facebook_link, account_code)
{
	var stars = null;
	var deletebutton = new Element('img');


	if( comment.rating>0 )
	{
		stars = new Element('span');

		for( i=0 ; i<comment.rating ; ++i )
		{
			stars.adopt(
				new Element('img',{'src':config_image_host+'/stars/18on.gif','width':'18','height':'18','alt':'star'})
			);
		}

		for( j=i ; j<5 ; ++j )
		{
			stars.adopt(
				new Element('img',{'src':config_image_host+'/stars/18off.gif','width':'18','height':'18','alt':'star'})
			);
		}
	}
		
	if( facebook_link && account_code==comment.codcli )
	{
		facebook = new Element('div').set('styles',{'float':'right'}).adopt(
				new Element('a',{'target':'blank','href':'http://facebook.shopto.net/facebook_login.php?comment=' + comment.comment_id}).adopt(
						new Element('p').set('text', ' Post On Facebook').set('styles',{'color':'#3B5998','height':'8px','text-align':'center'}),
						new Element('img', {'src':config_image_host+'/misc/shopto_facebook.png'}).set('styles',{'width':'175px','height':'35px'})
					)
				);
	
	} else {
		
		facebook = '';
	}

	if(deleteable)
	{
//		deletebutton.set('src',config_image_host+'/buttons/'+myLanguage+'/cancel_icon.png').set('title','Click to delete comment').set('style','vertical-align: middle')
		deletebutton.set('src',config_image_host+'/icons/cancel_icon.png').set('title','Click to delete comment').set('style','vertical-align: middle')
		.addEvent('click',function(ev){

			new Event(ev).stop();
			new Request.JSON({
				method: 'post',
				url: '/feeds/comments.php',
				urlEncoded: true,
				data:
				{
					'action':'delete',
					'id':comment.comment_id
				},
				onComplete: function(result) {
					$('comment_'+comment.comment_id).getParent().dispose();
					alert("Deleted");
				},
				onFailure: function(){
					alert("Failed to delete");
				}
			}).send();
		});
	} else {
		deletebutton.setStyle('display','none');
	}

	var div = new Element('div', {'class':'comment','style':'min-height: 85px;','id':'comment_'+comment.comment_id}).adopt (
		new Element('img', {'class':'avatar','alt':comment.nickname+' avatar','src':'/AVATAR/'+comment.codcli}),
		new Element('p',{'id':'comment_title_'+comment.comment_id}).adopt (
			facebook,
			deletebutton,
			new Element('small').adopt(
				new Element('span').set('text',' '+prettyDate(comment.created)),
				new Element('span').set('text',' - '+comment.nickname+' wrote:')
			)
		)
	);

	if( stars!=null )
	{
		div.adopt(new Element('table',{'cellspacing':'0','cellpadding':'0'}).adopt(
			new Element('tbody').adopt(
				new Element('tr',{'height':'20'}).adopt(
					new Element('td',{'id':'stars_'+comment.comment_id}).adopt(stars),
					new Element('td').set('text','  '),
					new Element('td').adopt(
						new Element('strong').adopt(
							new Element('i').set('text',(comment.summary.length>0 ? '"'+comment.summary+'"' : '' ))
						)
					)
				)
			)
		));
	}

	div.adopt(
		new Element('hr'),
		new Element('span',{'html':comment.comment})
	);


	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 ieBorderRadius(button)
{
	if(Browser.ie8 || Browser.ie7)
	{
		if (!document.namespaces.v) { document.namespaces.add("v", "urn:schemas-microsoft-com:vml"); }
		//console.log(button.tagName +'|'+ +'|'+ button.offsetWidth +'|'+ button.offsetHeight);

		var arcSize = Math.min(parseInt(button.currentStyle['-moz-border-radius'] ||
										button.currentStyle['-webkit-border-radius'] ||
										button.currentStyle['border-radius'] ||
										button.currentStyle['-khtml-border-radius']) /
							   Math.min(button.offsetWidth, button.offsetHeight), 1);
		var fillColor = button.currentStyle.backgroundColor;
		var fillSrc = button.currentStyle.backgroundImage.replace(/^url\("(.+)"\)$/, '$1');
		var strokeColor = button.currentStyle.borderColor;
		var strokeWeight = 1; //parseInt(button.currentStyle.borderWidth);
		var width_adjustment = 0;
		var height_adjustment = 0;
		var stroked = 'true';
		if (isNaN(strokeWeight)) {
			strokeWeight = 1;
			strokeColor = 'black';
			stroked = 'true';
		}

		// Find which element provides position:relative for the target element (default to BODY)
		var el = button;

		var limit = 100, i = 0;
		while ((typeof(el) != 'unknown') && (el.currentStyle.position != 'relative') && (el.tagName != 'BODY')) {
			el = el.parentElement;
			i++;
			if (i >= limit) { return(false); }
		}



		var el_zindex = parseInt(el.currentStyle.zIndex);
		// IE7 & IE8 differs in their way to treat z-index and it seems both are wrong...
		if (isNaN(el_zindex)) {
			el.style.zIndex = 1;
			el_zindex = 1;
		}

		if (Browser.ie7)
		{
			if (button.tagName == 'BUTTON')
			{
				width_adjustment = -(button.offsetWidth * 0.3);
			}
		}

		var rect_size = {
			'width': (button.offsetWidth > 0? button.offsetWidth - strokeWeight + width_adjustment : button.offsetWidth),
			'height': (button.offsetHeight > 0? button.offsetHeight - strokeWeight + height_adjustment : button.offsetHeight)
		};

		var el_pos = findPos(el);
		var this_pos = findPos(button);
		this_pos.y = this_pos.y + (0.5 * strokeWeight) - el_pos.y;
		this_pos.x = this_pos.x + (0.5 * strokeWeight) - el_pos.x;

		//console.log('target is positioned inside '+el.tagName+' id #'+el.id+', class .'+el.className+', z-index:'+el_zindex+', pos:'+this_pos.x+'/'+this_pos.y);

		var rect = document.createElement('v:roundrect');
		rect.arcsize = arcSize +'px';
		rect.strokecolor = strokeColor;
		rect.strokeWeight = strokeWeight +'px';
		rect.stroked = stroked;
		//rect.fillcolor = "fillColor";
		rect.style.display = 'inline-block';
		rect.style.position = 'absolute';
		rect.style.top = (this_pos.y-(el.style.lineHeight)) +'px';
		rect.style.left = (this_pos.x) +'px';
		rect.style.width = rect_size.width +'px';
		rect.style.height = rect_size.height +'px';
		rect.style.antialias = true;
		rect.style.zIndex = -1;

		var fill = document.createElement('v:fill');
		create_button_fill(button.get('class'),fill);

		rect.appendChild(fill);
		el.appendChild(rect);

		isIE6 = /msie|MSIE 6/.test(navigator.userAgent);

		// IE6 doesn't support transparent borders, use padding to offset original element
		if (isIE6 && (strokeWeight > 0)) {
			button.style.borderStyle = 'none';
			button.style.paddingTop = parseInt(button.currentStyle.paddingTop || 0) + strokeWeight;
			button.style.paddingBottom = parseInt(button.currentStyle.paddingBottom || 0) + strokeWeight;
		}

		if (typeof(window.rounded_elements) == 'undefined') {
			window.rounded_elements = new Array();

			if (typeof(window.onresize) == 'function') { window.previous_onresize = window.onresize; }
			window.onresize = window_resize;
		}

		//button.element.vml = rect;
		button.vml = rect;

		button.style.background = 'transparent';
		button.style.overflow = 'visible';
		button.style.border = '';
		button.style.zIndex = el.style.zIndex+1;

		//console.log(button.vml);

		window.rounded_elements.push(button);
	}
}

function create_button_fill(classname, fill)
{
	fill.angle = "180";
	fill.type = "gradient";
	fill.opacity = "1";

	classes = classname.split(' ');

	for( i=0 ; i<classes.length ; ++i )
	{
		switch( classes[i] )
		{
			case 'black':
				fill.color = "#C7C7C7";
				fill.colors = "40% #828282,70% #363636";
				fill.color2 = "#5C5C5C";
				return;

			case 'highlighted':
				fill.color = "#CFC9CF";
				fill.colors = "40% #616061,70% #1C1C1C";
				fill.color2 = "#2B2B2B";
				return;

			case 'red':
				fill.color = "#C70C0C";
				fill.colors = "40% #830909,70% #370000";
				fill.color2 = "#5D0000";
				return;

			case 'tiny':
				fill.color = "#C70C0C";
				fill.colors = "40% #830909,70% #370000";
				fill.color2 = "#5D0000";
				return;

			case 'topmenu':
				fill.color = "#EEEEEE";
				fill.color2 = "#BBBBBB";
				return;

			case 'gold':
				fill.color = "#C28B00";
				fill.colors = "23% #C28B00,69% #FFCD05";
				fill.color2 = "#FFEA96";
				return;

			case 'disabled':
				fill.color = "#CCCCCC";
				fill.colors = "23% #CCCCCC,69% #857E7E";
				fill.color2 = "#575757";
				return;
		}
	}



/*
	if(classname.match('black'))
	{
		console.log('black matched');
		fill.color = "#C7C7C7";
		fill.colors = "40% #828282,70% #363636";
		fill.color2 = "#5C5C5C";
	}

	if(classname.match('highlighted'))
	{
		console.log('highlighted matched');
		fill.color = "#CFC9CF";
		fill.colors = "40% #616061,70% #1C1C1C";
		fill.color2 = "#2B2B2B";
	}

	if(classname.match('red'))
	{
		console.log('red matched');
		fill.color = "#C70C0C";
		fill.colors = "40% #830909,70% #370000";
		fill.color2 = "#5D0000";
	}

	if(classname.match('tiny'))
	{
		console.log('tiny matched');
		fill.color = "#C70C0C";
		fill.colors = "40% #830909,70% #370000";
		fill.color2 = "#5D0000";
	}

	if(classname.match('topmenu'))
	{
		console.log('topmenu matched');
		fill.color = "#EEEEEE";
		fill.color2 = "#BBBBBB";
	}

	if(classname.match('gold'))
	{
		console.log('gold matched');
		fill.color = "#C28B00";
		fill.colors = "23% #C28B00,69% #FFCD05";
		fill.color2 = "#FFEA96";
	}

	if(classname.match('disabled'))
	{
		console.log('disabled matched');
		fill.color = "#CCCCCC";
		fill.colors = "23% #CCCCCC,69% #857E7E";
		fill.color2 = "#575757";
	}

	fill.angle = "180";
	fill.type = "gradient"
	fill.opacity = "1";

	return;
*/
}

// findPos() borrowed from http://www.quirksmode.org/js/findpos.html
function findPos(obj)
{
	var curleft = curtop = 0;

	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}

	return({
		'x': curleft,
		'y': curtop
	});
}

function window_resize() {
	if (typeof(window.rounded_elements) == 'undefined') { return(false); }

	for (var i in window.rounded_elements)
	{
		var el = window.rounded_elements[i];

		var strokeWeight = 1; //parseInt(el.currentStyle.borderWidth);
		if (isNaN(strokeWeight)) { strokeWeight = 0; }

		if( el.vml )
		{
			var parent_pos = findPos(el.vml.parentNode);
			var pos = findPos(el);
			pos.y = pos.y + (0.5 * strokeWeight) - parent_pos.y;
			pos.x = pos.x + (0.5 * strokeWeight) - parent_pos.x;
	
			el.vml.style.top = pos.y +'px';
			el.vml.style.left = pos.x +'px';
		}
	}

	if (typeof(window.previous_onresize) == 'function') { window.previous_onresize(); }
}

/**********************************************************************/

function RenderCssWhiteBox(content,width,height)
{
	return new Element('div', {'class': 'white-box'}).adopt(content);
}

function RenderCssWhiteContainer(content,width,height)
{
	return new Element('div', {'class': 'white-container'}).adopt(content);
}

function RenderCssPageContent(content,width,height,visible)
{
	return new Element('div', {'class': 'page-content','style':(visible ? 'opacity:1' : 'opacity:0;display:none;')}).adopt(content);
}

function RenderCssWhiteBoxPageContent(content,width,height,visible)
{
	if(visible==undefined)
	{
		visible = true;
	}

	return RenderCssPageContent(RenderCssWhiteBox(content,width,height),width,height,visible);
//	return new Element('div', {'class': 'page-content','style':(visible ? 'opacity:1' : 'opacity:0;display:none;')}).adopt(RenderCssWhiteBox(content,width,height));
}

function RenderCssWhiteContainerPageContent(content,width,height,visible)
{
	if(visible==undefined)
	{
		visible = true;
	}

	return RenderCssPageContent(RenderCssWhiteContainer(content,width,height),width,height,visible);
//	return new Element('div', {'class': 'page-content','style':(visible ? 'opacity:1' : 'opacity:0;display:none;')}).adopt(RenderCssWhiteContainer(content,width,height));
}

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/JSON/LOGVIEW/' + video_id,
		urlEncoded: true
	}).send();
}

function shortenURL(target, prefix, url, suffix)
{
	return new Request({
		method: 'post',
		url: '/feeds/shortenurl.php',
		data:{'url':url},
		urlEncoded: true,
		onComplete: function(response)
		{
			target.set('href', prefix + response + suffix);
		},
		onFailure: function()
		{
			target.set('href', prefix + url + suffix);
		}
	}).send();
}

function playVideo(container, url, image_url, original_width, original_height, full_width, skin, autostart)
{
	/*
	 * 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 = '';
	}

	//checking if autostart is disabled
	if (autostart != false)
	{
		var autostart = (cookie.indexOf(video_name)==-1);
	}

	$(container).set('text','').setStyles({'outline-style':'none','width':'', 'height':''}).adopt(
		new Swiff(myScriptURL + '/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': autostart,
				'smoothing': 'true',
				'resizing': 'true',
				/*'plugins' : 'viral-1'*/
/*				'skin': '/scripts/longtail/jreid_shopto1/jreid_shopto1.xml' */

				/* There is a known bug with longtail with the zip version not working
				in 64bit Linux flash players - but it does work on windows and mac. */

				'skin': (skin!=false ? (skin=='black' ? '/scripts/longtail/jreid_shopto1_black.zip' : '/scripts/longtail/jreid_shopto1.zip') : false),
				'logo.hide': 'false',
				'logo.position': 'bottom-right',
				'logo': '/scripts/longtail/'+ (Math.random()>=0.5 ? 'shoptotv_logo1.png' : 'shoptotv_logo2.png')
			}
		})
	).set('site:video-id', parseInt(video_name));


	try{
		$('player').adopt(
			new Element('div',{'class':'no-flash'}).adopt(
				new Element('p').setStyles({
					'margin': (size[1]/3) + 'px auto'
				}).adopt(
					document.createTextNode('You do not have flash, please visit the'),
					new Element('br'),
					new Element('a',{"href":"http://get.adobe.com/flashplayer/"}).set('text','Adobe Flash website')

				)


			).setStyles({
				'background': 'black no-repeat url('+image_url+') center center',
				'height': size[1] + 'px',
				'outline-style':'none'
			})
		).setStyles({'outline-style':'none'});
	} catch(e) {
		// IE has some kind of problem with the above ...
	}



	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"
	});
*/
}


function showShopToCard()
{
	if( $('ShopToCard')!=undefined )
	{ 
		$('ShopToCard').setStyle('display','block').tween('opacity',0,1);
	}
	
	return;
}

