var idleTime    = 7000;
var timeOut     = '';
var lastIdlePop = '';
var debug = false;
var movieWatcher = '';

var bubbleText = $H({
	amoeba: ["Click me!", "One cell wonder!"],
	fish: ["Blub blub", "Freak of nature!", "Missing link!", "Mmmm, worm!"],
	trex: ["Grrr, I'm extinct", "I'm hungry", "Duck, Meteor!"],
	caveman: ["Grog want wext", "Bam bam"]
})

function loadTimeline() {

	soundManager.createSound({
		id: 'intro',
		url: '/sounds/intro.mp3'
	});
	soundManager.createSound({
		id: 'wap',
		url: '/sounds/wap.mp3'
	});
	soundManager.createSound({
		id: 'wexting',
		url: '/sounds/wexting.mp3'
	});

	if (!debug) {	
		soundManager.play('intro');
		window.setTimeout("fadeIntroTitle()", 6000);
	} else {
		fadeIntroTitle();
	}



	['amoeba', 'fish', 'trex', 'caveman'].each(	function(i) {

		  soundManager.createSound({
			id: i,
			url: '/sounds/'+i+'.mp3'
		  });
		  soundManager.createSound({
			id: i+'_clickme',
			url: '/sounds/'+i+'_clickme.mp3'
		  });


		$(i+'_image').onclick = function() {
			addHit('click on '+i+' image');
			showTimelineDetail(i)
		}
		$(i+'_bubble').onclick = function() {
			addHit('click on '+i+' bubble');
			showTimelineDetail(i)
		}

		$(i+'_image').onmouseover = function() {
			if (!anyDetailsVisible()) {
				soundManager.play('wap');
				agitate(i);
			}
		}
	});
	$('wexting_image').onmouseover= function() {
		if (!anyDetailsVisible()) {
			img = $$('#wexting_image > img')[0];
			img.src = "/images/crowd_hl.png";
			soundManager.play('wexting');
		}
	}
	$('wexting_image').onmouseout= function() {
		img = $$('#wexting_image > img')[0];
		img.src = "/images/crowd.png";
	}
	$('wexting_image').onclick= function() {
		addHit('click on wexting image');
		goWexting();
	}

}

function anyDetailsVisible() {
	count = 0;
	$$('.detailFloater').each(	function(e) {
		if (e.visible()) {
			count++;
		}
	})
	return count > 0;
}


function idleAnimationInit() {
    Event.observe(document.body, 'mousemove', resetIdle, true);
    setIdle();
}

function onIdleFunction(){

	if (!anyDetailsVisible()) {
		//Effect.Pulsate('navRemindButton')
		var images = new Array('amoeba', 'fish', 'trex', 'caveman');
//		randomnumber = Math.round(Math.random()*4);
		randomnumber = Math.floor(Math.random()*4);
		while (randomnumber == lastIdlePop) {
			randomnumber = Math.floor(Math.random()*4);
		}
		lastIdlePop = randomnumber;
	
		soundManager.play(images[randomnumber] + '_clickme');
	//	Sound.play('/sounds/' + images[randomnumber] + '_clickme.wav');
		agitate(images[randomnumber])
	}
}

function resetIdle() {
    window.clearTimeout( timeOut );
    setIdle();
}

function stopIdle() {
    window.clearTimeout( timeOut );
}


function setIdle(){

    timeOut = window.setInterval( "onIdleFunction()", idleTime );
}


function fadeIntroTitle() {
	if (!debug) {
		Effect.Fade('introTitle');
	}
	Effect.Appear('interactiveTimeline', {queue:'end', afterFinish:function() {

		['e1', 'e2', 'o', 'v1', 'l', 'v2', 'period'].each(	function(i) {
			if (!debug) {
				Effect.Grow(i, {duration:.3, queue:'end'});
			} else {
				$(i).show();
			}
		})
		if (!debug) {
			idleAnimationInit();
		}


	}});

}



function showTimelineDetail(id) {
	if (!$(id+'_detail').visible()) {
		soundManager.play(id);
	
		dim_i = $(id+'_image').getDimensions()
		dim_n = $(id+'_name').getDimensions()

		setW = $(id+'_detail').getAttribute('w')
		setH = $(id+'_detail').getAttribute('h')

		dim = $('overlay').getDimensions()
		w = dim.width
		h = 225
		$(id+'_detail').clonePosition('overlay', {
			offsetLeft:0,
			offsetTop:150,
			setLeft:true,
			setTop:true,
			setWidth:false,
			setHeight:false
		});



		$(id+'_detail').setStyle({
			width:w+'px',
			height:h+'px'
		})

		$$('#'+id+'_detail > .detail_wrapper')[0].setStyle({
			left:(w/2)-350+'px'
		});

		Effect.Appear(id+'_detail', {
			duration: .2,
			afterSetup: function () {
				if (!$('overlay').visible()) {
					Effect.Appear('overlay', {duration:.2, to:.7})
				}

			},
			afterFinish: function() {
				$(id+'_detail').onclick = function() {
//					hideTimelineDetail(id);
				}

			}
		});
	}
}

function hideTimelineDetail(id) {
	Effect.Fade(id+'_detail', {duration:.2, afterSetup:function() {
		$('overlay').hide();
	}});
}

function agitate(i) {
	if (!$(i+'_bubble').visible()) {

		iBubbles = bubbleText.get(i);
		var randomnumber = Math.floor(Math.random()*iBubbles.length)
		$(i+'_bubble').update(iBubbles[randomnumber])

		$(i+'_bubble').clonePosition(i+'_image', {
			setLeft:true,
			setTop:true,
			offsetLeft:parseInt($(i+'_bubble').getAttribute('offsetleft')),
			offsetTop:parseInt($(i+'_bubble').getAttribute('offsettop')),
			setWidth:false,
			setHeight:false
		});

		$(i+'_bubble').show();
		window.setTimeout("$('"+i+"_bubble').fade();", 2000);
	}
	Effect.Shake(i+'_image', {distance:7})

}


function goWexting() {
	stopIdle();
	Effect.Appear('overlay', {duration:.2, to:.85})
	var dimensions = $('wexting_detail').getDimensions();
	w = dimensions.width
	h = dimensions.height

	$('wexting_detail').clonePosition('trex_image', {
		offsetLeft:-(w/3),
		offsetTop:-(h/4),
		setLeft:true,
		setTop:true,
		setWidth:false,
		setHeight:false
	});


	$('wexting_detail').setStyle({
		width:w+'px',
		height:h+'px'
	})
	$('wexting_detail').show();

/*
	if (!($('learnMore').visible())) {
		movieWatcher = window.setInterval( "isWextingOver()", 500 );
	}
*/

}

function isWextingOver() {
	obj = movieObj();
	rate = obj.GetRate()
	time = obj.GetTime()
	duration = obj.GetDuration()
	if (time > 235101) {
//	if ((rate == 0) && (time == duration)) {
		$('learnMore').appear();
		window.clearInterval(movieWatcher)
	}
}

function movieObj() {
	if (Prototype.Browser.Gecko) {
		return $$('#wextingMovie > embed')[0]
	} else {
		return $('wextingMovie')
	}
}

function restartMovie() {
	obj = movieObj();
	obj.Stop();
	obj.Rewind();
	obj.Play();
/*
	$('wextingMovie').SetTime(0);
	$('wextingMovie').SetRate(1);
*/
}

function CheckSmartFormSubmit(returnObj, divID) {
	canSubmit = true;
	badFields = new Object();
	if (divID != null) {
		str = '#' + divID + ' [required]';
	} else {
		str = '[required]';	
	}
	$$(str).each(	function(e) {
		if (($(e).value == "") || ($F(e) == $(e).getAttribute('defaultText'))) {
			badFields[e.id] = "bad";
			canSubmit = false;
			$(e).addClassName('badField');
			
		} else {
			$(e).removeClassName('badField');
		}
	})
	if (returnObj != null) {
		return {canSubmit:canSubmit, badFields:badFields};
	} else {
		return canSubmit;
	
	}

}


function addHit(what, doAfter) {
	new Ajax.Request('/tracker.php', {
		method: 'post',
		parameters: {
			hit:what
		},
		onSuccess: function(transport) {
			if (doAfter != null) {
				doAfter();
			}
		},
		onFailure: function(transport) {
//			alert("An error occurred.")
		}
	})

}

function showContactForm() {
  	new Ajax.Updater('contactForm', '/contact.php', {
		parameters: {
			
		},
		evalScripts:true,
		onLoaded: function() {
//			$('yacVirginIntro3').fadehide;
		},
		onInteractive: function() {
		},
		onComplete: function() {
			$('contactForm').appear({duration:.2});
			$('overlay').show();

		},
		onFailure:function(transport) {
			alert('An error occurred: '+transport.responseText);
		}
	});
			
}

function hideContactForm() {
//	$('yacVirginIntro3').className = 'yacVirginIntro3Start yacVirginIntro';
//	$('yacVirginIntro3').innerHTML = $('yacVirginIntro3').oldContent;
	$('contactForm').hide();
	$('overlay').hide();
}

function sendContactForm() {
	var re = /\D/g;
	$('customerPhone').value = $F('customerPhone').replace(re,'');
	

	if (CheckSmartFormSubmit()) {
		if ($F('customerPhone').match(/^\d{10}$/)) {
			addHit('submitted wexting contact form');
			new Ajax.Request('/contact.php', {
				method: 'post',
				parameters: {
					action			:'sendForm',
					customerName		:$F('customerName'),
					customerEmail		:$F('customerEmail'),
					customerPhone		:$F('customerPhone'),
					customerMessage	:$F('customerMessage')
				},
				onLoaded: function() {
				},
				onSuccess: function(transport) {
					alert('Your message was sent!');
					$('contactForm').fade({duration:.2});
					$('overlay').hide();
				},
				onFailure: function(transport) {
					alert("An error occurred.")
				}
			});
		} else {
			alert('Please be sure to enter a 10 digit phone number where you can be reached.');
		
		}
	} else {
		alert('Please be sure to enter your name, e-mail address, and a phone number where you can be reached.');
	}

}

