// This is the url we load the twitter feed from
var feedUrl = "http://twitter.com/status/user_timeline/stylmee.json?count=5&callback=populateTimeline";

function populateTimeline(obj) {
	
	var container = $("newsfeedInner");
	container.className = "";
	while(container.hasChildNodes()) { container.removeChild(container.firstChild); }
	
	var div, inner;
	for(var i=0; i<obj.length; i++) {
		div = Builder.node("div");
		inner = Builder.node("div", { className: "tweet" }); 
		inner.innerHTML = createLinks(obj[i]['text']);
		div.appendChild(inner);
		container.appendChild(div);
	}
	
	var feed = $('feed2_inner');
	if(feed) {
		
		feed.className = "";
		while(feed.hasChildNodes()) { feed.removeChild(feed.firstChild); }
		
		for(var i=0; i<obj.length; i++) {
			div = Builder.node("div");
			inner = Builder.node("div", { className: "tweet" }); 
			inner.innerHTML = createLinks(obj[i]['text']);
			div.appendChild(inner);
			feed.appendChild(inner);
		}
	}

	setInterval(nextTweet, 5000);
}

function buildSecondFeed() {
	var feed = $('feed2');
	if(feed) {
		var div = Builder.node("div", { id: 'feed2_inner', className: 'loading' });
		div.appendChild(document.createTextNode('Loading...'));
		feed.appendChild(div);
	}
}

function createLinks(str) {
	var result = str;
	result = result.replace(/([a-z]+:\/\/[^\s\)]+)/gi, '<a href="$1">$1</a>');
	result = result.replace(/(#[^\s]+)/g, '<a href="http://twitter.com/search?q=$1">$1</a>');
	result = result.replace(/@([^\s]+)/g, '<a href="http://twitter.com/$1">@$1</a>');
	return result;
}

function nextTweet() {
	var feed = $("newsfeedInner");
	var tweet = feed.firstChild;
	var height = tweet.clientHeight;
	new Effect.Move(feed, 
		{ x: 0, y: -height, mode: 'relative', duration: 0.3, 
		afterFinish: function() {
			feed.removeChild(tweet);
			feed.appendChild(tweet);
			feed.style.top = "0px";
		}});
	
	var feed2 = $('feed2_inner');
	if(feed2) {
		var tweet2 = feed2.firstChild;
		var height2 = tweet2.clientHeight;
		new Effect.Move(feed2, 
		{ x: 0, y: -height2, mode: 'relative', duration: 0.3, 
		afterFinish: function() {
			feed2.removeChild(tweet2);
			feed2.appendChild(tweet2);
			feed2.style.top = "0px";
		}});
	}
}

// for a step i out of steps, return between 0 and 1 where 0 is the
// starting point and 1 is the end point.  Used for animations
// because linear animation is boring.
function getStep(i, steps) {
	return 0.5 * (1 - Math.sin((Math.PI / 2) - ((Math.PI / steps) * i)));  // sinusoidal
	// return ((1 / steps) * i); // linear
}

var faqMutex = false;

function showFaq(id) {
	if(faqMutex) return false;
	faqMutex = true;
	var el = $("faq" + id);
	var q = $("faq_q" + id);
	
	var targetHeight;
	var myHeight;
	var frames = 15.0;
	
	if(el.style.display == "block") {
		
		q.className = q.className.replace(/\ssel/, '');
		targetHeight = 0;
		myHeight = el.getHeight();
		
	} else {
		
		q.className += " sel";

// measure the element without displaying it

		var position = el.style.position;		

		el.style.position = "absolute";
		el.style.visibility = "hidden";
		el.style.display = "block";
		
		targetHeight = myHeight = el.getHeight();
		
		el.style.height = "0px";
		el.style.position = position;
		el.style.visibility = "visible";

	}
	
	var height = parseInt(el.style.height);
	var i=0;
	var pct;

	var interval = setInterval(
		function() {
			pct = getStep(i++, frames);
			if(targetHeight == 0) {
				pct = 1 - pct;
			}

			pct = Math.round(myHeight * pct);
			if(i > frames) {
				clearInterval(interval);
				if(targetHeight == 0) {
					el.style.display = "none";
					el.style.height = "";
				} else {
					el.style.display = "block";
					el.style.height = "";
				}
			  faqMutex = false;
			} else {
				el.style.height = pct + "px";
			}
		},
		34
	);
	return false;
}

// Placeholders are part of the HTML5 draft, but at least
// Firefox and IE don't support them.  So, we fudge them.
function doPlaceholders() {
  tags = ["input","textarea"];
  for(t in tags) {
    var inputs = document.getElementsByTagName(tags[t]);
    for(var i=0; i<inputs.length; i++) {
      doJSPlaceholder(inputs[i]);
    }
  }
}

function doJSPlaceholder(obj) {
  var text = obj.getAttribute("placeholder");
  if(text) {
    obj.value = text;
    obj.className += " placeholder";
    Event.observe(obj, "focus", function() {
      if(obj.value==text) { obj.value = ""; }
      obj.className = obj.className.replace(/\s?placeholder/, "");
    });
    Event.observe(obj, "blur", function() {

      if(obj.value=="") {
        obj.value = text;
        obj.className += " placeholder";
      }
    });
  }
}

function removePlaceHolders(form) {
	var items = $(form).getElementsByClassName("placeholder");
	for(var i=0; i<items.length; i++) {
		items[i].value = "";
	}
	return true;
}

function canvasDropShadow(c, maxA) {
	
	var ctx = c.getContext('2d');
	var w = c.width;
	var h = c.height;
	var img = ctx.createImageData(w, h);
	var pix = img.data;
	var row, col, p, dx, dy, hw = w / 2, hp = Math.PI / 2;
	
	for(var i=0; i<pix.length; i+=4) {
		p = i / 4;
		row = p / w;
		col = p % w;
		dx = ((Math.abs(col - hw) / hw) * maxA) * 0.75;
//		dy = Math.sin((hp / h) * row) * maxA; // sinusoidal
		dy = ((maxA / h) * row); // linear
		pix[i+3] = dy - dx;
	}
	
	ctx.putImageData(img, 0, 0);	
}

function doContact() {
	var form = $('contactFormLarge');
	alert(form.serialize());
	return false;
}

function doFooterContact() {
	var form = $('contactForm');
	var loading = $('formLoading');
	
	var parent = form.parentNode;
	var height = parent.offsetHeight;
	
	loading.style.height = height + "px";
	while(loading.hasChildNodes()) loading.removeChild(loading.firstChild);
	
	loading.addClassName("loading");
	loading.addClassName("throb");
	form.addClassName("loading");
	
	form.request({
		parameters: { ajax: 1 },
		onComplete: function(transport) {
			loading.update(transport.responseText);
			loading.removeClassName("throb");
		}
	});
	
	return false;
}

function replaceContactForm() {
	$('formLoading').removeClassName("loading");
	$('contactForm').removeClassName("loading");
	return false;
}

function doWindowLoad() {
	doPlaceholders();
	buildSecondFeed();
	
	var script = document.createElement("script");
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", feedUrl);
	document.body.appendChild(script);
	
	var c = document.getElementById("ds");
	if(c) {
		c.width = c.parentNode.offsetWidth;
		canvasDropShadow(c, 50);
	}
	
	var anchor = window.location.hash;
	if(anchor) {
		var match = /#faq_q(\d+)/.exec(anchor);
		if(match && match.length > 0) {
			showFaq(match[1]);
		}
	}
}
Event.observe(window, "load", doWindowLoad);

