/**
 * @author Kyle Phillips * JavaScript functionality for 2007
 *         workofkylephillips.com
 */
 var is_iPhone = false;
 var contentOpen = false;
 var thumbsInOverState = new Array();
 var thumbsInOverStateContent = new Array();
 var isRevealing = false;
 
 var swfs = {};
 
 function isIPhone() {
  	var agent=navigator.userAgent.toLowerCase();
	is_iPhone = ((agent.indexOf('iphone')!=-1));
 }
 
 function revealInfo(event,target,id, project,description) {
 	if(isMouseLeaveOrEnter(event,target)){
 		turnOffOthersInOverState();
 		thumbsInOverState.push($(target).id);
 		thumbsInOverStateContent.push($(target).innerHTML);
 		// dimensions = $(target).getDimensions();
 		// Event.observe(target, 'click', revealProject);
 		$(target).innerHTML = "<div rel=\"/?id="+id+"\" class=\"innerthumbhover\"  onmousedown=\"SWFAddress.setValue('/?id="+id+"'); this.blur(); return false;\"><div rel=\"/?id="+id+"\" onmousedown=\"SWFAddress.setValue('/?id="+id+"'); this.blur(); return false;\" class=\"projlink\"><div class=\"projTitle\" onmousedown=\"SWFAddress.setValue('/?id="+id+"'); this.blur(); return false;\">"+project+"</div><div class=\"pad\" onmousedown=\"SWFAddress.setValue('/?id="+id+"'); this.blur(); return false;\">"+description+"</div></div></div>";
 		// $(target).height = dimensions.height;
 	}
 }
 function turnOffOthersInOverState() {
 	if(thumbsInOverState.length !=0)
 	{
 		for(var i=0;i<thumbsInOverState.length;i++) {
 			$(thumbsInOverState[i]).innerHTML = thumbsInOverStateContent[i];
 			thumbsInOverState.shift();
 			thumbsInOverStateContent.shift();
 		}
 	}
 }
 function returnImg(event,target, imgsrc){
 	if(isMouseLeaveOrEnter(event,target)){
 		$(target).innerHTML = "<img src=\""+imgsrc+"\" alt=\"Portfolio Graphic\">";
 	}
 }
function revealProject(id) {
	//location.href="#"+id;
	// $('project').hide();
	
	/*
	 * if(contentOpen==true) { //Effect.Move('project',{ x: 0, y: 0, mode:
	 * 'absolute', duration: 1}); //Effect.BlindUp('project',{duration: 0.5});
	 * //$('project').hide(); $('loading').show(); queryProjects(id);
	 * //setTimeout(queryProjects,1000,id); } else {
	 */
		// $('loading').show();
		// setTimeout(queryProjects,1000,id);
		queryProjects(id);
		// queryProjects(id);
	// }
	setTimeout(showMeAllThumbs,1000);

 	
}
function showMeThisTag(tag) {
	isRevealing = true;
	for(var i=0;i<ids.length;i++)
	{
		isAMatch = tryToMatch(ids[i],tag);
		if(!isAMatch) {
			$('th'+ids[i]).addClassName('hideThumb');
			// $('th'+ids[i]).innerHTML = "";
		}
		else $('th'+ids[i]).removeClassName('hideThumb');

	}
}
function revealProjectsOfThisTag(tag) {
	$('loading').show();
	var url='includes/ajaxContentRequest.php'
	var ajaxSubmitter = new Ajax.Request(
	url,
	{
		method: 'post',
		parameters: {action: "tag", tag: tag},
		onComplete: loadContentResponse
		
	});
}
function tryToMatch(id,tag){
	for(var j=0;j<tag.length;j++)
		{
			if(id == tag[j]) { 
				return true;
			}
		}
	return false;
}
/*
 * Currently showMeAllThumbs() is called after the topics are rolled off
 * to avoid flicker, call a different function that loads each that isn't 
 * turned back off by the next rollover
 */
function showMeAllThumbs() {
	if(!isRevealing) {
		for(var i=0;i<thumbs.length;i++) {
			$('th'+ids[i]).removeClassName('hideThumb');
		// $('th'+ids[i]).innerHTML = "<img src=\""+thumbs[i]+"\"
		// width=\""+thwidths[i]+"\" height=\"106\" alt=\"Portfolio Graphic\">";
		}
	}
}

function queryProjects(id) {
	var url='includes/ajaxContentRequest.php?'+id;
	var ajaxSubmitter = new Ajax.Request(
	url,
	{
		method: 'get',
		parameters: {action: "project"},
		onComplete: loadContentResponse
		
	});
}

function sendEmail(username,usermail,usercomments) {
	if(usercomments.length < 2) alert("Please enter a comment before submitting");
	else {
	var url='includes/snowMailPHP.php'
	var ajaxSubmitter = new Ajax.Request(
	url,
	{
		method: 'post',
		parameters: {FirstName: username, Email: usermail, ToComments: usercomments},
		onComplete: loadEmailResponse
		
	});
	}
}
function loadEmailResponse(originalrequest) {
	$('emailform').innerHTML = "<strong>Thank you for your feedback, your message has been sent.</strong>";
}

function goHomeButton() {
	return "<a rel=\"/\" style=\"float:right;cursor:pointer;\" href=\"/\" onmousedown=\"contentOpen=false;SWFAddress.setValue(this.rel); this.blur(); return false;\"><img src=\"images/x.gif\"></a> ";
}

function loadContentResponse(originalrequest) {
	$('project').addClassName('divFilled');
	
	swfs = {};
	
	var addCloser = goHomeButton();
	var addScroller = "<br/><img style=\"padding-top:5px;float:right;cursor:pointer;\"src=\"images/scrolldownicon.gif\" onmousedown=\"scrollToElement('thumbs',0);\"> ";
	var response = eval('(' + originalrequest.responseText + ')');
	var newHTML="";
	
	//set the document title
	document.title = getPageTitle(response.title);
	
	for(var i=0;i<response.content.length;i++) {
		if(i>0) newHTML +="<div class=\"alt\">\n";
		else newHTML +="<div>\n";
		var currentContent = response.content[i];
		if(currentContent.vimeo || currentContent.flash || currentContent.quicktime) 
		{
			if(is_iPhone)
			{
				newHTML += parseQTEmbed(currentContent.quicktime.file,currentContent.quicktime.width,currentContent.quicktime.height);
			}
			else
			{
				var swf;
				if(currentContent.vimeo)
				{
					swf = getVimeoSWFObject(i,currentContent.vimeo);
				}
				else if(currentContent.flash)
				{
					swf = getJWPlayerSWFObject(i, currentContent.flash);
				}
					
					/*newHTML += "<div style=\"width: "+swf.width+"px;height:"+swf.height+"px;cursor: pointer;background-image: url('"+swf.image+"');\" onclick=\"embedSWF('"+swf.divId+"');\" ><div style=\"display:block;position:relative;left:"+((swf.width*0.5)-25)+"px;top:"+((swf.height*0.5)-25)+"px;\" id=\""+swf.divId+"\"><a href=\"javascript:void();\"><img src=\"flvs/play_symbol.gif\" width=\"50\" height=\"50\"/></a></div>";
					newHTML += "</div>";*/
					
					swfs[swf.divId] = swf;
					newHTML += "<div id=\""+swf.divId+"\" style=\"width:"+swf.width+";height:"+swf.height+";\"></div>";
					
			}
		}
		if(currentContent.images) 
		{
			for(var j=0;j<currentContent.images.length;j++) 
			{
				newHTML += parseImage(currentContent.images[j].file,currentContent.images[j].width,currentContent.images[j].height);
			}
		}
		newHTML += "<h2>"+currentContent.header;
		if(currentContent.url)
		{
			newHTML += "<br/><a href=\""+currentContent.url+"\" target=\"_blank\" />"+currentContent.url+"</a> </h2>";
		}
		else
		{
			newHTML +="</h2>";
		}
		newHTML +="<div class=\"description\"><p>\n"+currentContent.description+"\n</p>\n</div>\n</div>";

	}
	
	
	
	
	
	$('project').innerHTML = addCloser + addScroller + newHTML;
	showProject();
	contentOpen = true;
	
	/*for(var s=0;s<swfs.length;s++)
	{
		var cSwf = swfs[s];
		swfobject.embedSWF(cSwf.swfLocation,cSwf.divId, cSwf.width,cSwf.height, "9.0.0", "expressInstall.swf", cSwf.flashvars, cSwf.params, cSwf.attributes);
	}*/
	
	setTimeout(scrollToElement,100,"project",{offset: -30});
	
	for(var prop in swfs)
	{
		embedSWF(swfs[prop].divId);
	}
}



function scrollToElement(element,options) {
	new Effect.ScrollTo(element,options);
}

function showProject() {
	$('project').show();
	$('loading').hide();
}

// This function is credited to http://dynamic-tools.net/toolbox/isMouseLeaveOrEnter/
function isMouseLeaveOrEnter(e, handler)
{		
	var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
	while (reltg && reltg != handler) reltg = reltg.parentNode;
	return (reltg != handler);
}


// Function that gives you the screen x and screen y, even after the user has scrolled
var scrOfX = 0, scrOfY = 0;
function getScrollXY() {
	if( typeof( window.pageYOffset ) == 'number' ) {
	//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}

// Fixes the IE background-image hover bug
try {
    document.execCommand( "BackgroundImageCache", false, true );
} catch( e ) { };

//get a SWFObject Object
function getJWPlayerSWFObject(i, flash)
{
	var swf = {};
	swf.swfLocation = "flvs/player.swf";
	swf.width = flash.width;
	swf.height = flash.height;
	swf.file = flash.file;
	swf.image = flash.image;
	swf.divId = "flashContent"+i;
					
	swf.flashvars = {	
									
		width: swf.width, 
		height: swf.height,
		controlbar: "over",
		id: "player"+i,
		backcolor: "000000", 
		frontcolor: "ffffff", 
		lightcolor: "ffffff",
		screencolor: "000000", 
		file: swf.file, 
		image:  swf.image
	};
				
	swf.params = {allowfullscreen: "true", allowscriptaccess: "always"};
	swf.attributes = {};
	swf.attributes.id = "swf"+i;
					
	return swf;
}



//parse a vimeo video
function getVimeoSWFObject(i,vimeo)
{
	var swf = {};
	swf.swfLocation = 'http://vimeo.com/moogaloop.swf?clip_id='+vimeo.id+'&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00ADEF&amp;fullscreen=1';//&amp;autoplay=1';
	swf.width = vimeo.width;
	swf.height = vimeo.height;
	swf.image = vimeo.image;
	swf.divId = "vimeo"+i;
	swf.flashvars = {};
	swf.params = {allowfullscreen: "true", allowscriptaccess: "always"};
	swf.attributes = {};
	swf.attributes.id = "swf"+i;
	
	return swf;
	
/*
	return '<object width="'+vimeo.width+'" height="'+vimeo.height+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='+vimeo.id+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00ADEF&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id='+vimeo.id+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00ADEF&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+vimeo.width+'" height="'+vimeo.height+'"></embed></object>';
	*/
}

//embed a swf using SWFObject
function embedSWF(id)
{
	if(!swfs[id])return;
	var cSwf = swfs[id];
	swfs[id] = null;
	//alert(cSwf.swfLocation);
	swfobject.embedSWF(cSwf.swfLocation,cSwf.divId, cSwf.width,cSwf.height, "9.0.0", "expressInstall.swf", cSwf.flashvars, cSwf.params, cSwf.attributes);
	var player = document.getElementById(cSwf.attributes.id);
	//alert(player);
	//setTimeout(beginPlay,500,player);
	
}

//tell JW Flash video player to begin
function beginPlay(player)
{
	player.sendEvent("PLAY","true");
}
	

function parseFlashEmbed(fileName,image,width,height) {
	
	
	//return '<object width="'+width+'" height="'+height+'"><param name="movie" value="http://workofkylephillips.com/flvs/mediaplayer.swf"><param name="flashvars" value="height='+height+'&width='+width+'&file='+fileName+'&image='+image+'&id=player&backcolor=0xcccccc&frontcolor=0x000000&lightcolor=0xFFFFFF&screencolor=0x000000&displayheight='+height+'"><param name="allowScriptAccess" value="always"><param name="allowfullscreen" value="true"><embed src="flvs/mediaplayer.swf" width="'+width+'" height="'+height+'" allowscriptaccess="always" allowfullscreen="true" flashvars="height='+height+'&width='+width+'&file='+fileName+'&image='+image+'&id=player&backcolor=0xcccccc&frontcolor=0x000000&lightcolor=0xFFFFFF&screencolor=0x000000&displayheight='+height+'"></embed></object>';
}
function parseQTEmbed(fileName,width,height) {
	return '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="'+height+'" width="'+width+'"><param name="src" value="'+fileName+'"><param name="autoplay" value="true"><param name="controller" value="false"><embed height="'+height+'" width="'+width+'" src="'+fileName+'" pluginspage="http://www.apple.com/quicktime/download/" type="video/quicktime" controller="false" autoplay="true"></object>';
	
}

function parseImage(fileName,width,height) {
	return "<img class='padimg' src='"+fileName+"' width='"+width+"' height='"+height+"' alt='Portfolio Graphic' />";
}

function placeEmailLink() {
	document.write('<a hre'+'f="ma'+'ilto'+':'+'%6B%79%6C%65%40%77%6F%72%6B%6F%66%6B%79%6C%65%70%68%69%6C%6C%69%70%73%2E%63%6F%6D">&#107;&#121;&#108;&#101;&#64;&#119;&#111;&#114;&#107;&#111;&#102;&#107;&#121;&#108;&#101;&#112;&#104;&#105;&#108;&#108;&#105;&#112;&#115;&#46;&#99;&#111;&#109;<\/a>');
}


//SOME SWFAddress Functionality
SWFAddress.addEventListener(SWFAddressEvent.CHANGE,handleChange);
function handleChange(event) {
	var index, rel, links = document.getElementsByTagName('a');
	for (var i = 0, l; link = links[i]; i++) {
		index = link.rel.indexOf('?');
		rel = (index > -1) ? link.rel.substr(0, index) : link.rel;
		link.className = rel == event.path ? 'selected' : '';
	}
	var parameters="";
	for (var p in event.parameters) {
		parameters += p + '=' + event.parameters[p];
	}
			
	if(parameters != "") {
		revealProject(parameters);
	}
	else {
		if(event.path !="/")revealProjectsOfThisTag(event.path);
		else $('project').hide();
	}
	
}
function formatTitle(title) {
   	return "The Work of Kyle Phillips - " + (title != "/" ? " / " + toTitleCase(title.substr(1,title.length - 2).replace(/\//g, " / ")) : "");
}
function toTitleCase(str) {
   	return str.substr(0, 1).toUpperCase() + str.substr(1).toLowerCase();
}

function getPageTitle(title) {
	return "The Work of Kyle Phillips - "+ title;
}

function getHomeTitle() {
	return "The Work of Kyle Phillips - Interaction Designer / Developer";
}

function resetPageTitle() {
	docment.title = getHomeTitle();
}

/**
 * LABS JSON FEED
 */
function getLabsPost(limit) {
	//$('loading').show();
	if(limit <= 0) limit = 1;
	var url='includes/labsfeed.php';
	var ajaxSubmitter = new Ajax.Request(
	url,
	{
		method: 'post',
		parameters: {request: "posts", limit: limit},
		onComplete: loadLabPostResponse
		
	});
}

function getLabsLinks(limit) {
	//$('loading').show();
	if(limit <= 0)limit = 1;
	var url='includes/labsfeed.php';
	var ajaxSubmitter = new Ajax.Request(
	url,
	{
		method: 'post',
		parameters: {request: "links", limit: limit},
		onComplete: loadLabsLinksResponse
		
	});
}

function loadLabsLinksResponse(originalrequest)
{

	var root = eval('(' + originalrequest.responseText + ')');
	var response = root.response;
	var post = "posts: ";
	
	for(var i=0;i<response.length;i++)
	{
		post += "<a href="+response[i].entry.uri+">"+response[i].entry.title+"</a>";
		if(i < response.length-1)post +=" / ";
	}
	
	$('labslinks').innerHTML = post;
}
function loadLabPostResponse(originalrequest)
{

	//alert("reponse: "+originalRequest);
	var root = eval('(' + originalrequest.responseText + ')');
	var response = root.response;
	var uri = response[0].entry.uri;
	var title = response[0].entry.title;
	var date = response[0].entry.date;
	var post_content = response[0].entry.post_content;
	
	var post = "<h2><a href=\""+uri+"\">"+title+"</a></h2>\n<h4>"+date+"</h4>\n"+"<p>"+post_content+"</p>";
	
	$('labspost').innerHTML = post;
	
	// prompt(response);
}




/**
 * XML REQUEST PARSING
 */
 
function getXMLResponse(responseText)
{
	var ajaxResponse = Try.these(
		function() { return new DOMParser().parseFromString(responseText, 'text/xml'); },
		function() { var xmldom = new ActiveXObject('Microsoft.XMLDOM'); xmldom.loadXML(responseText); return xmldom; }
	);
	return ajaxResponse;
}



function getLabsLinksXML(limit) {
	//$('loading').show();
	if(limit <= 0) limit = 1;
	var url='includes/labsfeed.php';
	var ajaxSubmitter = new Ajax.Request(
	url,
	{
		method: 'post',
		parameters: {request: "links", format: "xml", limit: limit},
		onComplete: labsLinksXMLResponse
		
	});
}

function labsLinksXMLResponse(originalrequest)
{
	var ajaxResponse = getXMLResponse(originalrequest.responseText);
	var response = ajaxResponse.getElementsByTagName('response')[0];
	var entries = response.getElementsByTagName("entry");

	var post = "posts: ";
	
	for(var i=0;i<entries.length;i++)
	{
		var uri = entries[i].getAttribute("uri");
		var title = entries[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
		post += "<a href=\""+uri+"\" title=\""+title+"\">"+title+"</a>";
		if(i < entries.length-1)post +=" / ";
		
	}
	
	$('labslinks').innerHTML = post;

	// alert(getXmlNodeValue(doc.response));

}


function getLabsPostsXML(limit) {
	//$('loading').show();
	if(limit <= 0) limit = 1;
	var url='includes/labsfeed.php';
	var ajaxSubmitter = new Ajax.Request(
	url,
	{
		method: 'post',
		parameters: {request: "posts", format: "xml", limit: limit},
		onComplete: labsPostsXMLResponse
		
	});
}

function labsPostsXMLResponse(originalrequest)
{
	var ajaxResponse = getXMLResponse(originalrequest.responseText);
	var response = ajaxResponse.getElementsByTagName('response')[0];
	var entries = response.getElementsByTagName("entry");
	
	var post="";
	
	for(var i=0;i<entries.length;i++)
	{
		var uri = entries[i].getAttribute("uri");
		var date = entries[i].getAttribute("date");
		var title = entries[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
		var post_content = entries[i].getElementsByTagName("content")[0].childNodes[0].nodeValue;
		
		post += "<h2><a href=\""+uri+"\" title=\"permanent link to: "+title+"\">"+title+"</a></h2>\n<h4>"+date+"</h4>\n<p>"+post_content+"</p>";
		
	}
	$('labspost').innerHTML = post;
}