var AJAX_SUPPORT =  !!( window.XMLHttpRequest || window.ActiveXObject );
var REFERER = false;

var userdata = {
	logged_in: false
	};

String.prototype.trim = function() {
	var str = this.replace(/^\s\s*/, '');
	return str.replace(/\s\s*$/, '');
	}

function loadingAnimation() {
	var elem = document.createElement( "img" );
	elem.alt = "Loading...";
	elem.src = "/common/image/loading.gif";

	return elem;
	}

// Onload
$(document).ready(
	function() {
		var referer = window.location.pathname;
		if ( referer == "/" || referer == "/index.php" ) {
			REFERER = "";
			}
		else {
			REFERER = window.location.pathname + window.location.search;
			}

		$("img[alt='Spoiler']").one( "click", revealSpoiler );
		$("select[name='action']")
			.bind( "change", imageActionForm_onChange )
			.each( imageActionForm_init );

		$(":input")
			.bind( 'blur', labelFocus )
			.bind( 'focus', labelFocus );

		if ( !AJAX_SUPPORT ) return;

		//////////////

		if ( $( "#alias" ).length ) new proto_searchSuggest( 'alias', 0 );
		if ( $( "#artist" ).length ) new proto_searchSuggest('artist', 3 );
		if ( $( "#inherited" ).length ) new proto_searchSuggest( 'inherited', 0 );
		if ( $( "#masstags" ).length ) new proto_searchSuggest('masstags', 0 );
		if ( $( "#source" ).length ) new proto_searchSuggest('source', 2 );
		if ( $( "#tags" ).length ) new proto_searchSuggest( 'tags', 1 );

		///////////////

		$("a.add_fav").click( addFav );
		$("a.bookmark").click( bookmark );
		$("a.more_replies").click( moreReplies );
		$("a.remove_fav").click( removeFav );
		$("a.reply").click( reply_init );
		$("a.show_all_meta").click( showAllMeta );

		enlivenMeta( document );
		enlivenPost( document );

		///////////////

		var query_history = $( "#query_history" );
		if ( query_history.length ) {
			var link = document.createElement( "a" );
			link.appendChild( document.createTextNode( "Toggle Query History" ) );
			link.href = "#";
			link.onclick = function(){ $( "#query_history ul" ).toggle(); return false; };

			var elem = document.createElement( "p" );
			elem.appendChild( link );

			query_history.append( elem );
			}
		}
	);

function enlivenMeta( div ) {
	$("a.quicktag_artist, a.quicktag_source, a.quicktag_theme", div)
		.click( quickTag )
		.attr( "href", "#" );
	$("form.image_rating", div).bind( "submit", rate );
	}

function enlivenPost( div ) {
	$("a.edit", div).click( editPost );
	$("dl.spoiler", div)
		.addClass( "hide" )
		.one( "click", showSpoiler );
	}

//Search Form Functions
function proto_searchSuggest ( input, type ) {
	//Variable Declaration
	if ( typeof( input ) == 'string' ) {
		var input = document.getElementById( input );
		if ( input == null ) return false;
		}
	else {
		input = input;
		}
	var type = type;

	var display = null;
	var displayDiv = document.createElement("div");
		displayDiv.className = "search_suggest_div";
	var menuLength = 0;
	var menuPosition = menuLength;
	var menuVisible = false;
	var origText = "";
	var suggest = new Array();

	//Intialization Routine
	var parent = $( input.parentNode );

	parent.wrap( document.createElement( "div" ) );
	parent.append( displayDiv );

	input.setAttribute( "autocomplete", "off" );
	input.onkeydown = scroll;
	input.onkeyup = inputChange;
	input.onkeypress = inputEnter;
	input.onblur = inputBlur;

	//Functions
	function getTagList( string ) {
		string = string.trim();
		var fragment = string;
		fragment = fragment.replace( /(!)?"(.+?)"/g, "" ).trim();
		string = string.substr( 0, string.length - fragment.length );
		if ( string != "" && string.charAt( string.length-1 ) != " " ) string += " ";
		return string;
		}

	function handle( html ) {
		menuClear();

		var list = html.split("\n");
		suggest = new Array();
		menuLength = list.length;

		for ( i = 0; i < menuLength; i++ ) {
			if ( list[i] != "" ) {
				suggest[i] = new Array();
				suggest[i]["value"] = list[i];
				}
			}

		menuLength = suggest.length;
		menuPosition = menuLength;
		menuCreate();
		}

	function inputBlur( event ) {
		setTimeout( menuHide, 200 );
		}

	function inputChange( event ) {
		event = event || window.event;
		var key = event.keyCode;

		if ( key != 38 && key != 40 && key != 13 ) {
			if ( input.value.trim() == "" ) {
				menuClear();
				}
			else {
				origText = input.value;
				query();
				}
			}
		}

	function inputEnter( event ) {
		event = event || window.event;
		var key = event.charCode || event.keyCode;

		if ( key == 13 && menuVisible ) {
			if ( menuPosition = menuLength ) {
				menuHide();
				}
			return false;
			}
		}

	function menuClear() {
		menuHide();
		menuLength = 0;
		menuPosition = menuLength;
		if ( display != null ) {
			displayDiv.removeChild( display );
			}
		display = null;
		}

	function menuClick( event ) {
		if (!event) var event = window.event;
		target = event.target || event.srcElement;

		for( i = 0; i < menuLength; i++ ) {
			if( suggest[i]["element"] == target ) {
				set( i );
				menuClear();
				input.focus();
				return false;
				}
			}

		return false;
		}

	function menuCreate() {
		if ( menuLength > 0 ) {
			display = document.createElement("ul");
			display.className = "search_suggest_list";
			displayDiv.appendChild( display );

			for ( var i = 0; i < menuLength; i++ ) {

				var elem = document.createElement("li");
				if ( !( i % 2 ) ) elem.className = "odd";
				elem.onclick = menuClick;
				elem.appendChild( document.createTextNode( suggest[i]["value"] ) );

				display.appendChild( elem );

				suggest[i]["element"] = elem;
				}

			var elem = document.createElement("li");
			elem.className = "close";
			elem.onclick = menuHide;
			elem.appendChild( document.createTextNode( "[Close]" ) );

			display.appendChild( elem );

			menuShow();
			}
		}

	function menuHide() {
		if ( display != null ) {
			menuVisible = false;
			$( display ).slideUp( "fast" );
			}

		return false;
		}

	function menuShow() {
		if ( menuLength != 0 && display != null ) {
			menuVisible = true;
			$( display ).show();
			}
		}

	function query() {
		if ( input.value.trim() != "" ) {
			$.get( "/httpreq.php",
				{ mode: "tag_search", tags: input.value, type: type },
				handle
				);
			}
		}

	function scroll( event ) {
		event = event || window.event;
		var key = event.keyCode;

		if ( key == 38 || key == 40 ) {
			if ( menuPosition < menuLength ) {
				display.childNodes[ menuPosition ].className = "";
				}

			if ( key == 38 ) {
				menuPosition--;
				}
			else {
				menuPosition++;
				}

			if ( menuPosition < 0 ) {
				menuPosition = menuLength;
				}
			else if ( menuPosition > menuLength ) {
				menuPosition = 0;
				}

			if ( menuPosition == menuLength ) {
				input.value = origText;
				}
			else {
				menuShow();
				display.childNodes[ menuPosition ].className += " active";
				set( menuPosition );
				}
			}
		}

	function set( i ) {
		string = getTagList( origText );
		input.value = string + suggest[i]["value"] + " ";
		}
	}

//Quick Tagging
function quickTag( event ) {
	function createForm () {
		var value = "";
		$( "span.tag", formContainer ).each( function() { value += $( this ).text() + " "; } );

		value = value.replace( /&lt;/g, "<" ).replace( /&gt;/g, ">" );

		input = document.createElement("input");
		input.className = "text";
		input.id = 'quicktag_input_' + this.id;
		input.name = input.id;
		input.size = "40";
		input.type = "text";
		input.value = value;

		var elem = document.createElement("div");
		elem.appendChild( input );

		var form = document.createElement("form");
		form.action = "";
		form.appendChild( elem );
		form.onsubmit = submit;

		target.unbind().click( submit );
		formContainer.fadeOut( "fast",
			function(){
				formContainer
					.empty()
					.append( form )
					.fadeIn( "fast" );

				var suggest = new proto_searchSuggest( input, type );
				input.focus();
				}
			);

		return false;
		}

	function handle( html ) {
		input = null;
		target.unbind().click( createForm );
		formContainer.stop( true, true ).html( html ).fadeIn();
		}

	function submit( html ) {
		$.post( "/httpreq.php",
			{ mode: "quicktagupdate", image_id: id, tags: input.value, type: type },
			handle
			);

		formContainer.fadeOut();

		return false;
		}

	var target = $( this );
	var id = $( this ).parents( "div.image_thread" ).get(0).id.match( /\d+/ )[0];
	var input = null;

	var type;
	switch( this.className ) {
		case "quicktag_artist":
			type = 3;
			break;

		case "quicktag_source":
			type = 2;
			break;

		case "quicktag_theme":
			type = 1;
			break;
		}


	var formContainer = $( "#quicktag" + type + "_" + id );
	createForm();
	return false;
	}

//Favorites
function addFav( event ) {
	var target = $( this.parentNode );
	var image_id = this.parentNode.id.replace( /fav/g, "" );

	$.post( "/image/fav/"+image_id+"/", { method: "ajax", action: "add" } );

	var elem = document.createElement( "a" );
	elem.className = "remove_fav";
	elem.href = "#";
	elem.onclick = removeFav;

	var icon = document.createElement( "img" );
	icon.alt = "Remove Favorite";
	icon.src = "/common/image/icon/favorite_remove.png";
	icon.title = "Remove Favorite";
	elem.appendChild( icon );

	target.fadeOut( "fast",
		function(){
			target
				.empty()
				.append( elem )
				.fadeIn()
			}
		);

	var icon = document.createElement( "img" );
	icon.alt = "Favorite";
	icon.src = "/common/image/icon/favorite.png";
	icon.title = "Favorite";
	$( "#i"+image_id+" div.image_block h2" ).prepend( icon );
	$( icon ).hide().fadeIn( "slow" );

	return false;
	}

function removeFav(event) {
	var target = $( this.parentNode );
	var image_id = this.parentNode.id.replace( /fav/g, "" );

	$.post( "/image/fav/"+image_id+"/", { method: "ajax", action: "remove" } );

	var elem = document.createElement( "a" );
	elem.className = "add_fav";
	elem.href = "#";
	elem.onclick = addFav;

	var icon = document.createElement( "img" );
	icon.alt = "Add Favorite";
	icon.src = "/common/image/icon/favorite_add.png";
	icon.title = "Add Favorite";
	elem.appendChild( icon );

	target.fadeOut( "fast",
		function(){
			target
				.empty()
				.append( elem )
				.fadeIn()
			}
		);

	$( "#i"+image_id+" img[alt='Favorite']" ).fadeOut( "slow", function(){ $( this ).remove(); } );

	return false;
	}

//Rating
function rate( event ) {
	var handle = function( html ) {
		var elem = document.getElementById( "rating" + id );

		if ( !elem ) {
			$( target ).parents( "li" ).eq(0).hide( "fast", function(){ $( this ).remove() } );
			}
		else if ( elem.tagName == "DD" ) {
			$( "#rating"+id ).hide().html( html ).fadeIn();
			$( target ).parents( "li" ).eq(0).hide( "fast", function(){ $( this ).remove() } );
			}
		else if ( elem.tagName == "DIV" ) {
			var text = html.split( "\n" );
			$( elem ).hide().html( text[1] ).fadeIn();
			}
		}

	var target = this;
	var id = target.id.match( /\d+/ )[0];

	var value = $( "select[name='rating']", this ).get(0).value;

	if ( value != "" ) {
		$.post( "/image/rate/" + id + "/",
			{ method: "ajax", rating: value },
			handle
			);
		}
	else {
		alert( "You must select a rating." );
		}

	return false;
	}

//Bookmark
function bookmark( event ) {
	var image_id = this.pathname.match( /\d+/ )[0];

	$.get( "/image/bookmark/" + image_id, { method: "ajax" } );

	var bookmarked = $( "#bookmark" );
	if ( bookmarked.length ) {
		bookmark_id = bookmarked.parents( "div.image_thread" ).get(0).id.replace( /i/, "" );

		var li = document.createElement( "li" );
		li.id = "bookmark" + bookmark_id;

		var elem = document.createElement( "a" );
		elem.className = "bookmark";
		elem.href = "/image/bookmark/" + bookmark_id + "/";
		elem.onclick = bookmark;
		li.appendChild( elem );

		var icon = document.createElement( "img" );
		icon.alt = "Bookmark";
		icon.src = "/common/image/icon/bookmark.png";
		icon.title = "Bookmark";
		elem.appendChild( icon );


		$( "#i" + bookmark_id + " div.image_block ul.controls" ).prepend( li );
		$( li ).hide().fadeIn();

		bookmarked.fadeOut( "slow", function(){ bookmarked.remove() } );
		}

	$( this ).parents( "li" ).eq(0).remove();

	var icon = document.createElement( "img" );
	icon.alt = "Bookmarked";
	icon.id = "bookmark";
	icon.src = "/common/image/icon/bookmark.png";
	icon.title = "Bookmarked";

	$( "#i" + image_id + " h2" ).prepend( icon );
	$( icon ).hide().fadeIn();

	return false;
	}

//Image Action Form
function imageActionForm_init() {
	var target = this.form;

	var label = document.createElement( "label" );
	label.appendChild( document.createTextNode( "Replacement: " ) );

	var input = document.createElement( "input" );
	input.className = "text";
	input.name = "repost";
	input.size = "30";
	input.type = "text";
	label.appendChild( input );

	var elem = document.createElement( "p" );
	elem.style.display = "none";
	elem.appendChild( label );

	target.appendChild( elem );
	}

function imageActionForm_onChange( event ) {
	var replace = $( "input[name='repost']", this.form );

	if( this.value == "repost" ) {
		replace.parents("p").eq(0).show();
		replace.focus();
		}
	else {
		replace.parents("p").eq(0).hide();
		}
	}

//Show All Meta Information
function showAllMeta( event ) {
	var handle = function ( html ) {
		div
			.stop( true, true )
			.removeClass( "center" )
			.hide()
			.html( html )
			.fadeIn();

		enlivenMeta( div );
		}

	var image_id = this.href.match( /image\/(\d+)\/?$/ )[1];
	var div = $(this).parents( "div.meta" ).eq(0);
	div.fadeOut( "normal",
		function(){
			div
				.empty()
				.addClass( "center" )
				.append( loadingAnimation() )
				.show();
			}
		);

	$.get(
		"/httpreq.php",
		{ mode: "show_all_meta", image_id: image_id, referer: REFERER },
		handle
		);

	return false;
	}

//Post Functions
//Reply
function reply_init() {
	var id = this.pathname.match( /(\d+)\/?$/ )[1];
	reply( id );
	return false;
	}

function reply( id, text ) {
	function cancel() {
		display.fadeOut( "fast", function(){ display.empty().hide().append( orig.children() ).fadeIn(); } );
		textarea = null;
		}

	function createForm( text ) {
		if ( !text ) text = "";

		display.children().appendTo( orig );

		var form = document.createElement("form");
		form.action = "";
		form.className = "quick_reply";
		form.onsubmit = submit;

		var elem = document.createElement("h3");
		elem.appendChild( document.createTextNode( "Reply" ) );

		var title = document.createElement("div");
		title.className = "title";
		title.appendChild( elem );
		form.appendChild( title );


		div = document.createElement("p");
		form.appendChild( div );

		textarea = document.createElement("textarea");
		textarea.cols = 75;
		textarea.rows = 10;
		textarea.value = text;
		div.appendChild( textarea );

		div = document.createElement("p");
		div.className = "submit";
		form.appendChild( div );

		var elem = document.createElement("input");
		elem.className = "button";
		elem.type = "submit";
		elem.value = "Submit";
		div.appendChild( elem );

		div.appendChild( document.createTextNode( " " ) );

		var elem = document.createElement("input");
		elem.className = "button";
		elem.type = "reset";
		elem.value = "Cancel";
		elem.onclick = cancel;
		div.appendChild( elem );

		display.append( form );
		$( form ).hide().fadeIn();
		textarea.focus();
		return false;
		}

	function handle( html ) {
		var target = $( "#post_block_"+id );

		var newPost = $( html );
		enlivenPost( newPost.get(0) );


		newPost
			.hide()
			.appendTo( target )
			.fadeIn();

		display
			.stop( true, true )
			.hide()
			.empty()
			.removeClass( "center" )
			.append( orig.children() )
			.fadeIn();
		}

	function submit() {
		$.post( "/image/reply/" + id + "/",
			{ method: "ajax", action: "submit", post_text: textarea.value, referer: REFERER },
			handle
			);

		display.fadeOut( "fast",
			function(){
				display
					.empty()
					.append( loadingAnimation() )
					.addClass( "center" )
					.show();
				}
			);
		textarea = null;

		return false;
		}

	var id = id;

	var display = $( "#reply_" + id );
	var orig = $( document.createElement( "div" ) );
	var textarea = null;

	if ( display == null ) return;

	createForm( text );
	return false;
	}

//Edit Post
function editPost( event ) {
	function cancel( event ) {
		postDiv.fadeOut( "fast", function(){ postDiv.html( origText ).fadeIn(); } );
		return false;
		}

	function createForm( html ) {
		if( $( "form", postDiv ).length == 0 ) {
			var form = document.createElement("form");
			form.action = "#";
			form.onsubmit = submit;

			var div = document.createElement("div");
			form.appendChild( div );

			textarea = document.createElement("textarea");
			textarea.name = "post_text";
			textarea.value = html;
			textarea.cols = 75;
			textarea.rows = 5;
			div.appendChild( textarea );

			var element = document.createElement("p");
			div.appendChild( element );

			var input = document.createElement("input");
			input.className = "button";
			input.type = "submit";
			input.value = "Update Post";
			element.appendChild( input );

			element.appendChild( document.createTextNode( " " ) );

			var input = document.createElement("input");
			input.className = "button";
			input.onclick = cancel;
			input.type = "reset";
			input.value = "Cancel";
			element.appendChild( input );

			postDiv.fadeOut( "fast",
				function(){
					postDiv.empty().append( form ).fadeIn();
					textarea.focus();
					}
				);
			}
		}

	function handle( html ) {
		postDiv.fadeOut( "fast", function(){ postDiv.html( html ).each( enlivenPost ).fadeIn() } );
		}

	function startCreateForm() {
		$.get( "/post/" + id,
			{ method: "ajax" },
			createForm );
		return false;
		}

	function submit() {
		$.post( "/post/" + id + "/edit/",
			{ method: "ajax", action: "update", post_text: textarea.value },
			handle
			);

		return false;
		}

	var id = this.href.match( /#p(\d+)$/ )[1];
	var postDiv = $( "#post_" + id );
	var origText = postDiv.html();

	var textarea = null;

	startCreateForm();

	return false;
	}

//Quote
function quote( image, post, name ) {
	function handle( html ) {
		var text = '[quote="' + name + '"]' + html + '[/quote]\n';
		var textarea = document.getElementById("reply_"+image).getElementsByTagName("textarea");

		if ( textarea.length ) {
			textarea[0].value += text;
			textarea[0].focus();
			}
		else {
			new reply( image, text );
			}
		}

	$.get( "/post/" + post,
		{ method: "ajax" },
		handle );
	}

//Show Spoiler
function showSpoiler( event ) {
	$( this ).removeClass( "hide" ).addClass( "show" );
	}

//Show More Replies
function moreReplies( event ) {
	function handle( html ) {
		var elem = $( document.createElement( "div" ) );
		elem
			.html( html )
			.each( function(){ enlivenPost( this ) } )
			.appendTo( "#post_block_" + image_id )
			.hide()
			.fadeIn( "slow" );

		if ( userdata.logged_in ) {
			foot.empty().removeClass( "center" );

			var link = $( document.createElement( "a" ) );
			link.append( document.createTextNode( "[Reply]" ) );
			link.addClass( "reply" );
			link.attr( "href", "/image/reply/" + image_id + "/" );
			link.click( reply_init );

			foot.append( link );
			}
		else {
			foot.remove();
			}
		}

	var image_id = this.href.match( /(\d+)#/ )[1];
	var foot = $( this ).parents( "div.post_foot" ).eq(0);

	foot
		.empty()
		.addClass( "center" )
		.append( loadingAnimation() );

	$.get(
		"/httpreq.php",
		{ image_id: image_id, mode: "morereplies", method: "ajax", referer: REFERER },
		handle
		);

	return false;
	}

//Other, unsorted functions
function labelFocus( event ) {
	var label = $( this ).parents( "label" ).eq(0);
	if ( label.length ) {
		label.toggleClass( "focus" );
		}
	else if ( this.id ) {
		$( "label[for='"+this.id+"']" ).toggleClass( "focus" );
		}
	}

function revealSpoiler( event ) {
	var filename = this.parentNode.href.match( /\/([\w\.-]+)$/ )[1];
	filename = filename.split( "." )[0]

	var loading = loadingAnimation()
	$( this ).replaceWith( loading );

	var image = document.createElement( "img" );
	image.alt = filename;
	image.src = "/images/thumbs/" + filename + ".jpeg";

	if ( image.complete ) {
		$( loading ).replaceWith( image );
		}
	else {
		image.onload = function() {
			$( loading ).replaceWith( image );
			}
		}

	return false;
	}

function checkinput() {
	if ( document.getElementById("imagefile").value == '') {
		alert('Enter a filename!');
		document.getElementById("imagefile").focus();
		return false;
	}

	else if (source.indexOf("know") != -1 || source.indexOf("...") != -1 || source.indexOf("??") != -1 || source.indexOf("idea") != -1 || source.indexOf("random") != -1)
	{
		alert('Don\'t enter incorrect source information, just leave it blank if you really don\'t know');
		return false;
	}
}

function getmasstags() {
	var checks = document.getElementsByName('masstagimg');
	var masstagimgs = '';
	$( "input:checked[name='masstagimg']" ).each( function() {
		masstagimgs += this.value + ' ';
		} );

	document.getElementById( "masstagimgs" ).value = masstagimgs;
}
