var isSafari = (navigator.userAgent.indexOf("Safari") > 0) ? true : false ;
var isIE = (navigator.userAgent.indexOf("MSIE") > 0) ? true : false ;
var scrollAnim;
var scrollAmount = 197;
var clickHoldInterval;
var content = Array();
var selectedCategoryTitle = "All";
var categoryElements = Array();
var lastSection;
var isInOverviewMode = false;
var highestZIndex = 0;
var dateLastScroll = 0;

function init() {
	Shadowbox.init();

	var contentDiv = document.getElementById("content");
	contentDiv.scrollTop = 0;

	var contentBackground = document.getElementById("contentBackground");
	var content = document.getElementById("content");
	var upBackground = document.getElementById("upBackground");
	var downBackground = document.getElementById("downBackground");
	var up = document.getElementById("up");
	var down = document.getElementById("down");
	contentBackground.style.display = "block";
	content.style.display = "block";
	upBackground.style.display = "block";
	downBackground.style.display = "block";
	up.style.display = "block";
	down.style.display = "block";
	upBackground.style.zIndex = 100;
	downBackground.style.zIndex = 101;
	up.style.zIndex = 102;
	down.style.zIndex = 103;

	var up = document.getElementById("up");
	var down = document.getElementById("down");
	up.style.display = "block";
	down.style.display = "block";
	YAHOO.util.Event.addListener(up, "mousedown", function () { 
		clickHoldInterval = window.setInterval( function () { scrollByAmount(-scrollAmount); }, 300);
		scrollByAmount(-scrollAmount);
	});
	YAHOO.util.Event.addListener(up, "mouseup", function () { window.clearInterval(clickHoldInterval); });
	YAHOO.util.Event.addListener(up, "mouseout", function () { window.clearInterval(clickHoldInterval); });
	YAHOO.util.Event.addListener(down, "mousedown", function () { 
		clickHoldInterval = window.setInterval( function () { scrollByAmount(scrollAmount); }, 300);
		scrollByAmount(scrollAmount);
	});
	YAHOO.util.Event.addListener(down, "mouseup", function () { window.clearInterval(clickHoldInterval); });
	YAHOO.util.Event.addListener(down, "mouseout", function () { window.clearInterval(clickHoldInterval); });
	YAHOO.util.Event.addListener(document, "mousewheel", handleScroll);
	YAHOO.util.Event.addListener(document, "DOMMouseScroll", handleScroll);
	if (isSafari) {
		YAHOO.util.Event.addListener(document, "keydown", handleKeyPress);
	} else {
		YAHOO.util.Event.addListener(document, "keypress", handleKeyPress);
	}
	YAHOO.util.Event.addListener(window, "resize", function () { layoutSubviews(); });

	// add onclick events for the header nav
	YAHOO.util.Event.addListener("About_Us", "click", toggleStripe, "About Us");
	YAHOO.util.Event.addListener("Clients", "click", toggleStripe, "Clients");
	YAHOO.util.Event.addListener("Contact", "click", toggleStripe, "Contact");

	var email = document.getElementById("email");
	email.innerHTML = "<a href=\"mailto:info"+"@"+"missioncm.com\"><span class=\"email\">info"+"(at)"+"missioncm.com</span></a>";

	updateCategoryList();
	layoutSubviews();
	animateEntrances();
	processHash();

	// ie6 png fix
	if (typeof supersleight != "undefined") {
		supersleight.run();
	}
}

function processHash() {
	var hash = window.location.hash.replace("#", "");
	if (hash == "About_Us" || hash == "Clients" || hash == "Contact") {
		YAHOO.lang.later(1000, this, "toggleStripe", hash.replace("_", " "), false);
	} else if (hash == "Overview") {
		YAHOO.lang.later(1000, this, "toggleOverview", null, false);
	} else if (hash != "") {
		selectedCategoryTitle = hash;
	}
	setSelectedCategoryTitle(selectedCategoryTitle);
}

function animateEntrances() {
	// logo
	var anim = new YAHOO.util.Anim("logo", {
		left: { to: 0 } 
	}, 0.5, YAHOO.util.Easing.easeOut);
	window.setTimeout(function () { anim.animate(); }, 500);

	// about nav items
	var anim2 = new YAHOO.util.Anim("About_Us", {
		opacity: { to: 1 } 
	}, 0.5, YAHOO.util.Easing.easeOut);
	window.setTimeout(function () { anim2.animate(); }, 500);

	var anim3 = new YAHOO.util.Anim("divider1", {
		opacity: { to: 1 } 
	}, 0.5, YAHOO.util.Easing.easeOut);
	window.setTimeout(function () { anim3.animate(); }, 600);

	var anim4 = new YAHOO.util.Anim("Clients", {
		opacity: { to: 1 } 
	}, 0.5, YAHOO.util.Easing.easeOut);
	window.setTimeout(function () { anim4.animate(); }, 700);

	var anim5 = new YAHOO.util.Anim("divider2", {
		opacity: { to: 1 } 
	}, 0.5, YAHOO.util.Easing.easeOut);
	window.setTimeout(function () { anim5.animate(); }, 800);

	var anim6 = new YAHOO.util.Anim("Contact", {
		opacity: { to: 1 } 
	}, 0.5, YAHOO.util.Easing.easeOut);
	window.setTimeout(function () { anim6.animate(); }, 900);

	// content nav
	var anim7 = new YAHOO.util.Anim("contentNav", {
		bottom: { to: 0 } 
	}, 0.5, YAHOO.util.Easing.easeOut);
	window.setTimeout(function () { anim7.animate(); }, 500);
	
}

function updateCategoryList() {
	var contentNav = document.getElementById("contentNav");
	contentNav.innerHTML = "";
	categoryElements = Array();

	// add the All element
	var element = document.createElement("a");
	element.href = "#All";
	element.title = "All";
	element.innerHTML = "All";
	element.onclick = function () { setSelectedCategoryTitle("All"); };
	categoryElements.push(element);
	contentNav.appendChild(element);

	for (var i = 0; i < content.length; i++) {
		if (!inArrayWithKey(content[i].category, categoryElements, "innerHTML")) {
			var element = document.createElement("a");
			element.href = "#"+ content[i].category.replace(" ", "_");
			element.title = content[i].category;
			element.innerHTML = content[i].category;
			element.onclick = function () { setSelectedCategoryTitle(this.innerHTML); };
			categoryElements.push(element);
			contentNav.appendChild(element);
		}
	}

	// add the overview element
	var element = document.createElement("a");
	element.href = "#Overview";
	element.title = "Overview";
	element.innerHTML = "Overview &nbsp;<span class='icon_grid'>&nbsp;&nbsp;&nbsp;</span>";
	element.onclick = function () { toggleOverview(); };
	categoryElements.push(element);
	contentNav.appendChild(element);
}

function setSelectedCategoryTitle(title) {
	for (var i = 0; i < categoryElements.length; i++) {
		if (categoryElements[i].title == title) {
			categoryElements[i].className = "on";
		} else {
			categoryElements[i].className = "";
		}
	}
	updateListWithCategoryTitle(title);
	selectedCategoryTitle = title;
}

function updateListWithCategoryTitle(c) {
	var list = document.getElementById("list");
	list.innerHTML = "";

	var contentDiv = document.getElementById("content");
	contentDiv.scrollTop = 0;

	var found = 0;
	for (var i = 0; i < content.length; i++) {
		if ((content[i].category == c || c == "All") && content[i].thumbVisible == true) {
			found++;
			var html = "<div class='meta'>";
			html += 	"<div class='title'>"+ content[i].title +"</div>";
			html += 	"<div class='description'>"+ content[i].description +"</div>";
			html += "</div>";
			html += "<img src='"+ content[i].thumbImage +"' />";
			var element = document.createElement("a");
			element.href = content[i].bigImage;
			element.innerHTML = html;
			element.className = "item";
			element.rel = content[i].rel;
			if (content[i].rel.indexOf("shadowbox") >= 0) {
			    Shadowbox.setup(element);
			} else {
				element.onclick = function () { toggleOverlay(this); return false; };
			}
			list.appendChild(element);
			content[i].listThumbElement = element;

			// attach the data object, so we can access it later when opening the overlay
			element.representedObject = content[i];

			// add the flyout animation for the meta data
			element.onmouseover = function () { 
				var meta = this.firstChild;
				meta.style.left = "0px";
				meta.style.display = "block";
				var anim = new YAHOO.util.Anim(meta, {
					left: { from:90, to:290 } 
				}, 0.25, YAHOO.util.Easing.easeOut);
				anim.animate();
			};
			element.onmouseout = function () { 
				var meta = this.firstChild;
				meta.style.left = "0px";
				meta.style.display = "none";
			}

			// animate it in
			element.style.opacity = "0";
			element.style.filter = "alpha(opacity=0)";
			var anim = new YAHOO.util.Anim(element, {
				opacity: { to: 1 } 
			}, 0.5, YAHOO.util.Easing.easeOut);
			YAHOO.lang.later(found * 300, anim, "animate", "", false);
		}
	}
}

function toggleOverlay(sender, second) {
	// the mouseup events will set the first parameter to the event automatically, so get around that
	if (second) {
		sender = second;
	}

	var shade = document.getElementById("shade");
	var overlay = document.getElementById("overlay");
	if (sender) {
		// set the content
		setOverlayContentWithCategory_title_description(sender.representedObject.category, sender.representedObject.title, sender.representedObject.description);
		setBigImageForElement(sender);

		// show it
		if (shade.style.display != "block" && overlay.style.display != "block") {
			if (!isIE) {
				shade.style.opacity = "0";
				overlay.style.opacity = "0";
				var anim = new YAHOO.util.Anim(shade, {opacity:{from: 0, to: 0.8 }}); 
				anim.duration = 0.5;
				anim.animate();
				var anim2 = new YAHOO.util.Anim(overlay, {opacity:{ from: 0, to: 1 }}); 
				anim2.duration = 0.5;
				YAHOO.lang.later(500, anim2, "animate", "", false);
			}
			shade.style.display = "block";
			overlay.style.display = "block";
			layoutSubviews();
		} else {
			layoutSubviews();
		}
	} else {
		overlay.style.display = "none";
		var bigImage = document.getElementById("overlayBigImage");
		bigImage.src = "";
		if (isIE) {
			shade.style.display = "none";
		} else {
			var anim = new YAHOO.util.Anim(shade, {opacity:{ to: 0 }}); 
			anim.duration = 0.3;
			anim.onComplete.subscribe(function () { this.getEl().style.display = "none"; });
			anim.animate();
		}
	}
}

function setOverlayContentWithCategory_title_description(category, title, description) {
	var overlayThumbs = document.getElementById("overlayThumbs");
	overlayThumbs.innerHTML = "";
	for (var i = 0; i < content.length; i++) {
		if (content[i].category == category && content[i].title == title && content[i].description == description) {
			var html = "<img src='"+ content[i].thumbImage +"' />";
			var element = document.createElement("a");
			element.href = content[i].bigImage;
			element.innerHTML = html;
			element.onclick = function () { setBigImageForElement(this); return false; };
			overlayThumbs.appendChild(element);
			content[i].overlayThumbElement = element;
		}
	}
}

function getClassName(obj) {
	if (typeof obj != "object" || obj === null) return false;
	return obj.constructor.toString();
}

function setBigImageForElement(element, second) {
	var bigImage = document.getElementById("overlayBigImage");
	//alert("leng = "+ content.length);
	for (var i = 0; i < content.length; i++) {
		if (content[i].overlayThumbElement == element || content[i].listThumbElement == element || content[i].overviewThumbElement == element) {
			bigImage.src = content[i].bigImage;

			//window.setTimeout(function (u) { bigImage.src = u; }, 100, content[i].bigImage);
			//bigImage.style.width = "600px";
			//window.status = "zz";
			//alert("setting image = "+ bigImage.src);
			//layoutSubviews();
			
			// show/hide and configure the more work buttons
			if (content[i].listThumbElement) {
				var moreWorkPrevious = document.getElementById("moreWorkPrevious");
				if (content[i].listThumbElement.previousSibling && content[i].listThumbElement.previousSibling.rel.indexOf("shadowbox") != false) {
					moreWorkPrevious.style.display = "block";
					YAHOO.util.Event.removeListener(moreWorkPrevious);
					YAHOO.util.Event.addListener(moreWorkPrevious, "mouseup", toggleOverlay, content[i].listThumbElement.previousSibling);
				} else {
					moreWorkPrevious.style.display = "none";
					YAHOO.util.Event.removeListener(moreWorkPrevious);
				}
				var moreWorkNext = document.getElementById("moreWorkNext");
				if (content[i].listThumbElement.nextSibling && content[i].listThumbElement.nextSibling.rel.indexOf("shadowbox") != false) {
					moreWorkNext.style.display = "block";
					YAHOO.util.Event.removeListener(moreWorkNext);
					YAHOO.util.Event.addListener(moreWorkNext, "mouseup", toggleOverlay, content[i].listThumbElement.nextSibling);
				} else {
					moreWorkNext.style.display = "none";
					YAHOO.util.Event.removeListener(moreWorkNext);
				}
			}
			break;
		}
	}
	return false;
}

function handleScroll(e) {
	if (isInOverviewMode == true) {
		return;
	}

	// limit the speed, so trackpads don't fly too fast
	var now = new Date();
	if (now.getTime() - dateLastScroll < 150) {
		return;
	}
	dateLastScroll = now.getTime();

	if (e.wheelDelta) {
		if (e.wheelDelta > 0) {
			scrollByAmount(-scrollAmount);
		} else {
			scrollByAmount(scrollAmount);
		}
	} else {
		if (e.detail > 0) {
			scrollByAmount(scrollAmount);
		} else {
			scrollByAmount(-scrollAmount);
		}
	}
}

function handleKeyPress(e) {
	var code = e.keyCode;
	if (code == 38) { // up arrow
		scrollByAmount(-scrollAmount);
	} else if(code == 33) { // page up
		scrollByAmount(-scrollAmount * 3);
	} else if (code == 40) { // down arrow
		scrollByAmount(scrollAmount);
	} else if (code == 34) { // page down
		scrollByAmount(scrollAmount * 3);
	} else if (code == 27) { // esc
		toggleOverlay();
	}
}

function scrollByAmount(amount) {
	var contentDiv = document.getElementById("content");

	// this is so if the user scrolls fast, the content scrolls faster too
	if (scrollAnim) {
		scrollAnim.stop(true);
	}

	scrollAnim = new YAHOO.util.Scroll(contentDiv, { scroll: { to: [0, contentDiv.scrollTop + amount] } }, 0.5, YAHOO.util.Easing.easeOutStrong);
	scrollAnim.animate();
}

function addContent(category, thumbImage, bigImage, title, description, thumbVisible, rel) {
	var o = Object();
	o.category = category;
	o.thumbImage = thumbImage;
	o.bigImage = bigImage;
	o.title = title;
	o.description = description;
	o.thumbVisible = thumbVisible;
	o.rel = rel;
	content.push(o);
}

function inArrayWithKey(item, arr, key){
	var found = false;
	for (var i = 0; i < arr.length; i++) {
		if (item == eval("arr["+ i +"]."+ key)) {
			found = true;
			break;
		}
	}
	return found;
}

function toggleStripe(e, section) {
	if (!section) {
		section = e;
	}
	var stripe = document.getElementById("stripe");
	if (section && (section != lastSection)) {
		var aboutUs = document.getElementById("content_About_Us");
		var clients = document.getElementById("content_Clients");
		var contact = document.getElementById("content_Contact");
		var thankYou = document.getElementById("content_Thank_You");
		setSectionDisplay(aboutUs, section);
		setSectionDisplay(clients, section);
		setSectionDisplay(contact, section);
		setSectionDisplay(thankYou, section);
		lastSection = section;

		if (stripe.style.display != "block") {
			stripe.style.zIndex = 400;

			// animate it in
			stripe.style.opacity = 0;
			stripe.style.filter = "alpha(opacity=0)";
			var anim = new YAHOO.util.Anim(stripe, {opacity:{from: 0, to: 1 }});
			anim.duration = 0.4;
			anim.animate();
			stripe.style.display = "block";
		}
	} else {
		stripe.style.display = "none";
		lastSection = "";
		window.setTimeout("window.location.hash = '#';", 200);
	}
	return false;
}

function setSectionDisplay(element, section) {
	if (element.id.replace("content_", "").replace("_", " ") == section) {
		element.style.display = "block";
	} else {
		element.style.display = "none";
	}
}

function layoutSubviews() {
	// resize the overlay
	var overlay = document.getElementById("overlay");
	var overlayContainer = document.getElementById("overlayContainer");
	var overlayScalePercent = 1;
	var overlayScalePercentX = getWindowWidth() / 960;
	var overlayScalePercentY = getWindowHeight() / 730;
	if (overlayScalePercentX < overlayScalePercentY) {
		overlayScalePercent = overlayScalePercentX;
	} else {
		overlayScalePercent = overlayScalePercentY;
	}
	if (overlayScalePercent > 1) {
		overlayScalePercent = 1;
		overlay.style.backgroundImage = "url(\"images/overlay_shadow_960x730.png\")";
	} else {
		overlay.style.backgroundImage = "none";
	}
	overlayContainer.style.fontSize = overlayScalePercent +"em";

	// position the overlay
	var overlay = document.getElementById("overlay");
	x = (getWindowWidth() / 2) - (overlay.offsetWidth / 2);
	if (x < -30) {
		x = -30;
	}
	overlay.style.left = x +"px";
	y = (getWindowHeight() / 2) - (overlay.offsetHeight / 2);
	if (y < -30) {
		y = -30;
	}
	overlay.style.top = y +"px";

	// center the overlay thumbnails
	var overlayThumbsContainer = document.getElementById("overlayThumbsContainer");
	var overlayThumbs = document.getElementById("overlayThumbs");
	if (overlayThumbs.firstChild) {
		var w = (overlayThumbs.childNodes.length * 100 * overlayScalePercent) + 6;
		overlayThumbs.style.width = w +"px";
		var x = (overlayThumbsContainer.offsetWidth / 2) - (w / 2);
		overlayThumbs.style.left = x +"px";
	}

	// position the stripe
	var stripe = document.getElementById("stripe");
	if (getWindowHeight() < 678) {
		y = getWindowHeight() - 300;
		if (y < 84) {
			y = 84;
		}
		stripe.style.top = y +"px";

		// position the header
		var header = document.getElementById("header");
		if (header) {
			y = (303 - (678 - getWindowHeight()));
			if (y < 10) {
				y = 10;
			}
			header.style.top = y +"px";
		}
	} else {
		stripe.style.top = "378px";
	}

	// set height of the categories list
	var h = 45 + (23 * categoryElements.length);
	var contentNav = document.getElementById("contentNav");
	contentNav.style.height = h +"px";
}

function getWindowHeight() {
	if (window.self && self.innerHeight) {
		return self.innerHeight;
	}
	if (document.documentElement && document.documentElement.clientHeight) {
		return document.documentElement.clientHeight;
	}
	return 0;
}

function getWindowWidth() {
	if (window.self && self.innerWidth) {
		return self.innerWidth;
	}
	if (document.documentElement && document.documentElement.clientWidth) {
		return document.documentElement.clientWidth;
	}
	return 0;
}

function toggleOverview() {
	var overview = document.getElementById("overview");
	var overviewContent = document.getElementById("overviewContent");
	var shade = document.getElementById("overviewShade");
	overviewContent.innerHTML = "";
	overview.scrollTop = 0;
	if (overview.style.display == "block") {
		isInOverviewMode = false;
		overview.style.display = "none";

		// animate the shade out
		var anim = new YAHOO.util.Anim(shade, {opacity:{ to: 0 }}); 
		anim.duration = 0.3;
		anim.onComplete.subscribe(function () { this.getEl().style.display = "none"; });
		anim.animate();

		window.setTimeout("window.location.hash = '#';", 200);
	} else {
		isInOverviewMode = true;

		shade.style.zIndex = 300;
		overview.style.zIndex = 301;
		overviewContent.style.zIndex = 302;

		shade.style.opacity = "0";
		shade.style.filter = "alpha(opacity=0)";
		shade.style.display = "block";
		var anim = new YAHOO.util.Anim(shade, {opacity:{from: 0, to: 1 }}); 
		anim.duration = 0.5;
		anim.animate();

		overview.style.display = "block";
		var found = 0;
		for (var i = 0; i < content.length; i++) {
			if (content[i].thumbVisible == true) {
				found++;
				var html = "<div class='meta'>";
				html += 	"<div class='title'>"+ content[i].title +"</div>";
				html += 	"<div class='description'>"+ content[i].description +"</div>";
				html += "</div>";
				html += "<img src='"+ content[i].thumbImage +"' />";
				var element = document.createElement("a");
				element.className = "item";
				element.href = content[i].bigImage;
				element.innerHTML = html;
				element.rel = content[i].rel;
				if (content[i].rel.indexOf("shadowbox") >= 0) {
				    Shadowbox.setup(element);
				} else {
					element.onclick = function () {
						this.style.zIndex = "";
						toggleOverlay(this); return false;
					};
				}
				overviewContent.appendChild(element);
				content[i].overviewThumbElement = element;

				// attach the data object, so we can access it later when opening the overlay
				element.representedObject = content[i];

				// animate it in
				element.style.opacity = "0";
				element.style.filter = "alpha(opacity=0)";
				var anim = new YAHOO.util.Anim(element, {
					opacity: { to: 1 } 
				}, 0.5, YAHOO.util.Easing.easeOut);
				YAHOO.lang.later(found * 200, anim, "animate", "", false);
			}
		}
	}
}

function submitContact(form) {
	YAHOO.util.Connect.setForm(form);
	if (form.elements["name"].value == "" || form.elements["email"].value == "" || form.elements["message"].value == "") {
		alert("Please complete all fields.");
		return;
	}
	YAHOO.util.Connect.asyncRequest("POST", "contact.php", { 
		success: function(o) {
			if (o.responseText == "0") {
				var contact = document.getElementById("content_Contact");
				setSectionDisplay(contact, "");
				setSectionDisplay(document.getElementById("content_Thank_You"), "Thank You");
				document.getElementById("contactForm").reset();
			} else {
				alert(o.responseText);
			}
			var sendButton = document.getElementById("sendButton");
			sendButton.value = "Send";
		}, 
		failure: function(o) {
			alert(o.responseText);
			var sendButton = document.getElementById("sendButton");
			sendButton.value = "Send";
		}
	});
	var sendButton = document.getElementById("sendButton");
	sendButton.value = "Sending...";
	return false;
}
