stockLevels = {};
stockLevel = 0;
totalStock = 0;
imageList = [];

$(document).ready(function(){
	preload();
	initProductFilters();
	initStockNotificationForm();
	initStockCheck();
	initBasketOverlay();
	initProductImg();
	initZoom();
	initBasketSummary();
	initSizingInfo();
	initCategoryHover();
	initHideAttributeTextField();
	initHideAttributeTextFieldPostcard();
	
});

function initBasketSummary(){
	$("#basketSummary .contents").tooltip({ tip: "#basketInfo", position: "center left"});
	$("#basketSummary #bag").tooltip({ tip: "#basketInfo", position: "center left"});
}

function initSizingInfo(){
	$(".sizingInfo").tooltip({ position: "bottom center"});
}

function initProductImg(){
	$('#productAdditionalImages a').click(function (){productIn(this); return false;}).attr('href', '');
}

function initCategoryHover(){
$(".productGroups img").hover(function(){this.src = this.src.replace("-hover.jpg",".jpg");},function(){this.src = this.src.replace(".jpg","-hover.jpg");});
}



function productIn(el){
	var img = $(el).find('img')[0];
	
	var med = getImgPath('medium', img);
	var lrg = getImgPath('large', img);

	//update the larger image area
	$('#mainImage img').attr('src', med);
	$('#mainImage a').attr('href', lrg).attr('rel', 'adjustX: 0, adjustY:0').addClass('cloud-zoom').CloudZoom();
	
}

function productOut(el){
	//nothing to see here - move along please
}

function productImgClick(el){
    var img = $(el).find('img')[0];
    
	var src = getImgPath('large', img);
    
   $('#imageOverlay .overlayWrapper').html('<img src="' + src + '" />');
   $('#imageOverlay').overlay().load();
	
	return false;
}

function initOverlay(){
	addOverlay('imageOverlay');
}

function getImgPath(type, el){

	var path = el.src.split('/');
	
	path.splice(4, 1);
	
	//add in medium to the page
	path[3] = 'images/products/'+type;

	var imgPath = el.src;

	var tmpPath = path.join('/');
	//check if the image exists

	if(imgExists(tmpPath)){
		imgPath = path.join('/');
	} else {
		//if the image was large and didn't exist, then check for medium
		if(type == 'large'){
			path[3] = 'images/medium';
			var medPath = path.join('/');
			if(imgExists(medPath)){
				//still revert to original path
				imgPath = medPath;
			}
		}
	}
	//join back
	return imgPath;
}

function imgExists(path){
	var exists = false;
	//check if it is listed in the imageList array. 
	for(var i = 0; i < imageList.length; i++){
		if(imageList[i] == path){
			exists = true;
			break;
		}
	}
	
	if(!exists){
		//not in the array, try and load it
		var img = new Image();	
		img.onload = function (e){
			e = e ? e : window.event;
			imageList.push(e.target.src);
			};
		img.src = path;
		if(img.width > 0){}
		img = null;
	}
	return exists;
}

function initZoom(){
	//need to trigger initial product image
	var prodImg = $('#mainImage');
	if(prodImg.length > 0){
		var base = {};
		var img = prodImg.find('img')[0];

		base.src = img.src.replace(/medium\//, '');
		var lrg = getImgPath('large', base);

		$(img).parent('a').attr('href', lrg).attr('rel', 'adjustX: -2, adjustY:0, zoomWidth:370').addClass('cloud-zoom').CloudZoom();
	}
}

function initProductFilters(){
	$('#productListing .filters select, .controls .filters select').change(function (){
		//when a select changes value, submit the form
		//but only if there is a value
		if(this.value !== ''){
			this.form.submit();
		}
	});
}

function initStockNotificationForm(){
	//find the form and hide
	var f = $('form[name="back_in_stock_notification"]');
	if(f.length > 0){
		f.hide();
		addFormOverlay();
		//target the link
		$('a[href*="back_in_stock_notification_form"]').click(function (){
			//grab the form and add to the overlay
			f.appendTo('#formOverlay > .overlayWrapper').show();
			$('#formOverlay').overlay().load();
			return false;
		});
		
	}
}

function initStockCheck(){
	//retrieve all attributes - initially
	checkAllAttributes();
	
	//now, we need to update this based on any changes in arrtributes
	$('select[id^="attrib"]').change(function (){
		checkAllAttributes();
	});
}

function updateStockAreaX(){
	if(stockLevel > 0){
		//ensure add to basket is visible
		$('#productDetailsList >li:first').text('In Stock');
		$('#productDetailsList .add').css('visibility', 'visible');
	} else {
		//display stock message
		$('#productDetailsList >li:first').text('Out of Stock');
		$('#productDetailsList .add').css('visibility', 'hidden');
	}
}
function updateStockArea(){

}

function checkAllAttributes(){
	stockLevel = totalStock;
	var ids = [];
	$('select[id^="attrib"]').each(function (){
		ids.push(this.value);
	});
	
	//now we have a collection of attributes - if there is only one
	//just check against that id, otherwise all ids have to exists
	if(ids.length == 1){
		checkStock(ids[0]);
	} else if(ids.length > 1){
		multiCheckStock(ids);
	}
	
	updateStockArea();
}

function checkStock(id){
	var level = 0;
	outer:
	for(var i in stockLevels){
		for(var j in stockLevels[i].attrs){
			if(id == stockLevels[i].attrs[j].id){
				level = stockLevels[i].qty;
				break outer;
			}
		}
	}
	stockLevel = level;
}

function multiCheckStock(ids){
	//work through each level check that all ids exist before updating stockLevel
	var level = 0;
	for(var i in stockLevels){
		var joined = [];
		for(var j in stockLevels[i].attrs){
			joined.push(stockLevels[i].attrs[j].id);
		}
		//sort the arrays so they are in the same order
		joined.sort();
		ids.sort();
		if(joined.join(',') == ids.join(',')){
			level = stockLevels[i].qty;
			break;
		}
	}
	stockLevel = level;
}

function addFormOverlay(){
	addOverlay('formOverlay');
}

function addOverlay(id){
	$('body').append('<div id="' + id + '" class="overlay"><div class="close"</div><div class="overlayWrapper"></div></div>');
	$('#' + id).overlay({
		top: 50,
		mask: {
			color: '#FFF',
			loadSpeed: 200,
			opacity: 0.7
		},
		closeOnClick: true,
		fixed: false
	});
}

function preload(){
	//we are basically going to work through all the images - before rollover
	//and check paths, which should cause preloading
	//$('#productAdditionalImages a').each(function (){
	//	var img = $(this).find('img')[0];
	//	if(img){
			//var med = getImgPath('medium', img);
			//var lrg = getImgPath('large', img);
	//	}
	//});
	
	//now for the main image
	//var prodImg = $('#mainImage');
	//if(prodImg.length > 0){
	//	var base = {};
	//	var img = prodImg.find('img')[0];
	//	base.src = img.src.replace(/medium\//, '');
		//add medium as that is what we start with
	//	imageList.push(img.src);
	//	var lrg = getImgPath('large', base);
	//}
}

function initBasketOverlay(){
	var note = $('#basketNotification');
	if(note.length > 0){
		note.find('.close').show().click(function (){hideNotification(); return false;});
		//set a timeout to automatically hide the notification
		setTimeout(hideNotification, 5000);
	}
}

function hideNotification(){
	$('#basketNotification').fadeOut();
}
function initHideAttributeTextField(){
	//this is based on fixed attribute IDs. If they change, we need to change this
	var textField = $('#attrib-9-0').parent('td');
	
	if($('#attrib-9-0').parent('td').hasClass('td_customisation'))
	{
		var select = $('#attrib-8');
		if(!select.find('option:selected').text().match(/Custom.*/)){
			$('#attrib-9-0').hide();
			$('#attrib-9-0').prev().hide();
			$('#attrib-9-0').prev().prev().hide();
		}
		
		//add change handler
		select.change(function (){
			if($(this).find('option:selected').text().match(/Custom.*/))
			{
				$('#attrib-9-0').fadeIn();
				$('#attrib-9-0').prev().fadeIn();
				$('#attrib-9-0').prev().prev().fadeIn();
			} 
			else 
			{
				$('#attrib-9-0').fadeOut();
				$('#attrib-9-0').prev().fadeOut();
				$('#attrib-9-0').prev().prev().fadeOut();
			}
		});
	}	
	else
	{
		if(textField.length > 0)
		{
			var select = $('#attrib-8');
			if(!select.find('option:selected').text().match(/Custom.*/)){
				$('#attrib-9-0').hide();
			}
			
			//add change handler
			select.change(function (){
				if($(this).find('option:selected').text().match(/Custom.*/))
				{
					$('#attrib-9-0').fadeIn();
				} 
				else 
				{
					$('#attrib-9-0').fadeOut();
				}
			});
		}
	}
}
function initHideAttributeTextFieldPostcard(){
	//this is based on fixed attribute IDs. If they change, we need to change this
	var textField = $('#attrib-12-0').parent('td');
	$('input[name="remainingtxt_12"]').addClass('counter');
	if($('#attrib-12-0').parent('td').hasClass('td_customisation'))
	{
		var select = $('#attrib-11');
		if(!select.find('option:selected').text().match(/Custom.*/)){
			$('#attrib-12-0').hide();
			$('input[name="remainingtxt_12"]').hide();
			$('input[name="remainingtxt_12"]').prev().prev().hide();
			$('.shifty').hide();
		}
		
		//add change handler
		select.change(function (){
			if($(this).find('option:selected').text().match(/Custom.*/))
			{
				$('#attrib-12-0').fadeIn();
				$('input[name="remainingtxt_12"]').fadeIn();
				$('input[name="remainingtxt_12"]').prev().prev().fadeIn();
				$('.shifty').fadeIn();
			} 
			else 
			{
				$('#attrib-12-0').fadeOut();
				$('input[name="remainingtxt_12"]').fadeOut();
				$('input[name="remainingtxt_12"]').prev().prev().fadeOut();
				$('.shifty').fadeOut();
			}
		});
	}
	else
	{
		if(textField.length > 0)
		{
			var select = $('#attrib-11');
			if(!select.find('option:selected').text().match(/Custom.*/)){
				textField.hide();
			}
		
			//add change handler
			select.change(function (){
				if($(this).find('option:selected').text().match(/Custom.*/))
				{
					textField.fadeIn();
				} 
				else 
				{
					textField.fadeOut();
				}
			});
		}
	}
}
