
// Initialize variables
var containerWidth;
var containerHeight;
var x_orig;
var y_orig;
var nameid; // used if we are showing a prev. generated name
var nameforid; // used if we are showing a prev. generated name
var imgArray = new Array;


/*
 * initPage() called after preloader completes
 */
function initPage() {
	// get div container dimensions
	containerWidth = $("#mightyname").width();	
	containerHeight = $("#mightyname").height();
	x_orig = _x(0, containerWidth);
	y_orig = _y(0, containerHeight);
	
	animationGo();
	
	/* Decide what action to take */
	// Check Querystring to see if we show shared page
	// shared url will look something like http://www.makememighty.ca/?n=1612
	nameid = getParameterByName('n');
	if (nameid) {
		$.ajax({
			type: 'GET',
			url:"getname2.php",
			data: {n: nameid},
			dataType: 'json',
			timeout: 5000,
			error: 
				function() {
					// on error just take them to homepage (i.e. name/gender form)
					showMakeMeMightyBox();
				},
			success:
				function(data) {
					nameforid = data;
					if (nameforid=='') {
						// error or invalid id
						showMakeMeMightyBox();
					} else {
						showName(nameforid);
					}
				}
		});
		
		
	} else {
		showMakeMeMightyBox();
	}
}


function replaceInitialFonts() {
	Cufon.replace('#mightyname-label', { fontFamily: 'Campanile' }); //13px
	Cufon.replace('#genders label', { fontFamily: 'Mrs Eaves Small Caps' }); //22px
}

/* Background "Crest Creation" animation */
function animationGo() {
	// Array of images

	imgArray = ['http://mighty.cachefly.net/makememighty/img/Basilisk.png',
					'http://mighty.cachefly.net/makememighty/img/Narwhal.png',
					'http://mighty.cachefly.net/makememighty/img/Centaur.png',
					'http://mighty.cachefly.net/makememighty/img/Griffin.png',
					'http://mighty.cachefly.net/makememighty/img/harpy.png',
					'http://mighty.cachefly.net/makememighty/img/lamia.png',
					'http://mighty.cachefly.net/makememighty/img/mantygre.png',
					'http://mighty.cachefly.net/makememighty/img/musimon.png',
					'http://mighty.cachefly.net/makememighty/img/phoenix.png',
					'http://mighty.cachefly.net/makememighty/img/seabishop.png',
					'http://mighty.cachefly.net/makememighty/img/seahorse.png',
					'http://mighty.cachefly.net/makememighty/img/seamonk.png',
					'http://mighty.cachefly.net/makememighty/img/sphinx.png',
					'http://mighty.cachefly.net/makememighty/img/Unicorn.png',
					'http://mighty.cachefly.net/makememighty/img/Wyvern.png'
					];

	addImage(randomImagePath(), -50, 375);
	addImage(randomImagePath(), 0, 300);
	addImage(randomImagePath(), 30, 200);
	addImage(randomImagePath(), 30, 100);
	addImage(randomImagePath(), 40, 0);
	addImage(randomImagePath(), 30, -100);
	addImage(randomImagePath(), -30, -115);


	addImage(randomImagePath(), -50, 375);
	addImage(randomImagePath(), 0, 300);
	addImage(randomImagePath(), 30, 200);
	addImage(randomImagePath(), 30, 100);
	addImage(randomImagePath(), 40, 0);
	addImage(randomImagePath(), 30, -100);
	addImage(randomImagePath(), -30, -115);
}

/* Add an image and it's flipped counterpart to background (i.e. add to crest) */
function addImage(path, x, y) {
	var img = new Image(), img1id = 0, img2id = 0;
	img.src = path;
	img.onload = function() {
		// Generate random image ID's
		img1id = Math.floor(Math.random()*1000000);
		img2id = Math.floor(Math.random()*1000000);
		$("#mightyname").append('<img src="'+path+'" id="'+img1id+'" class="pic" />');
		$("#"+img1id).css({
			'left'  : _x(x, containerWidth), 
			'top' : _y(y, containerHeight),
			'width' : img.width, 
			'height' : img.height
		});
		// set pre-animation image state
		$("#"+img1id).css({
			width : 0,
			height : 0,
			'left'  : _x(0, containerWidth),
			'top' : _y(0, containerHeight)
		});
		// animate!
		$("#"+img1id).animate({
			width : img.width,
			height : img.height,
			left  : _x(x, containerWidth), 
			top : _y(y, containerHeight)
		}, Math.floor(Math.random()*1500+300), 'swing');
		// add mirror image ///////////////////////////////////////////////////////////////////////////
		//$("#mightyname").append('<img src="flipimg.php?img='+path+'" id="'+img2id+'" class="pic" />');
		var flippath = path.replace('img/', 'img/flip_');
		$("#mightyname").append('<img src="'+flippath+'" id="'+img2id+'" class="pic" />');
		$("#"+img2id).css({
			'left'  : _x(x*-1, containerWidth)-img.width, 
			'top' : _y(y, containerHeight),
			/*'backgroundImage'  : 'url('+path+')', */
			'width' : img.width, 
			'height' : img.height
		});
		// set pre-animation image state
		$("#"+img2id).css({
			width : 0,
			height : 0,
			'left'  : _x(0, containerWidth),
			'top' : _y(0, containerHeight)
		});
		// animate!
		$("#"+img2id).animate({
			width : img.width,
			height : img.height,
			left  : _x(x*-1, containerWidth)-img.width, 
			top : _y(y, containerHeight)
		}, Math.floor(Math.random()*1500+300), 'swing');
	};
}

/* Animate/fade in the initial form box (i.e. enter your name, gender) */
function showMakeMeMightyBox() {
		// set pre-animation image state
		$("#mmmbox").css({
			opacity : 1,
			display : 'block'
		});
		// animate!
		$("#mmmbox").animate({
			opacity : 1
		}, 1000, 'swing', function () {
			$("#content").html($("#makememighty-form").html()).attr("style", "visibility:visible;").css("opacity", 0).animate({opacity: 1}, 300);
			replaceInitialFonts(); // cufon
		});
}



/************************************
 * Returns random image path.
 *  - removes it from array so that
 *    images are not repeated
 ************************************/
function randomImagePath() {
	numImages = imgArray.length;
	r = Math.floor(Math.random()*numImages);
	imgPath = imgArray[r];
	// remove img from array so it's not repeated
	imgArray.splice(r, 1);
	return imgPath;
}



function replaceMightyNameFonts() {
	Cufon.replace('.title', { fontFamily: 'Campanile' });
	Cufon.replace('#replay', { fontFamily: 'Campanile' });
	Cufon.replace('#again', { fontFamily: 'Campanile' });
	Cufon.replace('#proclaim', { fontFamily: 'Campanile' });
	Cufon.replace('#adjective', { fontFamily: 'Mrs Eaves Italic' }); //24px
	Cufon.replace('#eponym', { fontFamily: 'Mrs Eaves Petite Caps' }); //20px
	Cufon.replace('#epithet', { fontFamily: 'Mrs Eaves Petite Caps' }); //20px
}

function interstitialAnimationGo() {
	imgArray = ['http://mighty.cachefly.net/makememighty/img/Basilisk.png', 'http://mighty.cachefly.net/makememighty/img/Centaur.png', 'http://mighty.cachefly.net/makememighty/img/Griffin.png', 'http://mighty.cachefly.net/makememighty/img/harpy.png', 'http://mighty.cachefly.net/makememighty/img/lamia.png', 'http://mighty.cachefly.net/makememighty/img/mantygre.png', 'http://mighty.cachefly.net/makememighty/img/musimon.png', 'http://mighty.cachefly.net/makememighty/img/phoenix.png', 'http://mighty.cachefly.net/makememighty/img/seabishop.png', 'http://mighty.cachefly.net/makememighty/img/seahorse.png', 'http://mighty.cachefly.net/makememighty/img/seamonk.png', 'http://mighty.cachefly.net/makememighty/img/sphinx.png', 'http://mighty.cachefly.net/makememighty/img/Unicorn.png', 'http://mighty.cachefly.net/makememighty/img/Wyvern.png', 'http://mighty.cachefly.net/makememighty/img/Narwhal.png'];
	imgToAnimate = new Array(
						[randomImagePath(),  -150,  275],
						[randomImagePath(),    20,    0],
						[randomImagePath(),   -20,  -40],
						[randomImagePath(),  -220,  100],
						[randomImagePath(),    10,  -30],
						[randomImagePath(),  -100,    0],
						[randomImagePath(),   -30,  115]				
					);
	nextAnimation(imgToAnimate);
}

function nextAnimation(imgToAnimate) {
	if (imgToAnimate.length == 0) return; // no more images to animate
	
	var img = new Image(), imgid = 0;
	var cur = imgToAnimate.pop();
	img.src = path = cur[0];
	x 		= cur[1];
	y 		= cur[2];
	
	img.onload = function() {
		imgid = Math.floor(Math.random()*1000000);
		$("#mightyname").append('<img src="'+path+'" id="'+imgid+'" class="pic" />');
		$("#"+imgid).css({
			'left'  : _x(x, containerWidth), 
			'top' : _y(y, containerHeight),
			'width' : img.width,
			'height' : img.height
		});
		// set pre-animation image state
		$("#"+imgid).css({
			width : 0,
			height : 0,
			'left'  : x_orig,
			'top' : y_orig
		});
		// animate!
		$("#"+imgid).animate({
			width : img.width,
			height : img.height,
			left  : _x(x, containerWidth), 
			top : _y(y, containerHeight)
		}, Math.floor(3000/7), 'swing', function () {
			$(this).animate({ //animate back
				width : 0,
				height : 0,
				left  : x_orig,
				top : y_orig
			}, Math.floor(3000/7), 'swing');
			
			nextAnimation(imgToAnimate); //next
		});
	}
}


function implodePics() {
	$("img.pic").each(function () {
		$(this).animate({
			width : 0,
			height : 0,
			left  : _x(0, containerWidth),
			top : _y(0, containerHeight)
		}, Math.floor(Math.random()*1500+300), 'swing', function () {$(this).remove();});
	});
}

function showName(namejson) {
	var mmmbox = $("#mmmbox");

	mmmbox.find("#content").remove();
	mmmbox.html("<p id='nameofmight'> </p>");
	if (namejson && namejson != '') { // When they're on a shared page
		var title1a = namejson.title1a,
			title1b = namejson.title1b,
			adj 	= namejson.adj,
			epithet = namejson.epithet;
		$("#mmmbox").show();
		
		$("#nameofmight").html('<div id="first" class="title">' + title1a + '</div><div id="main" class="title">' + Url.decode(title1b) + '</div><div id="adjective">' + adj + '</div><div id="epithet">' + epithet + '</div>');
		formatNameOfMight();
		$("#action").html('<a id="makeyourown" href="#">Make Me Mighty</a>').animate({top:"140px"}, "slow", "swing");
	} else { // When they're on a new name page
		var dataDiv = mmmbox.get(0),
			title1a = jQuery.data(dataDiv, "title1a"),
			title1b = jQuery.data(dataDiv, "title1b"),
			adj = jQuery.data(dataDiv, "adj"),
			epithet = jQuery.data(dataDiv, "epithet"),
			crc32 = jQuery.data(dataDiv, "crc32");
		$("#nameofmight").html('<div id="first" class="title">' + title1a + '</div><div id="main" class="title">' + title1b + '</div><div id="adjective">' + adj + '</div><div id="epithet">' + epithet + '</div><div id="make-actions"><a href="#" id="again">Again!</a><a href="#" id="replay">Returneth</a><a href="#share-box" id="proclaim">Proclaim</a></div>');
		$("#share-box").html('<div class="url">http://makememighty.ca/?n=' + crc32 + '</div><div class="share-options"><div class="fb"><a href="#">Share on Facebook</a></div><div class="twitter"><a target="tweetMighty" href="http://twitter.com/home?status=My+name+has+been+made+of+Might%21+What+will+thy+name+become%3F+http%3A%2F%2Fmakememighty.ca%2F%3Fn%3D' + crc32 + '+%23makememighty">Share on Twitter</a></div><div class="clipboard"><a href="#">Copy to Clipboard</a></div><div class="zazzle"><a target="buyZazzle" href="http://www.zazzle.ca/api/create/at-238384749230705396?rf=238384749230705396&ax=Linkover&pd=240398752410123154&fwd=DesignTool&h=Exo-Planetary%20Puppetmaster%2C%20The%20Weaver%20of%20Cosmic%20Strings&i=http%3A%2F%2Fmighty.cachefly.net%2Fmakememighty%2Fimg%2FBasilisk.png&n=Emperor Chrisrix&e=The%20Invincible">Buy it on Zazzle</a></div></div>');
		$("#share-box .zazzle a").attr("href", populateZazzleLink(title1a + " " + title1b, adj, epithet));
		$("#proclaim").fancybox({callbackOnShow: setupCopyToClipboard, hideOnContentClick: false, frameHeight: 170, overlayOpacity: 0.5, overlayColor: "#000"});
		formatNameOfMight();
	}
}

function formatNameOfMight() {
	var mightyname = $("#nameofmight"),
		mightynameWidth = mightyname.width(),
		mightynameHeight = mightyname.height();

	if (mightynameHeight > 240) {
		$(".title", mightyname).css("fontSize", "37px");
	}
	
	if ($("#main.title").text().length > 14) {
		$("#main.title").css("fontSize", "24px");
	}
	replaceMightyNameFonts();
	mightyname.fadeIn("slow");
}

function createName() {
	$("#interstitial").fadeOut("fast", function () {showName();animationGo();});
}

function setupCopyToClipboard() {
    ZeroClipboard.setMoviePath( 'http://makememighty.ca/flash/ZeroClipboard.swf' );
	var clip = new ZeroClipboard.Client();
	clip.setText($("#fancy_content .url").text());
	clip.setHandCursor(true);
	clip.glue($("#fancy_content .clipboard").get(0));
    clip.addEventListener('complete',function(){
        $("#fancy_content .url").css("backgroundColor", "#fff25f").animate({
            backgroundColor: "white"
        }, 1000);
		try {
			pageTracker._trackPageview('/share/copyurl');
		} catch(err) {}
    });
	try {
		pageTracker._trackPageview('/proclaim');
	} catch(err) {}
}

function populateZazzleLink(name, epithet, honorific) {
	var prolog = "http://www.zazzle.ca/api/create/at-238384749230705396?rf=238384749230705396&ax=Linkover&pd=240404597723242922&fwd=DesignTool",
		images = ['http://mighty.cachefly.net/makememighty/img/Shield_01.png', 'http://mighty.cachefly.net/makememighty/img/Shield_02.png', 'http://mighty.cachefly.net/makememighty/img/Shield_03.png'],
		randNum = Math.floor(Math.random()*images.length);

	return prolog + "&line1=" + Url.encode(name) + "&line2=" + Url.encode(epithet) + "&line3=" + Url.encode(honorific) + "&i=" + Url.encode(images[randNum]);
}


/*********************************
 *        EVENT HANDLERS         *
 *********************************/

// Name/Gender Form Submit ("Transmogrify")
$("#startmake").live("click", doSubmitTransmogrifyForm); /* button click */
$("#mmmbox form").live("submit", doSubmitTransmogrifyForm); /* submit via 'return' key */

/* callback for above event handlers*/
function doSubmitTransmogrifyForm() {
	var mmmbox = $("#mmmbox").get(0),
		name = $("#mightyname-input").val() || "",
		gender = ($(".mightygender:checked").length === 0) ? "" : $(".mightygender:checked").get(0).value;

	$.getJSON("createname2.php", {"in": Url.encode(name), "gender": Url.encode(gender)}, function (data) {
		jQuery.data(mmmbox, "name", name);
		jQuery.data(mmmbox, "gender", gender);
		jQuery.data(mmmbox, "title1a", Url.decode(data.title1a));
		jQuery.data(mmmbox, "title1b", Url.decode(data.title1b));
		jQuery.data(mmmbox, "adj", Url.decode(data.adj));
		jQuery.data(mmmbox, "epithet", Url.decode(data.epithet));
		jQuery.data(mmmbox, "crc32", Url.decode(data.crc32));
		$("#mmmbox").find("#content").remove();
		$("#mmmbox").html("<div id='content'><p id='interstitial'>" + Url.decode(data.interstitial) + "</p></div>");
		Cufon.replace('#interstitial', { fontFamily: 'Campanile' });
		$("#interstitial").fadeIn("slow");
		implodePics();
		interstitialAnimationGo();
		setTimeout(createName, 3000);
	});
	try {
		pageTracker._trackPageview('/transmogrify');
	} catch(err) {}
	return false;
}

/* callback for replay event handlers */
function doReplay() {
	var mmmbox = $("#mmmbox");
	
	$("#action").animate({top:"244px"}, "slow", "swing", function () {
		$("#action a").remove();
	});
	implodePics();
	mmmbox.find("#nameofmight").fadeOut(1500, function () {
		$(this).remove();
		mmmbox.html("<div id='content'> </div>");
		$("#content").attr("style", "visibility:hidden;");
		$("#mightyname").children('img').remove();
		animationGo();
		showMakeMeMightyBox();
	});
}

function doAgain() {
	var mmmbox = $("#mmmbox"),
		dataDiv = mmmbox.get(0),
		name = jQuery.data(dataDiv, "name"),
		gender = jQuery.data(dataDiv, "gender");

	$("#action").animate({top:"244px"}, "slow", "swing", function () {
		$("#action a").remove();
	});
	implodePics();
	mmmbox.find("#nameofmight").fadeOut(1200, function () {
		$(this).remove();
		$("#mightyname").children('img').remove();
		$.getJSON("createname2.php", {"in": Url.encode(name), "gender": Url.encode(gender)}, function (data) {
			jQuery.data(dataDiv, "title1a", Url.decode(data.title1a));
			jQuery.data(dataDiv, "title1b", Url.decode(data.title1b));
			jQuery.data(dataDiv, "adj", Url.decode(data.adj));
			jQuery.data(dataDiv, "epithet", Url.decode(data.epithet));
			jQuery.data(dataDiv, "crc32", Url.decode(data.crc32));
			mmmbox.html("<div id='content'><p id='interstitial'>" + data.interstitial + "</p></div>");
			Cufon.replace('#interstitial', { fontFamily: 'Campanile' });
			$("#interstitial").fadeIn("slow");
			interstitialAnimationGo();
			setTimeout(createName, 3000);
		});
	});
}

$("#fancy_content .fb a").live("click", function () {
	/* BASIC SHARING: */
	var u = $("#fancy_content .url").text();
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u),'sharer','toolbar=0,status=0,width=626,height=436');
	
	
	/* Trying out sharing via FB Connect */
/*	var api_key = '137d20314fbaf225ad9912cb9013c821',
		channel_path = 'xd_receiver.html';
	FB.init(api_key, channel_path);

	
	FB.streamPublish();
*/
	try {
		pageTracker._trackPageview('/share/facebook');
	} catch(err) {}
	return false;
});

$("#fancy_content .twitter a").live("click", function () {
	try {
		pageTracker._trackPageview('/share/twitter');
	} catch(err) {}
	return true;
});

$("#fancy_content .zazzle a").live("click", function () {
	try {
		pageTracker._trackPageview('/zazzle');
	} catch(err) {}
	return true;	
});

$("#replay").live("click", function () {
	doReplay();
	try {
		pageTracker._trackPageview('/returneth');
	} catch(err) {}
	return false;
});

$("#makeyourown").live("click", function() {
	doReplay();
	try {
		pageTracker._trackPageview('/makememighty');
	} catch(err) {}
	return false;
});

$("#again").live("click", function() {
	doAgain();
	try {
		pageTracker._trackPageview('/again');
	} catch(err) {}
	return false;
});

