ziebart = function() {
	var 
		isHome = false,
		maxLoop = 10,			// max home page loops
		maxCLoop = 5,			// max home page car loops
		maxICLoop = 10,		// max internal page loop
		cDuration = 14000,	// cloud animation duration
		carDuration = 1500,	// car animation duration
		carDelay = 500,		// car animation delay
		inc = 1250,				// width of header image
		loop = 0,				// car loop counter
		cLoop = 0,				// cloud loop counter
		ie;						// if ie, *not in use*
		
	return {
		enlargeImage : function(data, e) {
			if (data.originalEvent) {
				e = data;
				data = {};
			}
			data = data || {};
			if (e) {
				e.preventDefault();
			}
		
			if (!$('#loading')) {
				$.append('<div id="loading" />');
			}
		
			if (!data.img) {
				data.img = new Image();
				data.img.src = this.href;
			}else{
				if (typeof this.href != 'undefined') {
					if (data.img.src != this.href) {
						data.img = new Image();
						data.img.src = this.href;
					}
				}
			}
		
			if (!data.parent) {
				data.parent = this.parentNode;
			}
			if (data.img.complete) {
				$('#imgViewer, #loading').remove();
				
				var viewer = document.createElement('div'),
					close = document.createElement('div'),
					img = document.createElement('img');
				
				viewer.id = 'imgViewer';
				close.id = 'close';
				img.src = data.img.src;
				
				$(close).add(viewer).click(function() { $('#imgViewer').remove(); });
				
				// validate position
				var validatePosition = function(pos) {
					var boundary = {
						'top' : $(document).scrollTop(),
						'right' : $(document).scrollLeft()+$(window).width(),
						'bottom' : $(document).scrollTop()+$(window).height(),
						'left' : $(document).scrollLeft()
					};
					pos.right = pos.left + pos.width;
					pos.bottom = pos.top + pos.height;
					
					if (pos.right > boundary.right) {
						pos.left = boundary.right - 20 - pos.width;
					}
					
					if (pos.bottom > boundary.bottom) {
						pos.top = boundary.bottom - 20 - pos.height;
					}
					
					return pos;
				};
				
				var imgPos = $(data.parent).offset();
				imgPos = { 'left' : imgPos.left + $(data.parent).width()/2, 'top' : imgPos.top + $(data.parent).height()/2 };
				imgPos = {
					'left' : imgPos.left - img.width / 2,
					'top' : imgPos.top - img.height / 2,
					'width': img.width,
					'height': img.height
				};
				
				imgPos = validatePosition(imgPos);
				
				$(viewer).css('position','absolute').css('z-index','9999').append(close, img)
					.css('left', imgPos.left < 10 ? 10 : imgPos.left ).css('top', imgPos.top < 10 ? 10 : imgPos.top );
				
				$(document.body).append(viewer);
								
				/*
				
				pX = $D.getX(parent) + (parent.offsetWidth/2);
				pY = $D.getY(parent) + (parent.offsetHeight/2);
				
				imgX = pX-(img.width/2);
				imgY = pY-(img.height/2);
				
				imgR = imgX+img.width;
				imgB = imgY+img.height;
				
				scTop = $(data.parent).scrollTop();
				scBottom = scTop + $(document.body).outerHeight();
				
				scLeft = $(data.parent).scrollLeft();
				scRight = scLeft + $(document.body).outerWidth();
							
				imgX = (imgX<scLeft) ? scLeft+10 : imgX;
				imgY = (imgY<scTop) ? scTop+10 : imgY;			
				imgX = (imgR>scRight) ? scRight-10-img.width : imgX;
				imgY = (imgB>scBottom) ? scBottom-10-img.height : imgY;
				
				imgX = (imgX<10) ? 10 : imgX;
				imgY = (imgY<10) ? 10 : imgY;
				
							
				$D.setXY(viewer,[imgX,imgY]);
				
				$(data.parent).append(viewer);
				return;
				return; */
			}else{
				var test = function(e, obj) {
					ziebart.enlargeImage(data, null);					
				}
				imgID = window.setTimeout(test,500);
			}
			
		},
	
		init : function() {
		
			$('#billingSame').click(function() {
				if (this.checked === true) {
					
					$.each($(this).parent().parent().find('input, select'), function(key, billing) {
						var shipID = billing.id.replace('billing','shipping');
						var input = document.getElementById(shipID);
						if (input) {
							if (input.tagName.toLowerCase() == 'input') {
								input.value = billing.value;
							}else{
								input.selectedIndex = billing.selectedIndex;
							}
						}
					});
				}
			});
			
			$('.enlargeImage').bind('click', ziebart.enlargeImage, {});
		
			if ($("#form_mailing").length)
				this.vForm('#form_mailing');
			
			$('#f_location').submit( function(e) {
				if($('#zipcode').val().length) {
					e.preventDefault();
					$.getJSON("http://maps.google.com/maps/geo?q="+$('#zipcode').val()+"&key="+gAPI+"&sensor=false&output=json&callback=?", function(data) {
							if(data.Status.code==200) {
								var result = {};
								var lat = data.Placemark[0].Point.coordinates[1];
								var long = data.Placemark[0].Point.coordinates[0];
								window.location = '/locations/?lat='+lat+'&long='+long;
							}else{
								window.location = '/locations/?zip='+$('#zipcode').val();
							
							}
						}
					);
				}
			});
				
			$('#form_coupon').validator({
				errorClass: 'error12384325'
			});
				
			$('#form_contact').validator({
				errorClass: 'error12384325'
			});
			
			// us location toggle
			$("#us_location").click(function(){
				if ($('#form_location').css('display') == 'block') {
					$('#form_location').css('display','none');
				}else{
					$('#form_location').css('display','block');				
				}
			});
			
			// hurrr, product nav & animations
			$('#item li').mouseover(function(){
			
				// hide default item, show hovered one
				$('#pg_item00').css('display','none');
				$('#pg_'+this.id).css('display','block');
				
				// check for attached image!
				if ($('#'+this.id+'img').length) {
				
					// is this a car alarm or remote start (ie needs to flash
					if (this.id == 'item07' || this.id == 'item01') {
						$('#'+this.id+'img').animate ({opacity:"0.75" }, 300 ).animate ({opacity:0 }, 300 );
						if (this.id == 'item07') {
							$('#'+this.id+'img').everyTime ( 500, function (){
								$('#'+this.id).animate ({opacity:"0.75" }, 300 ).animate ({opacity:0 }, 300 );
							});
						}else{
							$('#'+this.id+'img').everyTime ( 500, function (){
								$('#'+this.id).animate ({opacity:"0.75" }, 300 ).animate ({opacity:0 }, 300 );
							},2);
						}
						
					// no flash needed
					}else{
						$('#'+this.id+'img').animate({
								opacity: 0.75
							},500);
					}
				}
				
				checkLength = function(e) {
					length = parseInt(this.attr('maxlength'));
					if (this.value.length > len) {
						this.value = this.value.substr(0, len); 
						return false;
					}
				}
				$('textarea[maxlength]').keyup(checkLength).blur(checkLength);
				
			}).mouseout(function(){
			
				// show default item, hide unhovered one
				$('#pg_item00').css('display','block');			
				$('#pg_'+this.id).css('display','none');
				
				// check for attached image
				if ($('#'+this.id+'img').length) {
				
					// fade out attached image
					if (this.id == 'item07' || this.id == 'item01') {
						$('#'+this.id+'img').stop(true).stopTime().animate({
								opacity: 0
							},500);
					}else{
						$('#'+this.id+'img').animate({
								opacity: 0
							},500);					
					}
				}
				
			});
			
			// cars
			if ($('#heading img').length) {
				isHome = true;
				this.animateCars($('#heading img:first'));
			}
			$('#header').css('backgroundPositionX','0')
			this.header();
		
			// international location image
			$('.images li img[rel]').overlay({
					close: ".close, img"
			});

		},
		animateCars : function(el) {
			if (ie)
				return false;
			el.css('right','-150px' );
			el.css('opacity','0.0' );
			el.addClass('active');
			
			el.animate({
				right: '10',
				opacity: '1'
			}, carDuration, function() {
				if (loop < maxCLoop) {
					$(this).delay(carDelay).animate({
						right: '160',
						opacity: '0'
					}, carDuration, function() {
					
						if ($('#heading img.active ~ img:not(.active)').length) {
							var next = $('#heading img.active ~ img:not(.active):first');
						}else{
							var next = $('#heading img:first');
							loop+=1;
						}
						$(this).removeClass('active');
						ziebart.animateCars(next);
					
					});
				}
			});
		},
		header : function() {
			(isHome==true) ? max=maxLoop : max=maxICLoop;
		
			if (cLoop < max) {
			
		   	var curX = $('#header').css('backgroundPosition');
		   	if (curX.indexOf('px') != -1) {
		   		curX = curX.replace('px','');
		   	}
		   	curX = curX.split(' ');
		   	curX = parseFloat(curX[0]);
		   	
		   	if (curX >= inc) {
		   		var rm = Math.floor(curX/inc);
		   		var newX2 = curX - rm*inc + curX%inc;
		   		$('#header').css('backgroundPosition',newX2+'px 0');
		   		curX = newX2;
		   	}
		   	
		   	var newX = curX + inc;
		   	
				$('#header').animate(
					{backgroundPosition:newX+"px 0"},
					{easing: "linear",
					duration: cDuration,
					complete: ziebart.header}
				);
				cLoop+=1;
			}
		
		},
		vForm : function(theID) {
			$(theID).validator({
				errorClass: 'error12384325'
			}).submit(function(e) {
				var form = $(this);
				// client-side validation OK.
				if (!e.isDefaultPrevented()) {
					var page = this.action;
					
					$.getJSON(page +'?'+ form.serialize()+'&submit=true', function(json) {
					
						// everything is ok. (server returned true)
						if (json.success === true)  {
						
							form.html(json.thankyou);
							if (json.popup) {
							
								var ty = $("<div></div>")
									.html('<img src="/assets/style/images/pg_ty.png" alt="Thank You">')
									.attr('id','form_ty')
									.css('opacity','0');
								
								$('body').append(ty);
								
								ty.animate({
									opacity: 1
								},500, function(){
									ty.delay(2000).fadeOut(2000);
								});
							}
						
						// server-side validation failed. use invalidate() to show errors
						} else {
						
							form.data("validator").invalidate(json);
						}
					});
					
					e.preventDefault();
				}
			});
			
		}
	};
}();

$(document).ready(function() { ziebart.init(); });

