var blinkL, blinkR ,tmt, analogo;
var blinker =0;
var mousedown=false;
var movecan=false,movecan_offset,train_offset;
var dmt = 9.4;
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var dragaround, dragaroundOn=true;

var train,$screen,margin,margins=new Object;
	$(document).ready(function(){
		$screen = $("#screen");
		analogo = $('#analogo img');
		//body height
		if($(window).height()>900)$('body').css('height',$(window).height()+'px');
		//drag around
		dragaround = $('#drag-around');
		dragaround.css('left',(analogo.position().left+560)+'px');
		dragaroundBlink();
		//page engine
		train = $('#train');
		margin = ($screen.width()-707)/2;
		train.css('width',($('.page').length*(707+margin)+100)+'px');
		$('.page').each(function(){
			$(this).css('margin-left',margin+'px');
			margins["#"+$(this).attr('id')]=$(this).offset().left-margin;
			//attach dregger func
			$(this).hover(function(){
				document.body.style.cursor = 'default';
				movecan=false;
			},function(){
				document.body.style.cursor = 'url(img/hand_cursor.png),url(img/hand_cursor.cur),auto';
				movecan=true;
			});
		})
			//preload hand cursors
			$.preLoadImages("img/hand_cursor.png","img/hand_cursor2.png","img/hand_cursor2.cur","img/hand_cursor.cur");
		
		$('a[href^=#]').click(function(e){
			e.preventDefault();
			train.animate({marginLeft:(-(margins[$(this).attr('href')]))+'px'},1000,function(){
				if($(window).scrollTop()>500)$(document).scrollTo(0,500,{axis:'y'});
			})
			
		})
		
		//form
		$('#formsubmitter').click(function(e){
			e.preventDefault();
			$('#contact form').submit();
		})
		$("#contact form").resetForm().submit(function(e){
			e.preventDefault();
			if(reg.test($(this).find('input[name=email]').attr('value'))){
				$(this).ajaxForm({success:SentMail});
			}
		}).find('input,textarea').each(function(){
			if(this.tagName.toLowerCase()=="input")
				$(this).wrap('<div class="input"/>');
			else $(this).wrap('<div class="textarea"/>');
			$(this).focus(function(){
				//console.log($(this).parent());
				$(this).css({opacity:0.8, backgroundColor:'#2673a5', color:'white'}).parent().css('webkit-box-shadow','0 0 10px #fff').css('moz-box-shadow','0 0 10px #fff').css('box-shadow','0 0 10px #fff');
			}).focusout(function(){
				$(this).css({opacity:1, backgroundColor:'#9fd5f8', color:'black'}).parent().css('webkit-box-shadow','none').css('moz-box-shadow','none').css('box-shadow','none');
			});
		});
		
		
		
		//blink
		blinkR = new Image();
		blinkR.src = 'http://analogo.net/img/analogo_blinkR.png';
		blinkR.onLoad = RLoaded();
		//eye it up
		initCanvas();
		$(canvas).css('left',analogo.position().left+'px')
		$('body').each(function(){
			$('a').hover(function(e){
				$(document).bind('mousemove',UpdateEyes);
				UpdateEyes(e);
				mousedown=true;
			},function(e){
				mousedown=false;
				$(document).unbind('mousemove',UpdateEyes)
				eye1.y = 29;
				eye1.x = 60;
				eye2.y = 29;
				eye2.x = 220;
			})
			$(this).mousedown(function(e){
				if(movecan) e.preventDefault();
				$(document).bind('mousemove',UpdateEyes);
				UpdateEyes(e);
				mousedown=true;
				if(movecan){
					if(dragaroundOn){
						dragaroundOn=false;
						dragaround.animate({opacity:0},500,function(){dragaround.remove()});
						
					}
					movecan_offset=e.clientX;
					train_offset=Number(train.css('margin-left').replace('px',''));
					document.body.style.cursor = 'url(img/hand_cursor2.png),url(img/hand_cursor2.cur),auto';
					$(document).bind('mousemove',MoveCanvas);
				}
			})
			$(this).mouseup(function(e){
				mousedown=false;
				$(document).unbind('mousemove',UpdateEyes)
				eye1.y = 29;
				eye1.x = 60;
				eye2.y = 29;
				eye2.x = 220;
				if(movecan){
					document.body.style.cursor = 'url(img/hand_cursor.png),url(img/hand_cursor.cur),auto';
					$(document).unbind('mousemove',MoveCanvas);
					//scrollto nearest page
					if(movecan_offset>e.clientX){
						//get nearest page on the right
						var nearestx=5000,nearest;
						$('.page').each(function(){
							thisleft = $(this).position().left;
							if(thisleft<nearestx&&thisleft>0){
								nearestx=$(this).position().left;
								nearest=$(this);
							}
						})
						if(nearest===undefined){
							//if the no page on the right, scrollto last
							
							train.animate({marginLeft:(-(margins['#contact']))+'px'},350,function(){
								if($(window).scrollTop()>500)$(document).scrollTo(0,500,{axis:'y'});
							})
						} else //in any other case
						train.animate({marginLeft:(-(margins['#'+nearest.attr('id')]))+'px'},function(){
							if($(window).scrollTop()>500)$(document).scrollTo(0,500,{axis:'y'});
						})
					}
					else if(movecan_offset<e.clientX) {
						//get nearest page on the left
						var nearestx=-5000,nearest;
						$('.page').each(function(){
							thisleft = $(this).position().left;
							if(thisleft>nearestx&&thisleft<0){
								nearestx=$(this).position().left;
								nearest=$(this);
							}
						})
						if(nearest===undefined){
							//if the no page on the left, scrollto first
							train.animate({marginLeft:(-(margins['#home']))+'px'},350,function(){
								if($(window).scrollTop()>500)$(document).scrollTo(0,500,{axis:'y'});
							})
						} else //in any other case
						train.animate({marginLeft:(-(margins['#'+nearest.attr('id')]))+'px'},350,function(){
							if($(window).scrollTop()>500)$(document).scrollTo(0,500,{axis:'y'});
						})
					}
				}
			})
		})
	})
	
	//Move Canvas conduct
	function MoveCanvas(e){
		train.css({marginLeft:(train_offset+(e.clientX-movecan_offset))+'px'})
		
	}
	
	
	//handle case window is resized
	$(window).resize(function(){
		$(canvas).css('left',analogo.position().left+'px')
		margin = ($screen.width()-707)/2;
		train.css('width',($('.page').length*(707+margin)+100)+'px');
		$('.page').each(function(){
			$(this).css('margin-left',margin+'px');
			margins["#"+$(this).attr('id')]=$(this).offset().left-margin-train.css("margin-left").replace("px","");
		})
	})
	function RLoaded(){
		tmt = setInterval(BlinkR,15000);
	}
	function BlinkR(){
		analogo.attr('src','http://analogo.net/img/analogo_blinkR.png');
		setTimeout(function(){
			analogo.attr('src','http://analogo.net/img/analogo.png');
			blinker++;
			if(blinker==2)blinker=0;
			else setTimeout(BlinkR,700);
		},700)
	}
	
	function UpdateEyes(e){
		var canx = $(canvas).position().left;
		var cany = $(canvas).position().top;
		var a,b,c,y,x;
		/*
		//This turns detection of first eye separately
		var a = e.clientX-canx-60;
		var b = e.clientY-114;
		var c = Math.sqrt(a*a+b*b);
		var y = (dmt/c)*b;
		var x = Math.sqrt(dmt*dmt-y*y);if(e.clientX<canx+60)x=-x;
		*/
		a = e.clientX-canx-220;
		b = e.clientY-114;
		c = Math.sqrt(a*a+b*b);
		y = (dmt/c)*b; 
		x = Math.sqrt(dmt*dmt-y*y); if(e.clientX<canx+220)x=-x;
		
		eye1.y = 29+y;
		eye1.x = 60+x;
		eye2.y = 29+y;
		eye2.x = 220+x;
	}
	
	var t=0; // time in ms
	var fps = 60; // frames per second
	var timeInterval = 1000 / fps; // in ms
	var canvas = null; // canvas DOM object
	var context = null; // canvas context
	
	var eye1=null,eye2=null;

	function initCanvas() {
		canvas=document.getElementById("myCanvas");
		context=canvas.getContext("2d");
		initStageObjects();
		drawStageObjects();
		setInterval(updateStage,timeInterval);
	}
	
	function Eye(x,y,radius){
		this.x = x;
		this.y = y;
		this.radius = radius;
	}

	function updateStage() {
		// if(mousedown)UpdateEyes();
		t+=timeInterval; 
		clearCanvas();
		updateStageObjects();
		drawStageObjects();	
	}

	function initStageObjects() {
		// do stuff here
		eye1 = new Eye(60,29,8.8);
		eye2 = new Eye(220,29,8.8);
		retina1 = new Eye(60,29,20);
		retina2 = new Eye(220,29,20);
	}

	function drawStageObjects() {
		// draw retinas (to hide original eyes)
		context.beginPath();
		context.arc(retina1.x,retina1.y,retina1.radius,0,2*Math.PI,false);
		context.arc(retina2.x,retina2.y,retina2.radius,0,2*Math.PI,false);
		context.fillStyle="white";
		context.fill();
		// context.endPath();
		//draw the new eyes
		context.beginPath();
		context.arc(eye1.x,eye1.y,eye1.radius,0,2*Math.PI,false);
		context.arc(eye2.x,eye2.y,eye2.radius,0,2*Math.PI,false);
		context.fillStyle="black";
		context.fill();
		
	}

	function updateStageObjects() {
		// do stuff here
	}

	function clearCanvas() {
		context.clearRect(0,0,canvas.width, canvas.height);
		context.beginPath();
	}
	
	function SentMail(){
		console.log('sent');
		$("#formsubmitter").after("<div id='contactsent'>Thanks for contacting us! We will get back to you shortly...</div>").remove();
	}
	function dragaroundBlink(){
		if(dragaroundOn){
		dragaround.animate({opacity:.3},800,function(){
			dragaround.animate({opacity:.7},800,dragaroundBlink);
		});
		}
	}
	
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)
