
	hotspots=[];

	// fiche zoning controls
	$(window).resize(function() {
		$("#ficheZone").ficheZoneResize();
	});
	$(window).scroll(function() {
		$("#ficheZone").ficheZoneResize();
	});
	
	// unit functions
	initUnitYear=function() {
		$("#year").change(function() {
			supplier=$("#supplier").val();
			year=$("#year").val();
			if (supplier=="" || year=="") {
				$("#unitModelSelect").html('');
				return;
			}
			window.location.href=c8urls.main+"find/type/"+supplier+"/"+year;
			return false;
		});
	}
	initUnitType=function() {
		$("#supplier").change(function() {
			supplier=$("#supplier").val();
			$("#unitModelSelect").html('');
			if (supplier=="") {
				$("#unitYearSelect").html('');
				return;
			}
			$("#unitYearSelect").html('<img src="'+'/shop/static/images/ajax-loader-small.gif"/><span style="padding-left:10px;">Searching...<span>');
			$.post(c8urls.ajax+"unit/year/"+supplier,null,function(data) {
				$("#unitYearSelect").html(data);
				initUnitYear();
			});
		});
	}
	
	viewqtywindow=function(href,id) {
		c=$("#modifyPart");
		c.html('<img src="'+'/shop/static/images/ajax-loader-small.gif"/><span style="padding-left:10px;">Loading...</span>');
		c.eventTop(href).show();
		$.post(c8urls.main+"basket/vieweqty/"+id,null,function(data) {
			c.html(data).eventTop(href).find("#qty").focus();
			c.find("#close").click(function() {
				$("#modifyPart").hide(); 
			});
			c.find("#update").click(function() { 
				$.post(c8urls.main+"basket/modqty/"+$(c).find("#partid").val()+"/"+c.find("#qty").val(),null,function(data) {
					handleQtyChange(id,data);
					$("#modifyPart").hide(); 
				});
			} );
			c.find("#delete").click(function() { 
				$.post(c8urls.main+"basket/modqty/"+$(c).find("#partid").val()+"/0",null,function(data) {
					handleQtyChange(id,data);
					$("#modifyPart").hide(); 
				});
			} );
			c.find(".openExplainQty").explainQty();
		});		
	}
	
	// image zoomer
	imageZoomSetup=false;
	imageZoom=function(picture) {
			if (imageZoomSetup) return;
			imageZoomSetup=true;

			picture_width=picture.width();
			picture_height=picture.height();
			
			img=picture.parent();
			img_width=img.width();
			img_height=img.height();
			if (img_width<picture_width || img_height<picture_height)
			{
				picture.width(picture_width*80/100);
				picture.height(picture_height*80/100);
			};

			var drag;
			var drag_x;
			var drag_y;
			var size=80;
			
			var mvMouseMoveHandler;
			var mvMoseUpHander;
			
			mvMouseMoveHandler = function(event) {
				if (!drag) return;
				event.preventDefault();
				img.scrollLeft(drag_x-event.pageX);
				img.scrollTop(drag_y-event.pageY);
			};

			mvMouseUpHandler = function(event) {
				drag=false;
				$(document).unbind("mouseup",mvMouseUpHandler);
				$(document).unbind("mousemove",mvMouseMoveHandler);				
			};

			$("#hotspotMarker").click(function(event) {
				event.stopPropagation();
				viewqtywindow(event,$(this).attr('rel'));
			});
			
			picture.mousemove(function(event) {
				o = $(picture).offset();
				hit_x=(event.pageX-3-o.left)*100/size;
				hit_y=(event.pageY-7-o.top)*100/size;
				
				for (scan=0;scan<hotspots.length;scan++) {
					if (hit_x>=hotspots[scan][1] && hit_x<=hotspots[scan][1]+hotspots[scan][3]
					  && hit_y>=hotspots[scan][2] && hit_y<=hotspots[scan][2]+hotspots[scan][4]
					) {
						x=$("#hotspotMarker");
						pofs=x.parent().offset();
						$(x).show();
						$(x).css({
								"left" : hotspots[scan][1]*size/100+3, 
								"top" :  (-picture_height+hotspots[scan][2])*size/100-7,
								"width" : hotspots[scan][3]*size/100+1,
								"height" : hotspots[scan][4]*size/100+1,
							});
						$(x).attr('rel',hotspots[scan][0]);
						return true;
					}
				}			
				$("#hotspotMarker").hide();
			});
			
			picture.mousedown(function(event) {
				
				o = $(picture).offset();
				hit_x=(event.pageX-5-o.left)*100/size;
				hit_y=(event.pageY-5-o.top)*100/size;
				
				for (scan=0;scan<hotspots.length;scan++) {
					if (hit_x>=hotspots[scan][1] && hit_x<=hotspots[scan][1]+hotspots[scan][3]
					  && hit_y>=hotspots[scan][2] && hit_y<=hotspots[scan][2]+hotspots[scan][4]
					) {
						return true;
					}
				}
				
				event.preventDefault();
					
				drag=true;
				drag_x=img.scrollLeft()+event.pageX;
				drag_y=img.scrollTop()+event.pageY;
				$(document).mouseup(mvMouseUpHandler);
				$(document).mousemove(mvMouseMoveHandler);
			});
			
			var zMouseMoveHandler;
			var zMoseUpHander;

			zMouseMoveHandler = function(event) {
				if (!drag) return;
				event.preventDefault();
				
				o = $("#ficheZoomThumb").offset();
				r = $("#ficheZoom").offset();
				o.left=event.pageX-7;
				if (o.left<r.left) {
					o.left=r.left;
				}
				if (o.left+15>r.left+100) {
					o.left=r.left+100-15;
				}
				$("#ficheZoomThumb").offset(o);

				size=40+(o.left-r.left)/1;
				picture.width(picture_width*size/100);
				picture.height(picture_height*size/100);
			};

			zMouseUpHandler = function(event) {
				drag=false;
				$(document).unbind("mouseup",zMouseUpHandler);
				$(document).unbind("mousemove",zMouseMoveHandler);				
			};
			
			zMouseDownHandler=function(event) {
				event.preventDefault();						
				
				drag=true;
				$(document).mouseup(zMouseUpHandler);
				$(document).mousemove(zMouseMoveHandler);
				zMouseMoveHandler(event);
			};

			o=$("#ficheZoom").mousedown(zMouseDownHandler).offset();
			
			o.left+=80;
			o.top-=5;

			$("#ficheZoomThumb").mousedown(zMouseDownHandler);//.offset(o);
			
	};

	// simple function to goto selected part
	loadPart=function(id) {
		window.location=c8urls.main+"find/part/"+id;
	}
	
	// redraw basket summary after AJAX submission on qty change
	handleQtyChange=function(id,data) {
		data=eval("("+data+")");
		$("#fichePartsTable").find("#"+id).find("#qty").html(data.qty);
		$("#basketSummary").html(data.basket);		
	};
	

	// generic form submission. Uses AJAX to sumbit. Used heavily in checkout process
	jQuery.fn.c9Submit = function(settings)
	{
		this.each(function() {
			settings.form=this;
			$(this).submit(function() {
				$('.validation-error').removeClass('validation-error');
				$('.validation-segment').remove();
				$(settings.form).find('#noticeboard').html("");
				$(this).each(function (index,element) {
					$.ajax({
						"type":"POST",
						"url":settings.url,
						"data":$(element).serialize(),
						"async" : false,
						"error" : function(x,y,z) { alert("Something went wrong:"+z); },
						"cache": false,
						"success": function(data) {
							$error=0;
							if (data) {
								var json = eval('(' + data + ')');
								if (json.validation) {
									$('.validation-error').removeClass('validation-error');
									$('.validation-segment').remove();
									for (var v in json.validation) {
										if (json.validation.hasOwnProperty(v)) {
											$(settings.form).find('input[name|='+v+']').parent().addClass('validation-error')
											.append('<div class="validation-segment">'+json.validation[v]);
										}
									}
									return;
								}
								if (json.error) {
									$error=1;
									var content="";
									for (var msg in json.error) {
										content=content+'<div class="'+json.error[msg][0]+'>'+json.error[msg][1]+'</div>';
									}
									$(settings.form).find('#noticeboard').html(content);
									return;
								}							
								if (json.redirect) {
									window.location=json.redirect;
									return;
								}
							}
							if ("success" in settings) {
								settings.success();
							} 
							if ("redirect" in settings) {
								window.location=settings.redirect;
							}
						}
					});
				});
				return 1;
			});
			return this;
		});
	};

	// handle resizing of fiche image/parts
	var ficheZoneRatio=0.5;
	ficheRatioResize=function()
	{
		var drag;
		var rMouseMoveHandler;
		var rMoseUpHander;

		rMouseMoveHandler = function(event) {
			event.preventDefault();			
			o = $("#ficheRatioThumb").offset();
			r = $("#ficheZone").offset();
			o.top=event.pageY;
			if (o.top<r.top) {
				//o.top=r.top;
			}
			o.top=o.top-r.top;
			ficheZoneRatio=(o.top-25-220)/($("#ficheZone").height()-25-220);
			if (ficheZoneRatio<0.1) ficheZoneRatio=0.1;
			if (ficheZoneRatio>0.9) ficheZoneRatio=0.9;
			$("#ficheZone").ficheZoneResize();
		};

		rMouseUpHandler = function(event) {
			drag=false;
			$(document).unbind("mouseup",rMouseUpHandler);
			$(document).unbind("mousemove",rMouseMoveHandler);
		};
		
		rMouseDownHandler=function(event) {
			event.preventDefault();
			drag=true;
			$(document).mouseup(rMouseUpHandler);
			$(document).mousemove(rMouseMoveHandler);
		};

		$("#ficheRatioThumb").mousedown(rMouseDownHandler);
	};	
	
	// handle resizing of entire fiche zone
	jQuery.fn.ficheZoneResize=function() {
		return this.each(function(){
			winheight=$(window).height()-5;
			height=winheight-$(this).offset().top;
			height+=$(window).scrollTop();
			$(this).height(height);
			height=height-30-220;
			$(this).find("#ficheImage").height(height*ficheZoneRatio);
			$(this).find("#fichePartsList").height(height*(1-ficheZoneRatio));
		  });
	};

	jQuery.fn.explainQty=function()
	{
		return this.click(function(event){
			event.stopPropagation();
			$("#explainQty").bbTop($(this)).show();
		});
	}
	
	// popup window
	jQuery.fn.bbTop=function(parent) {
				return this.each(function(){
					o=$(this).offset();
					p=parent.offset();
					ph=parent.outerHeight();
					wh=$(window).height();
					h=$(this).outerHeight();
					w=$(this).outerWidth();
					
					l=p.left-w/2;
					if (l<0) l=0;

					if (p.top+ph+h+10>wh) {
						$(this).css({"left" : l, "top" : p.top-h });
					} else {
						$(this).css({"left" : l, "top" : p.top+ph });
					}
				});
	};

	jQuery.fn.eventTop=function(event) {
		return this.each(function(){
			wh=$(window).height();
			h=$(this).outerHeight();
			w=$(this).outerWidth();
			
			l=event.pageX-w/2;
			if (l<0) l=0;

			
			py = event.pageY-h/2;
			if (py<0) py=0;

			if (py+h+10>wh) {
				$(this).css({"left" : l, "top" : py-h/2 });
			} else {
				$(this).css({"left" : l, "top" : py });
			}
		});
};
	
	
	$(document).ready(function() {
		$(".openExplainQty").explainQty();
		
		// init fiche zone
		ficheRatioResize();
		$("#ficheZone").ficheZoneResize();

		var ulList=new Array();
		// init sidebar sizes
        //var abs_top = $("#sideBarDiv").offset().top;
		var abs_top=0;
		$("#sideBar ul").each(function() {
			a=$(this).prev("a");
			margin=0;
			var top=0;
			margin=$(a).offset().top;
			top=$(this).height()/2-$(a).height()/2;
			margin=margin-top;
            if (margin<abs_top) margin=abs_top;
			$(this).offset({ 
				"left" : $(this).parent().offset().left+$(this).prev("a").width()
				,"top" : margin
			} );
			
			ulList.unshift(this);
		});
		
		for (i=0;i<ulList.length;i++) {
			$(ulList[i]).hide();
		}
		
		var clearAllSideBar;
		var clearAllSideBarFunc=function()
		{
			for (i=0;i<ulList.length;i++) {
				$(ulList[i]).hide();
			}
			$("#sideBar a").removeClass("selectedBar");
			clearAllSideBar=null;
		};
		
		$(document).click(function() {
			if (clearAllSideBar!=null) {
				clearAllSideBarFunc();
			}
		});
		
		// side bar hover and click
		$("#sideBar").find("ul").hide();
		$("#sideBar a").click(function(event) { event.stopPropagation(); } );
		$("#sideBar a").hover(function() {
			var ulList=new Array();
			$(this).parent().parent().find("ul").each(function() {
				ulList.unshift(this);
			});
			for (i=0;i<ulList.length;i++) {
				$(ulList[i]).hide();
			}
			$(this).parent().parent().find("a").removeClass("selectedBar");
			$(this).addClass("selectedBar");
			$(this).next("ul").show();
			clearTimeout(clearAllSideBar);
		},function() {
			clearAllSideBar=setTimeout(clearAllSideBarFunc,1000);
		});
		
		// part seach popup
		$("#partSearchList").hide();

		// modify part popup
		$("#modifyPart").hide().click(function(event) {  
			event.stopPropagation();
			p=$("#explainQty");
			if (p.is(":visible")) {
				p.hide().offset({ "left" :0, "right" :0 });
			}
		});

		$("#explainQty").hide().click(function(event) {  
			event.stopPropagation();
		});
		
		// fiche component scrollers
		$("#scrollLeft").click(function() {
			$("#componentList").animate({scrollLeft: $("#componentList").scrollLeft()-170},100);
		});
		
		$("#scrollRight").click(function() {
			$("#componentList").animate({scrollLeft: $("#componentList").scrollLeft()+170},100);
		});
		
		// click outside modify part. This looks a little inefficient. Should only bind when modify part shows
		$("body").click(function(event) {
			p=$("#modifyPart");
			if (p.is(":visible")) {
				p.hide().offset({ "left" :0, "right" :0 });
			}
			p=$("#explainQty");
			if (p.is(":visible")) {
				p.hide().offset({ "left" :0, "right" :0 });
			}
		});

		// part number searching and arrow keys
		var partLookupTimeout=null;
		$("#partnumber").keydown(function(event) {
			if (event.which==40) { // down
				base=$("#partSearchList");
				pos=$(base).find("tr.selected");
				if (pos.next().length==0) return;
				$(base).find(".selected").removeClass("selected");
				pos.next().children().addClass("selected");
				pos.next().addClass("selected");
			}
			if (event.which==38) { // up
				base=$("#partSearchList");
				pos=$(base).find("tr.selected");
				if (pos.prev().length==0) return;
				$(base).find(".selected").removeClass("selected");
				pos.prev().children().addClass("selected");
				pos.prev().addClass("selected");
			}
			if (event.which==13) { // up
				base=$("#partSearchList");
				pos=$(base).find("tr.selected");
				if (pos.length==0) return;
				loadPart(pos.attr("id"));
			}
		});

		var lastval='';
		$("#partnumber").keydown(function(event) {
			if (partLookupTimeout!=null) {
				clearTimeout(partLookupTimeout);
			}
			base=$(this);
			partLookupTimeout=setTimeout(function() {
			val=base.val();
			if (lastval==val) return;
			lastval=val;
			if (val=='') {
				$('#partSearchList').hide();
				$('#partSearchList').offset({ "left" :0, "right" :0 });
				return;
			}
			psl=$('#partSearchList');
			if (!psl.is(":visible")) {
				psl.html('<img src="'+'/shop/static/images/ajax-loader-small.gif"/><span style="padding-left:10px;">Searching...<span>');
				psl.bbTop($("#partnumber"));
				psl.show();
			}
			$.post(c8urls.ajax+"search/part/",base.parents("form").serialize(),function(data) {
				$(".selected").removeClass("selected");
				$("#partSearchList").html(data).find(".partMatch").hover(function() {
					$(".selected").removeClass("selected");
					$(this).parent().find("td").addClass("selected");
					$(this).parent().addClass("selected");
				});
				$("#partSearchList").find("tr").click(function() { 
					loadPart($(this).attr("id"));
				});
			});
			},250);
		});
		

		// unit search selection
		$("#unitSearch").submit(function() {
			window.location.href=c8urls.main+"find/type/"+
				$(this).find("#supplier").val()+"/"+
				$(this).find("#year").val();
				return false;
		});
		
		// unit selection
		$("#unitThumbPanel li").click(function() {
			unit=$(this).attr("id");
			if (unit==0) return;
			window.location.href=c8urls.main+"find/unit/"+unit;
		});

		$("#unit").change(function() { 
			unit=$("#unit").val();
			if (unit==0 || unit=="") return;
			window.location.href=c8urls.main+"find/unit/"+unit;
			return false;
		});

		// fiche selection
		$("#fiche").change(function() { $("#selectFiche").submit(); }); 
		$("#selectFiche").submit(function() {
			unit=$(this).find("#fiche").val();
			if (unit==0) return;
			window.location.href=c8urls.main+"find/fiche/"+unit;
			return false;
		});
				
		$(".selectableComponent").click(function() {
			window.location=c8urls.main+"find/fiche/"+$(this).attr("id");
			return;
		});

		$("#basketButton").click(function() { 
			window.location=c8urls.main+"basket";
			return false;
		});
		
		$("#ficheLink a").click(function() {
			window.open($(this).attr("href"),null,'resizable=true');
			return false;
		});
	
		
		$("#update").click(function() { 
			c=$(this).parents("form");
			$.post(c8urls.main+"basket/modqty/"+$(c).find("#partid").val()+"/"+c.find("#qty").val(),null,function(data) {
				window.location.reload();
			});
		} );
		$("#delete").click(function() { 
			c=$(this).parents("form");
			$.post(c8urls.main+"basket/modqty/"+$(c).find("#partid").val()+"/0",null,function(data) {
				window.location.reload();
			});
		} );
		
		
		$("#fichePartsTable tr td").click(function(event) {
			event.stopPropagation();
			viewqtywindow(event,$(this).parent().attr("id"));
		});
				
		$(".partCell").hover(function() {
			$(".selected").removeClass("selected");
			$(this).parent().children("td").addClass("selected");
		});

		$("#fichePartsTable tr td").hover(function() {
			$(".selected").removeClass("selected");
			$(this).parent().children("td").addClass("selected");
		});

		$(".basketCell").hover(function() {
			$(".selected").removeClass("selected");
			$(this).parent().children("td").addClass("selected");
		});
		
		$(".basketCellRight").hover(function() {
			$(".selected").removeClass("selected");
			$(this).parent().children("td").addClass("selected");
		});


		$(".partClickCell").click(function() {
			window.location=c8urls.main+"find/fiche/"+$(this).parent().attr("id");
		});

		$(".ficheClickCell").click(function() {
			window.location=c8urls.main+"find/part/"+$(this).parent().attr("id");
		});
		
		fi=$("#ficheImage img");
		fi.load(function() {
			imageZoom(fi);
		});
		if (fi.length>0) {
			if (fi[0].complete || fi[0].readyState === 4) {
				imageZoom(fi);
			}
		}
		
		$(".selectableComponent").hover(function() {
			$(".selected").removeClass("selected");
			$(this).addClass("selected");
		});
		
		initUnitType();
		initUnitYear();
	});

