var current_page = '';
$(document).ready(function () {

	//setup_maximage();
	
	setup_menu_links();
	setup_address();
	
	swf_musicplayer();
	setup_signup_form();
	
	// $(window).resize(function() {
	// 	var offset = $('#content .content').offset();
	// 	console.log(offset);
	// 	$('#header h1 a.logo').css({
	// 		'left': offset.left
	// 	});
	//     });

});

function setup_menu_links(){
	$('#menu a, #header a').click(function(){
		$("#menu a").removeClass("active");
		var page = parse_hash($(this).attr('rel'));
		$.address.value(page);
		$(this).addClass("active");
		return false;
	});
}

//listen for hash changes and setup the initial page
function setup_address(){
	$.address.init(function(){
		//load the current page
		if(window.location.hash == '' || window.location.hash == '/'){
			var p = window.location.href.substr(base_url.length);
			//console.log('init: '+p);
			if(p == '' || p == '/'){
				p = 'home';
			}
			page_bind_actions( parse_hash(p) );
			current_page = p;
			$.address.value(p);
		}else{
			//console.log('init: hash found');
			current_page = parse_hash(window.location.hash) || parse_hash("");
			change_page(current_page);
		}
		
	}).change(function(event) { 
		var request_page = parse_hash(event.value);
		//console.log('change: '+event.value);
		//if the hash changes, call a page change
		//but only if it's not the current page
		if(request_page != current_page){
			//if(pageTracker != null && typeof(pageTracker) != 'undefined'){
			//	pageTracker._trackPageview(base_url+request_page);
			//}
			change_page( request_page );
		}
	});
}

function change_page(page){
	
	//loading_show();
	$('#content').fadeOut(500, function(){
		//$.address.value(page);
		page_unbind_actions(current_page);
		ajax_content( page );
	});
}

function ajax_content(page){
	
	$.ajax({
		type: "POST",
		url: base_url+page,
		dataType: "html",
		data: "ajax=true",
		cache: true,
		async: true,
		success: function(data){
	   		got_page_content(data, page);
		}
		
	});
}

function got_page_content(data, page){
	$('#content').html(data);
	page_bind_actions(page);
	do_the_traci_swap(page);
	
	current_page = page;
	
	$('#content').fadeIn(500, function(){
		if ($('span.safe_email','#content').size() > 0){
			$('span.safe_email','#content').html(safe_email());
		}
	});
}

function page_bind_actions(page){
	//console.log('bind: '+page);
	switch( page ){

		case 'home':
			setup_innerfade();
			$('#header').stop().animate({ 
				top: "300px"
			}, 500 );
		break;
		
		case 'press':
			$('.toggle_article').toggle(
			function() {
				$(this).parent().find('.snippet').toggle(300);
				$(this).parent().find('.article').slideDown();
				$(this).find('a').text('[ Read Less ]');
			},function() {
				$(this).parent().find('.snippet').toggle(300);
				$(this).parent().find('.article').slideUp();
				$(this).find('a').text('[ Read More ]');
			})
		break;
		
		case 'schedule':
			$('.toggle_article').click(function() {
				$(this).parent().find('.article').slideToggle();
			})
		break;
		
		case 'news':
			get_tweets();
		break;
		
		default:;
	}
	
}

function page_unbind_actions(page){
	//console.log('unbind: '+page);
	switch( page ){
		case 'home':
			stop_innerfade();
			$('#header').stop().animate({ 
				top: "138px"
			}, 500 );
		break;
		
		case 'press':
			$('.show_article').unbind('click');
		break;
		
		case 'schedule':
			$('.show_article').unbind('click');
		break;
		
		default:;
	}	
	
}
//old
/*
function loadPage(page) {
	
	$('#content').fadeOut(500, function(){
		$('#content').load('/'+page+' .content', function(data){
			$('#content').attr('class', page);
			$('#content').fadeIn();
	
			if ($('span.safe_email').size() > 0){
				$('span.safe_email').html(safe_email());
			}	
			
		});
	});	
	
}
*/

function swf_musicplayer(){
	var flashvars = {
		home_path: base_url,
		auto_start: 'no',
		init_volume: 80
	};
	var params = {
		wmode: "transparent"
	};

	swfobject.embedSWF(public_folder+'flash/musicplayer.swf', "swf_musicplayer", "132", "35", "9.0.0", false, flashvars, params);
}

function safe_email() {
	var email = '';

	var l=new Array();
	l[0]='>';l[1]='a';l[2]='/';l[3]='<';l[4]='|109';l[5]='|111';l[6]='|99';l[7]='|46';l[8]='|101';l[9]='|103';l[10]='|97';l[11]='|115';l[12]='|115';l[13]='|97';l[14]='|109';l[15]='|111';l[16]='|114';l[17]='|116';l[18]='|101';l[19]='|109';l[20]='|64';l[21]='|116';l[22]='|116';l[23]='|97';l[24]='|109';l[25]='>';l[26]='"';l[27]='|109';l[28]='|111';l[29]='|99';l[30]='|46';l[31]='|101';l[32]='|103';l[33]='|97';l[34]='|115';l[35]='|115';l[36]='|97';l[37]='|109';l[38]='|111';l[39]='|114';l[40]='|116';l[41]='|101';l[42]='|109';l[43]='|64';l[44]='|116';l[45]='|116';l[46]='|97';l[47]='|109';l[48]=':';l[49]='o';l[50]='t';l[51]='l';l[52]='i';l[53]='a';l[54]='m';l[55]='"';l[56]='=';l[57]='f';l[58]='e';l[59]='r';l[60]='h';l[61]=' ';l[62]='a';l[63]='<';
	for (var i = l.length-1; i >= 0; i=i-1) {
		if (l[i].substring(0, 1) == '|') {
			email = email+"&#"+unescape(l[i].substring(1))+";";
		} else {
			email = email+unescape(l[i]);
		}
	}
	return email;

}

function do_the_traci_swap(page){
	// if (page=='') {page = 'home'}
	// 	
	// 	//$('body').css('background', '#FFFFFF url(public/images/layout/bg-'+page+'.jpg) repeat-x fixed center bottom');
	// 	
	// 	$('#traci img[rel]').add('#traci .home').fadeOut(500, function(){
	// 		$('#traci img[rel='+page+']').fadeIn(500);
	// 	});
	$('#traci img.traci').fadeOut(400, function(){
		path = $('#traci .img_swap img[rel='+page+']').attr('src');
		//console.log(path);
		load_image(path, function(){
		    $('#traci img.traci').attr('src', path);
			$('#traci img.traci').fadeIn(400);
		});
	});
}

function load_image(path, callback){
	var img = new Image();
	$(img).load(function () {
		$(this).css('display', 'none');
	    callback();
		$(this).remove();
	}).error(function () {
	    // notify the user that the image could not be loaded
	}).attr('src', path);
}

function get_tweets(){
	var url = 'http://twitter.com/statuses/user_timeline/';  
	var user = 'tracisnowe';
	var opts = '.json?count=10&callback=?';
	$.getJSON(url+user+opts, function(data){
   		$.each(data, make_tweet);
		$('#tweets .loading').fadeOut('fast');
	});
}
function make_tweet(i, tweet){
	//var post_date = tweet.created_at.substring(0, tweet.created_at.lastIndexOf(':'));
	var post_date = tweet.created_at.substring(0, 10);
	var html = '<div class="tweet">'+
					'<div class="tweet_date">'+post_date+'</div>'+
					'<div class="tweet_text">'+tweet.text.parseURL()+'</div>'+
				'</div>';
	$(html).hide().appendTo('#tweets').fadeIn(400);
}

function setup_signup_form(){
	init_inline_labels('#signup_form form');
	$('#signup_form form').validate({
		rules: {
			'email': {
				required: true,
				email: true,
				maxlength: 500
			}
		},
		messages: {
			'email': 'Your email is required'
		},
		submitHandler: function(form) {
			$(form).ajaxSubmit({
				type: 'post',
				dataType: 'script',
				clearForm: true,
				success: function(responce){
					//do something with the form here
					//like hide it
					alert(responce);
				}
			});
		}
	});
}
function init_inline_labels(elm){
	$('label + input', elm).each(function() {
		$(this).prev('label').hide();
		if($(this).val() === '') {
			var txt = $(this).prev('label').text();
			$(this).val(txt);
		}

		$(this).focus(function() {
			var txt = $(this).prev('label').text();
			if($(this).val() === txt) {
				$(this).val('').addClass('focused');
			}
		});

		$(this).blur(function() {
			var txt = $(this).prev('label').text();
			if($(this).val() === '') {
				$(this).val(txt).removeClass('focused');
			}
		});
	});

}

function setup_maximage(){
	if ($('#traci img.traci').size() > 0) {
		$('#traci img.traci').maxImage({
			maxFollows: 'height',
			topSpace: 10,
			maxAtOrigImageSize: false,
			leftSpace: 0,
			minHeight: 650
		});
	}
}

function unload_maximage(){
	delete window.resize;
	$('#traci img.traci').each(function(){
		delete $(this).maxImage;
	});
}

var slide_timer;
var current_img;
function setup_innerfade(){
	if ($('#traci .img_swap img').size() > 0) {
		current_img = $('#traci .img_swap img').eq(1);
		slide_timer = setInterval(change_image, 5000);
	}
}
function change_image(){
	//console.log('before: '+current_img.attr('rel'));
	do_the_traci_swap( current_img.attr('rel') );
	if(current_img.next('img').length > 0){
		current_img = current_img.next('img');
	}else{
		current_img = $('#traci .img_swap img:first');
	}
	//console.log('after: '+current_img.attr('rel'));
}
function stop_innerfade(){
	//console.log('clearInterval: '+slide_timer);
	clearInterval(slide_timer);
}

function parse_hash(hash){
	//console.log('hash: '+hash);
	return hash.replace(/^\//, '');
}

String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
		return url.link(url);
	});
};