window.addEvent('domready', function() {
	//Add links to product list
	$$('.product-list a').addEvent('click', function() {
		var product_id = this.id.substr(12)
		var callback = {
			success: function(responseText) {
				$('vmMainPage').innerHTML = responseText;
				//customJS();
				//lookJS();
			}
		};
		var opt = {
			method:'get',
			onComplete:callback.success
		};
		new Ajax(live_site+'index2.php?option=com_virtuemart&page=shop.look_details&flypage=flypage_thelook&tmpl=component&vmccheck=1&only_page=1&product_id='+product_id, opt ).request();
	});
});

function gotoWishlist(loc){
    window.location = loc
}


//function wishlistLogin(formId) {
//	doPopup('<p>'+lang_theme_wishlist_login+'</p>');
//}

function handleAddToWishlistFailure(formId) {
	doPopup('<p>'+lang_theme_wishlist_select_size+'</p>');
	reinstatelinks();
}

function handleAddToWishlistSuccess( formId, parameters ) {
	formAddToWishlist = document.getElementById(formId);
	var callback = function(responseText) {
		var product_id = formAddToWishlist.getElement('input[name=product_id]').getProperty('value');
		var item_id = formAddToWishlist.getElement('input[name=Itemid]').getProperty('value');
		updateWishlistButton(product_id, item_id);
		doPopup('<p>'+lang_theme_wishlist_added+'</p>');
		reinstatelinks();
	};

	var opt = {
	    method:'post',
	    data:$(formId),
	    onComplete:callback,
	    evalScripts: true
	};

	new Ajax(formAddToWishlist.action, opt).request();
}

function handleRemoveFromWishlist( formId, parameters ) {
	formRemoveFromWishlist = document.getElementById( formId );

	var callback = function() {
		var product_id = formRemoveFromWishlist.getElement('input[name=product_id]').getProperty('value');
		var item_id = formRemoveFromWishlist.getElement('input[name=Itemid]').getProperty('value');
		updateWishlistButton(product_id, item_id);
		doPopup('<p>'+lang_theme_wishlist_removed+'</p>');
		reinstatelinks();
	};

	var opt = {
	    method:'post',
	    data:$(formId),
	    onComplete:callback,
	    evalScripts:true
	};

	new Ajax(formRemoveFromWishlist.action, opt).request();
}
function changeLookProduct(el){
	var callback = {
		success: function(responseText) {
			$('vmMainPage').innerHTML = responseText;
			activateLinks();
		}
	}; 
	var opt = {
		method: 'get',
		onComplete: callback.success
	};
	new Ajax( el.href + '&tmpl=component&vmccheck=1&only_page=1', opt ).request();	
	return false;
}
// RW - Added to ensure thelook works correctly.
function changeColorInfo(color)
{
    string = color.alt;
    output = string.substring(0, 15);
    if (string.length > 18)
        {
            output += "...";
        }
    document.getElementById('open-colours-more').innerHTML = "<center>" + color.alt + "</center>";
}

function doPopup(content) {
	//Close any previous popup
	if(typeof document.boxB != 'undefined') {
		document.boxB.close();
	}
	if(typeof timeoutID != 'undefined') {
		clearTimeout(timeoutID);
	}

	document.boxB = new MooPrompt('notice', content, {
		buttons:0,
		width:331,
		height:62,
		overlay:true,
		showCloseBtn:false
	});
	setTimeout('document.boxB.close()', 3000);
}

function updateWishlistButton(productid, item_id) {
	var callback = function(responseText) {
		button = $('wishlist-button');
		try {
			button.innerHTML = responseText;
		} catch(e) {}
	};
	var option = { method: 'post', onComplete: callback, data: {only_page:1, page:"shop.wishlist_button",flypage:"flypage_thelook", option:"com_virtuemart", Itemid:item_id, product_id:productid} };
	new Ajax( live_site + 'index2.php', option).request();
}

function changeLookProductcolor(el){
	var callback = {
		success : function(responseText) {
			$('vmMainPage').innerHTML = responseText;
			activateLinks();
		}
	};
	var opt = {
	    method: 'get',
	    onComplete: callback.success
    };
	new Ajax( el.href + '&only_page=1', opt ).request();
	return false;
}

function activateLinks(){
	var re = new RegExp("_[0-9]+x[0-9]+\.jpg");
	var count = 0; 
	
	// Declaring increment vars
	var totIncrement = 0;
	var increment = 167;
	var noIncrements = 2;
	
	
	// FX var
	var fx = new Fx.Style('available-colours', 'margin-left', {
	duration: 1000,
	transition: Fx.Transitions.Back.easeOut,
	wait: true
	});
	if ($('next')) {
		$('next').addEvents({
		'click' : function(event){
		if(count>=0 && ((count + 1) <= noIncrements)){
		totIncrement = totIncrement - increment;
		fx.stop();
		fx.start(totIncrement);
		count++;
		return false;
		}
		}});
	}
	
	if ($('previous')) {

		$('previous').addEvents({
			'click' : function(event){
			if(count>0 && count!=1){
			totIncrement = totIncrement + increment;
			fx.stop();
			fx.start(noIncrements);
			count--;
			totIncrement = 0;
				fx.stop()
				fx.start(0);
				count--;
				return false;
	
			}

	
			}
		});
	}
	
	$$('div#product-details .product-image-img').addEvent(
		'click',
		function () {
			$('product-main-image').setHTML('');
			$(document.body).getElement('#product-main-image').setStyle('background-image', 'url('+this.src.replace('/sdthumbnails', '').replace(re, ".jpg")+')');
		}
	);

	$$('.video').addEvent('click', function(event) {
		 new Event(event).stop();
		 var video = this.href;
		 var html = '<object id="video" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="490" height="598">';
		 html += '<param name="movie" value="'+location.protocol+'//'+location.hostname+'/static/video/playersd.swf" />';
		 html += '<param name="flashvars" value="url='+video+'&hHeight=598&hWidth=490" />';
		 html += '<param name="wmode" value="opaque">';
		 html += '<!--[if !IE]>-->';
		 html += '<object type="application/x-shockwave-flash" data="'+location.protocol+'//'+location.hostname+'/static/video/playersd.swf" width="490" height="598" wmode="opaque" flashvars="url='+video+'&hHeight=598&hWidth=490">';
		 html += '<!--<![endif]-->';
		 html += ' <a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>';
		 html += '<!--[if !IE]>-->';
		 html += '</object>';
		 html += '<!--<![endif]-->';
		 html += '</object><img src="'+location.protocol+'//'+location.hostname+'/static/images/overlays/product.png" class="product overlay" alt="" />';
		 $('product-main-image').setHTML(html);
	});
	
	if($('div-available-colours') != null) {
		//console.log($('available-colours'));
		
		//Colour picker
		$('div-available-colours').setStyle('position', 'absolute');
		//$('colours').setStyle('overflow', 'auto');
		var dropdown = new Fx.Style('div-available-colours', 'opacity', {duration: 500,transition: Fx.Transitions.linear, delay: 250});
		
		var shown = false;
		//var dropdown = new Fx.Tween('available-colours', 'opacity');
		if($('product-quantity')) dropdown.set(0);
                else dropdown.set(1); // Shows the colours to start

		if($('div-available-colours').getSize().size.y > 200){
			$('div-available-colours').setStyle("margin-top",(0-$('available-colours').getSize().size.y) + "px");
		}
		
		/*$('div-available-colours').addEvent('mouseover', function(event) {
			dropdown.set(1);
		});*/
		
		$('open-colours-more').addEvent('mouseover', function(event) {
			if (shown == false)
			{
				dropdown.start(0,1);
				shown = true;
			}
		});
		
		$('product-shop').addEvent('mouseleave', function(event) {
			if (shown == true)
			{
				dropdown.start(1,0);
				shown = false;
			}
		});
	}
}

/**
 * This file holds javscript functions that are used by the templates in the Theme
 * 
 */
 
 // AJAX FUNCTIONS 
function loadNewPage( el, url, isproduct ) {
	
	var theEl = $(el);
	var callback = {
		success : function(responseText) {
//			if($('order-details') != null) {
//				$('order-history').setStyle('height', 160);
//			}
			theEl.innerHTML = responseText;
			//if( Lightbox ) Lightbox.init();
			//R58 - Rerun custom JS on reload - Jonathan
			//if(isproduct) customJS();
			var ww = new WordWrapper({element: 'product-desc'});  
			//console.log(ww);
		}
	};
	var opt = {
	    // Use POST
	    method: 'get',
	    // Handle successful response
	    onComplete: callback.success
    };
	new Ajax(url + '&only_page=1', opt ).request();
}

function handleGoToCart() { document.location = location.protocol+'//'+location.hostname+'/index.php?option=com_virtuemart&page=shop.cart&product_id=' + formCartAdd.product_id.value ; }

function handleAddToCart( formId, parameters ) {
	formCartAdd = document.getElementById( formId );
	var callback = function(responseText) {
		updateMiniCarts();
		// close an existing mooPrompt box first, before attempting to create a new one (thanks wellsie!)
		if (document.boxB) {
			document.boxB.close();
			if(typeof(timeoutID) != 'undefined') clearTimeout(timeoutID);
		}
		document.boxB = new MooPrompt("", responseText, {
				buttons: 0,
				width:287,
				height:62,
				overlay: true,
				showCloseBtn:false
			});
		
		setTimeout('document.boxB.close()', 3000);
		setTimeout('activateLinks()', 3001);
	};
	
	var opt = {
	    // Use POST
	    method: 'post',
	    // Send this lovely data
	    data: $(formId),
	    // Handle successful response
	    onComplete: callback,
	    evalScripts: true
	};

	new Ajax(formCartAdd.action, opt).request();
}
/**
* This function searches for all elements with the class name "vmCartModule" and
* updates them with the contents of the page "shop.basket_short" after a cart modification event
*/
function updateMiniCarts() {
	var callbackCart = function(responseText) {
		carts = $$( '.vmCartModule' );
		if( carts ) {
			try {
				for (var i=0; i<carts.length; i++){
					carts[i].innerHTML = responseText;
		
					try {
						color = carts[i].getStyle( 'color' );
						bgcolor = carts[i].getStyle( 'background-color' );
						if( bgcolor == 'transparent' ) {
							// If the current element has no background color, it is transparent.
							// We can't make a highlight without knowing about the real background color,
							// so let's loop up to the next parent that has a BG Color
							parent = carts[i].getParent();
							while( parent && bgcolor == 'transparent' ) {
								bgcolor = parent.getStyle( 'background-color' );
								parent = parent.getParent();
							}
						}
						var fxc = new Fx.Style(carts[i], 'color', {duration: 1000});
						var fxbgc = new Fx.Style(carts[i], 'background-color', {duration: 1000});

						fxc.start( '#222', color );				
						fxbgc.start( '#fff68f', bgcolor );
						if( parent ) {
							setTimeout( "carts[" + i + "].setStyle( 'background-color', 'transparent' )", 1000 );
						}
					} catch(e) {}
				}
			} catch(e) {}
		}
	};
	var option = { method: 'post', onComplete: callbackCart, data: { only_page:1,page: "shop.basket_short", option: "com_virtuemart" } };
	new Ajax( location.protocol+'//'+location.hostname+'/index2.php', option).request();
} 
/**
* This function allows you to present contents of a URL in a really nice stylish dhtml Window
* It uses the WindowJS, so make sure you have called
* vmCommonHTML::loadWindowsJS();
* before
*/
//function fancyPop( url, parameters ) {
//	parameters = parameters || {};
//	popTitle = parameters.title || '';
//	popWidth = parameters.width || 700;
//	popHeight = parameters.height || 600;
//	popModal = parameters.modal || false;
//	
//	window_id = new Window('window_id', {className: "mac_os_x", 
//										title: popTitle,
//										showEffect: Element.show,
//										hideEffect: Element.hide,
//										width: popWidth, height: popHeight}); 
//	window_id.setAjaxContent( url, {evalScripts:true}, true, popModal );
//	window_id.setCookie('window_size');
//	window_id.setDestroyOnClose();
//}
