window.Processing.data = {
	state: 1, // 1 = play, 0 = paused
	firstrun: true
};

var p;
var is_ff = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

$(document).ready(function(){
	
	if ( is_ff ) {
		$("textarea.codepress").codepress({
			path: '/assets/codepress/'
		});
	}
	
	function getSource(){
		if ( is_ff ) $.codepress.update();
		return $("#source").val();
	}
	
	$("#nav a[href^=#]").click(function(){
		var $current = $(this);
		var page = "#"+$(this).attr("href").split("-")[1];
		if ( $(page).is(":hidden") ) {
			$("#nav a.active").click();
			$(this).addClass("active");
			$(page)
				.fadeIn("normal")
				.bind('mouseleave',function(){
					$current.click();
				});
		} else {
			$current.removeClass("active");
			$(page)
				.fadeOut("normal")
				.unbind('mouseleave');
		}
		return false;
	});
	
	// refresh canvas
	function reloadCanvas(source) {
		
		var height = window.Processing.data.height;
		var width = window.Processing.data.width;
		var canvasHTML = '';
		if ( width > 0 && height > 0 ) {
			var offset = 50;
			canvasHTML = '<canvas id="display" style="left:'+ offset +'%;top:'+ offset +'%;margin:-'+ (height/2) +'px 0 0 -'+ (width/2) +'px;width:'+ width +'px;height:'+ height +'px;display:none;"></canvas>';
		} else {
			canvasHTML = '<canvas id="display" style="width:'+ $("body").width() +'px;height:'+ $("body").height() +'px;display:none;"></canvas>';
		}
		
		// reload canvas
		$("#display").fadeOut("normal",function(){
			$("canvas").remove();
			$("body").append(canvasHTML);
			if ( $("#pp").hasClass("play") ) $("#pp").click();
			try {
				p = null;
				p = new Processing($("canvas")[0],source);
			} catch(e) {
				alert("There was a glitch in the matrix...\n\n"+ e.name +"\n\n" + e.message);
			}
			$("#display").fadeIn("normal");
		});
	}
	
	$("#refresh").click(function(){
		var initialised = true;
		if ( window.Processing.data.source == getSource() ) {
			reloadCanvas(window.Processing.data.truesource);
		} else {
			window.Processing.data.source = getSource();
			
			if (window.Processing.data.firstrun) {
				$(".author a[href=#open-browse]").click();
				$(".home a[href=#open-about]").click();
				window.Processing.data.firstrun = false;
			}
			
			$.post("/",{
				ajax: "refresh",
				source: window.Processing.data.source
			},function(data){
				if(data.error) {
					alert("Please avoid using any regular javascript in the scripts.");
				} else {
					if (data.unsupported) {
						var unsupported = 'You have some currently unsupported methods in your script:\n';
						for(i=0; i < data.unsupported.length; i++) {
							unsupported += '  - ' + data.unsupported[i] + ');\n';
						}
						alert(unsupported);
					} else {
						// need to pull out size attributes and set the css to center it
						window.Processing.data.height = data.height;
						window.Processing.data.width = data.width;
						
						// set full size if none specified
						var source = data.source.replace(/[^\.]size\(\)\;/,'size('+ $("body").width() +','+ $("body").height() +');');
						window.Processing.data.truesource = source;
						reloadCanvas(source);
					}
				}
			},"json");
		}
		return false;
	}).click();
	
	
	
	// lockable code window
	function lock() {
		if ( $(this).hasClass("locked") ) {
			$(this).removeClass("locked").html("Lock");
			// $("#script-area").bind('mouseenter',showSource);
			// $("#script-area").bind('mouseleave',hideSource);
		} else {
			$(this).addClass("locked").html("Unlock");
			// $("#script-area").unbind('mouseenter');
			// $("#script-area").unbind('mouseleave');
		}
	}
	$("#lock").bind("click",lock);
	
	var scriptWidth = parseInt($.cookie('script_width')) || ($("#script-area").width()-6); // correct for padding
	var offset = scriptWidth - 6;
	$("#script-area").css({
		width: scriptWidth,
		left: -offset
	});
	$("#script-area .extendo").css({
		width: scriptWidth - 6
	});
	
	// bounce in / out
	function showSource(){
		if ( !$("#lock").hasClass("locked") ) {
			$(this).not(":animated").animate({
				left: 0
			},1000,"easeOutBounce",function(){
				$("#source").focus();
			});
		}
	}
	function hideSource(){
		if ( !$("#lock").hasClass("locked") ){
			var width = $(this).width();
			$.cookie('script_width',width);
			offset = width - 6;
			$(this).not(":animated").animate({
				left: -offset
			},1000,"easeOutBounce",function(){
				if ( getSource() != window.Processing.data.source ) {
					$("#refresh").click();
				}
			});
		} else {
			if ( getSource() != window.Processing.data.source ) {
				$("#refresh").click();
			}
		}
	}
	$("#script-area")
		.bind('mouseenter',showSource)
		.bind('mouseleave',hideSource);
	
	// play / pause
	$("#pp").live("click",function(){
		if ($(this).hasClass("pause")) {
			// window.Processing.data.state = 0;
			p.noLoop();
			$(this).removeClass("pause").html("Play").addClass("play");
		} else {
			//window.Processing.data.state = 1;
			p.loop();
			$(this).removeClass("play").html("Pause").addClass("pause");
		}
	});
	
	$("#delete").click(function(){
		$.post("/",{
			ajax: "delete"
		},function(){
			window.location.href = $("#location .author-name").attr("href");
		});
	});
	
	$("#logout").click(function(){
		$.post("/",{
			ajax: "logout"
		},function(){
			window.location.href = "/";
		});
		return false;
	});
	
	$("label[for=search]").labelise();
	
	var search = {
		page: $.cookie('search_page') || 0,
		query: $.cookie('search_query') || ''
	};
	
	if ( search.query != "" ) {
		$("#search").focus().val(search.query);
	}
	
	if ( $("body").hasClass("author") ) {
		search.query = $(".author-name").text();
		search.page = 0;
	}
	if ( $("body").hasClass("home") ) {
		search.query = '';
	}
	
	function search_scripts() {
		$.post("/",{
			ajax: "search",
			search: search.query,
			page: search.page
		},function(data){
			$("#results").fadeOut("slow",function(){
				$(this).html(data);
				$(this).fadeIn("normal");
			});
			$.cookie('search_page',search.page);
			$.cookie('search_query',search.query);
		});
	}
	
	$("#browse form").submit(function(){
		search.query = $("#search").val();
		search_scripts();
		if ( search.query == "" ) {
			$("#browse a.clear").hide();
		} else {
			$("#browse a.clear").show();
		}
		return false;
	});
	
	search_scripts();
	
	$("#browse a.page-link").live("click",function(){
		// if next
		if ( $(this).attr("rel") == "next" ) {
			search.page++;
			if ( search.page < 0 ) search.page = 0;
			search_scripts();
		}
		// if back
		if ( $(this).attr("rel") == "prev" ) {
			search.page--;
			if ( search.page < 0 ) search.page = 0;
			search_scripts();
		}
		return false;
	});
	
	$("#browse a.clear").live("click",function(){
		search = {
			page: 0,
			query: ''
		};
		$("#search").val("").blur();
		search_scripts();
		return false;
	});
	
	
	
	// setup quick jump input
	$("#goto").keydown(function(e){
		var size = $(this).val();
		size = size.length;
		
		// if deleting
		if ( e.keyCode == 8 ) {
			size-1;
		}
		
		// sanity
		if ( size < 1 ) {
			size = 1;
		}
		
		$(this).css("width",(size)+"em");
		
		// if enter then GOTO->
		if ( e.keyCode == 13 ) {
			window.location.href = "/" + $(this).val();
		}
	}).focus();
	
	$("#download").click(function(){
		window.location.href = window.location.href + '/download';
		return false;
	});
	
	// resizable script area :) I love jquery ui
	
	$("#script-area").resizable({
		handles: 'e',
		alsoResize: '.extendo',
		maxWidth: $("body").width()-200,
		minWidth: 250,
		delay: 0,
		distance: 0,
		start: function() {
			$(".ui-resizable-e").addClass("active");
			$("#script-area")
				.unbind('mouseenter')
				.unbind('mouseleave');
			},
		stop: function() {
			$(".ui-resizable-e").removeClass("active");
			$("#script-area")
				.bind('mouseenter',showSource)
				.bind('mouseleave',hideSource);
			}
	});
	
	// set script status
	$("#publish").click(function(){
		var status = ($("#publish:checked").length == 1) ? 'published' : 'draft';
		$.post("/",{
			ajax: "status",
			status: status
		},function(){
			search_scripts();
		});
	});
	
	
	$("#embed-width,#embed-height").keyup(function(){
		$("#embed textarea").val($("#embed textarea").val().replace(/style\=\".*?\"/,'style="width:'+ $("#embed-width").val() +'px;height:'+ $("#embed-height").val() +'px;"'));	
	});
	
	$("#embed textarea").click(function(){
		$(this).select();
		return false;
	});
	
	// if non home page and owner open code window
	if ( $("li.account .user").text() == $("#location .author-name").text() && $("body").attr("class") == "" ) {
		$("#script-area").mouseenter();
	}
	
});