stockLevels = {};
stockLevel = 0;
totalStock = 0;
imageList = [];

$(document).ready(function(){
	//preload();
	initProductFilters();
	initStockNotificationForm();
	//initStockCheck();
	initBasketOverlay();
	//initProductImg();
	//initZoom();
	initBasketSummary();
	//initSizingInfo();
});

function initBasketSummary(){
	$("#basketSummary .contents").tooltip({ tip: "#basketInfo", position: "bottom center"});
	$("#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 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: 10, 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('/');
	//add in medium to the page
	path[3] = 'images/'+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: 10, adjustY:0').addClass('cloud-zoom').CloudZoom();
	}
}

function initProductFilters(){
	$('#productListing .filters select').change(function (){
		//when a select changes value, submit the form
		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 updateStockArea(){
	if(stockLevel > 0){
		//ensure add to basket is visible
		$('#productDetailsList >li:first').text('In Stock');
		$('#productDetailsList >li:first').css('color','#77787C');
		$('#productDetailsList >li:first').css('font-size','11px');		
		$('#productDetailsList .add').css('visibility', 'visible');
		$('.order #qtyBox').css('visibility', 'visible');
		$('.order #qtyBox :input').attr('disabled', false);
		$('#bisn').css('visibility', 'hidden');
	} else {
		//display stock message
		$('#productDetailsList >li:first').text('Out of Stock');
		$('#productDetailsList >li:first').css('color','red');
		$('#productDetailsList >li:first').css('font-size','18px');
		$('#productDetailsList .add').css('visibility', 'hidden');
		$('.order #qtyBox').css('visibility', 'hidden');
		$('.order #qtyBox :input').attr('disabled', true);
		$('#bisn').css('visibility', 'visible');
	}
}

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();
}

