var shown = false;

$(document).ready(function() {
	init();
	$('#sliders').css({'visibility':'hidden'});

	var distance = 10;
	var time = 250;
	var hideDelay = 1000;

	var hideDelayTimer = null;

	// tracker
	var beingShown = false;
	// var shown = false;
	
	// show loading wheel
	$('#grimace_wrapper').before($('<div id="grimace_wheel"></div>'));
	
	if (navigator.appName == "Microsoft Internet Explorer") {
		var trigger = $('#grimace_wrapper', this);
		var popup = $('#sliders', this);
		$([trigger.get(0), popup.get(0)]).mouseover(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			if (beingShown || shown) {
				return;
			} else {
				beingShown = true;
				popup.css({'visibility':'visible'});
				beingShown = false;
				shown = true;
			}
		}).mouseout(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				popup.css({'visibility':'hidden'});
				shown = false;
				}, hideDelay);
			});

	} else {
		var trigger = $('#grimace_wrapper', this);
		var popup = $('#sliders', this).css('opacity', 0);
		$([trigger.get(0), popup.get(0)]).mouseover(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			if (beingShown || shown) {
				return;
			} else {
				beingShown = true;
				popup.css({
					visibility: 'visible'
				}).animate({
					left: '+=' + distance + 'px',
					opacity: 1
				}, time, 'swing', function() {
					beingShown = false;
					shown = true;
				});
			}
		}).mouseout(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				popup.animate({
					left: '-=' + distance + 'px',
					opacity: 0
				}, time, 'swing', function () {
					shown = false;
					popup.css('visibility', 'hidden');
				});
				}, hideDelay);
			});
		
	}
	
})

function pickRandomEmotion() {
	var emotions = new Array();
	emotions[0] = "anger";
	emotions[1] = "fear";
	emotions[2] = "disgust";
	emotions[3] = "joy";
	emotions[4] = "sadness";
	emotions[5] = "surprise";
	
	var values = new Object();
	values.anger = 0;
	values.fear = 0;
	values.disgust = 0;
	values.joy = 0;
	values.sadness = 0;
	values.surprise = 0;
	for (var i = 0; i < 2; i++) {
		values[emotions[Math.floor(Math.random()*emotions.length)]] = Math.random();
	};
	grimace.addEventListener('emotionSet', 'onEmotionSet');
	grimace.setEmotion(values, 0.3);
}

// portions courtesy of http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html
var grimace;

var jsReady = false;
function isReady() {
	return jsReady;
}


function init() {
	jsReady = true;
	grimace = getMovie('Grimace');
	
	sliders.init();
	
	initListeners();
	
	loadFacedata();
}
function getMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	}
	else {
		return document[movieName];
	}
}

function initListeners() {
	try {
		if (!grimace.isReady()) {
			throw new Error('Grimace not ready');
		}
		grimace.addEventListener('loadComplete', 'onLoadComplete');
		grimace.addEventListener('captureComplete', 'onCaptureComplete');
	}
	catch (e) {
		// Retry later if Grimace was not ready yet.
		setTimeout(initListeners, 300);
	}
}

function loadFacedata() {
	var ok;
	try {
		if (!grimace.isReady()) {
			throw new Error('Grimace not ready');
		}
		// Paths are relative to location of Grimace.swf
		grimace.loadFacedata([
			'grimace/head.xml',
			'grimace/features.xml',
			'grimace/wrinkles.xml',
			'grimace/emotions.xml',
			'grimace/overlays.xml'
		]);
	}
	catch (e) {
		// Retry later if Grimace was not ready yet.
		setTimeout(loadFacedata, 300);
	}
}

function onLoadComplete() {
	$('#grimace_wheel').remove();
	$('#grimace_wrapper').css('opacity', 0).fadeTo('slow', 1);
	
	grimace.setPosition(0,0);
	grimace.setScaleMode("showAll");
	grimace.draw();
	
	setInterval(function() {
		if (!shown) {
			pickRandomEmotion();
		}
	}, 4000);
}

// emotion sliders based on jquery ui
var sliders = {
	resolution: 100,
	
	values: {
		joy:      0,
		surprise: 0,
		fear:     0,
		sadness:  0,
		disgust:  0,
		anger:    0
	},
	
	init: function() {
		var scope = this;
		
		$('#joy').slider({
			max: this.resolution,
			slide: function(e,ui){
				scope.slide('joy');
			}
		});
		$("#surprise").slider({
			max: this.resolution,
			slide: function(e,ui){
				scope.slide('surprise');
			}
		});
		$("#fear").slider({
			max: this.resolution,
			slide: function(e,ui){
				scope.slide('fear');
			}
		});
		$("#sadness").slider({
			max: this.resolution,
			slide: function(e,ui){
				scope.slide('sadness');
			}
		});
		$("#disgust").slider({
			max: this.resolution,
			slide: function(e,ui){
				scope.slide('disgust');
			}
		});
		$("#anger").slider({
			max: this.resolution,
			slide: function(e,ui){
				scope.slide('anger');
			}
		});
	},
	
	notify: true,
	
	slide: function(emotion) {
		if (!this.notify) {
			return;
		}
		
		var value = $('#'+emotion).slider('value');
		value /= this.resolution;

		this.values[emotion] = value;
		
		
		this.update();
		
		// Immediately set new emotion
		grimace.setEmotion(this.values, 0);
	},
	
	update: function() {
		// Deactivate unused sliders when two emotions are already active.
		// Mixtures of more than 3 emotions are usually unintelligible.
		
		var active = 0;
		for (var i in this.values) {
			if (this.values[i] > 0) {
				active++;
			}
		}
		
		if (active >= 2) {
			for (var i in this.values) {
				if (this.values[i] == 0) {
					$('#'+i).slider('disable');
				}
				else {
					$('#'+i).slider('enable');
				}
			}
		}
		else {
			for (var i in this.values) {
				$('#'+i).slider('enable');
			}
		}
	}
}

function onEmotionSet() {
	grimace.removeEventListener('emotionSet', 'onEmotionSet');
	
	sliders.notify = false;
	
	var emotions = grimace.getEmotion()
	for (var i in sliders.values) {
		if (emotions[i]) {
			sliders.values[i] = emotions[i];
		}
		else {
			sliders.values[i] = 0;
		}
	}
	for (var i in sliders.values) {
		$('#'+i).slider('moveTo', 100 * sliders.values[i]);
	}
	
	sliders.update();
	sliders.notify = true;
}

