/* 
 * jQuery Color Animations 
 * Copyright 2007 John Resig 
 * Released under the MIT and GPL licenses. 
 */ 
 
(function(jQuery){jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(fx.state==0){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end)}fx.elem.style[attr]="rgb("+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(",")+")"}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)return color;if(result=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];if(result=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];return colors[jQuery.trim(color).toLowerCase()]}function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,"body"))break;attr="backgroundColor"}while(elem=elem.parentNode);return getRGB(color)};var colors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);

/*
 * jQuery plugin: fieldSelection - v0.1.0 - last change: 2006-12-16
 * (c) 2006 Alex Brem <alex@0xab.cd> - http://blog.0xab.cd
 */
(function(){var c={getSelection:function(){var e=this.jquery?this[0]:this;return(('selectionStart'in e&&function(){var l=e.selectionEnd-e.selectionStart;return{start:e.selectionStart,end:e.selectionEnd,length:l,text:e.value.substr(e.selectionStart,l)}})||(document.selection&&function(){e.focus();var r=document.selection.createRange();if(r==null){return{start:0,end:e.value.length,length:0}}var a=e.createTextRange();var b=a.duplicate();a.moveToBookmark(r.getBookmark());b.setEndPoint('EndToStart',a);return{start:b.text.length,end:b.text.length+r.text.length,length:r.text.length,text:r.text}})||function(){return{start:0,end:e.value.length,length:0}})()},replaceSelection:function(){var e=this.jquery?this[0]:this;var a=arguments[0]||'';return(('selectionStart'in e&&function(){e.value=e.value.substr(0,e.selectionStart)+a+e.value.substr(e.selectionEnd,e.value.length);return this})||(document.selection&&function(){e.focus();document.selection.createRange().text=a;return this})||function(){e.value+=a;return this})()}};jQuery.each(c,function(i){jQuery.fn[i]=this})})();

/*
 * jquery.uploadProgress
 *
 * Original Copyright (c) 2008 Piotr Sarnacki (drogomir.com)
 * Modified for Fangamer by Ryan Alyea
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 */
(function($) {
  $.fn.uploadProgress = function(options) {
  options = $.extend({
    interval: 2000,
    progressBar: "#progressbar",
    progressUrl: "/progress",
    start: function() {},
    uploading: function() {},
    complete: function() {},
    success: function() {},
    error: function() {},
    preloadImages: ["/include/images/uploading.gif"],
    uploadProgressPath: '/javascripts/jquery.uploadProgress.js',
    jqueryPath: '/javascripts/jquery.js',
                              timer: ""
  }, options);
  
  $(function() {
    //preload images
    for(var i = 0; i<options.preloadImages.length; i++)
    {
      options.preloadImages[i] = $("<img>").attr("src", options.preloadImages[i]);
    }
    /* tried to add iframe after submit (to not always load it) but it won't work. 
    safari can't get scripts properly while submitting files */
    if($.browser.safari && top.document == document) {
      /* iframe to send ajax requests in safari 
         thanks to Michele Finotto for idea */
      iframe = document.createElement('iframe');
      iframe.name = "progressFrame";
      $(iframe).css({width: '0', height: '0', position: 'absolute', top: '-3000px'});
      document.body.appendChild(iframe);
      
      var d = iframe.contentWindow.document;
      d.open();
      /* weird - safari won't load scripts without this lines... */
      d.write('<html><head></head><body></body></html>');
      d.close();
      
      var b = d.body;
      var s = d.createElement('script');
      s.src = options.jqueryPath;
      /* must be sure that jquery is loaded */
      s.onload = function() {
        var s1 = d.createElement('script');
        s1.src = options.uploadProgressPath;
        b.appendChild(s1);
      }
      b.appendChild(s);
    }
  });
  
  return this.each(function(){
    $(this).bind('submit', function() {
      $("#GO_UPLOAD").parents("li").eq(0).hide().after('<li class="odd"><div id="uploading">\n\
  	      <div id="progress" class="bar">\n\
  	        <div id="progressbar">&nbsp;</div>\n\
  	      </div>\n\
  	    </div>\n\
  	    </li>')
      var uuid = "";
      for (i = 0; i < 32; i++) { uuid += Math.floor(Math.random() * 16).toString(16); }
      
                        /* update uuid */
                        options.uuid = uuid;
      /* start callback */
      options.start();
 
      /* patch the form-action tag to include the progress-id 
                           if X-Progress-ID has been already added just replace it */
      if(old_id = /X-Progress-ID=([^&]+)/.exec($(this).attr("action"))) {
        var action = $(this).attr("action").replace(old_id[1], uuid);
        $(this).attr("action", action);
      } else {
        if (typeof gotoattachment != "undefined" && gotoattachment == true) {
          $(this).attr("action", jQuery(this).attr("action") + "?X-Progress-ID=" + uuid + "#attachment_uploaded_data");
        }
        else {
          $(this).attr("action", jQuery(this).attr("action") + "?X-Progress-ID=" + uuid);
        }
      }
      var uploadProgress = $.browser.safari ? progressFrame.jQuery.uploadProgress : jQuery.uploadProgress;
      options.timer = window.setInterval(function() { uploadProgress(this, options) }, options.interval);
      
    });
  });
  };
 
jQuery.uploadProgress = function(e, options) {
  jQuery.ajax({
    type: "GET",
    url: options.progressUrl,
    dataType: "json",
    beforeSend: function(xhr) {
      xhr.setRequestHeader("X-Progress-ID", options.uuid);
    },
    success: function(upload) {
      if (upload.state == 'uploading') {
        upload.percents = Math.floor((upload.received / upload.size)*1000)/10;
        
        var bar = $.browser.safari ? $(options.progressBar, parent.document) : $(options.progressBar);
        bar.css({width: upload.percents+'%'});
          options.uploading(upload);
      }
      
      if (upload.state == 'done' || upload.state == 'error') {
        window.clearTimeout(options.timer);
        options.complete(upload);
        
      }
      
      if (upload.state == 'done') {
        options.success(upload);
      }
      
      if (upload.state == 'error') {
        options.error(upload);
      }
    }
  });
};
 
})(jQuery);

var logged_in_user = null
function read_icons() {
	var test = new Array();
	var i = 0;
  var $topics = $("tr").not("#tableheader").map(function(){test[i] = $(this).attr("id");i++;})
  var listofids = test.join(",");
	//alert(listofids);
	var test2;
	$.get("/forum/read/",{topics: listofids},function(data){
		test2 = eval('(' + data + ')');
		for (i=0;i<test2.length;i++)
		{
			$("tr#"+test2[i]).find("td#image").html('<img src="http://starmen.net/forum/theme/hijola/images/existing_content.png">');
		}
		$("tr").find("th#image").css("visibility","visible");
		$("tr").find("td#image").css("visibility","visible");
	});
}

function add_overlay() {
	$("body").prepend('<div id="overlay"><div id="litbox"></div></div>');
}

function do_loading() {
	do_overlay(66);
	$("#litbox").html('<img src="/include/images/loading.gif"/>').show();
}

function do_overlay(width) {
	if (typeof width == "undefined") {
	    width = 550;
  }
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	var litboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 300) / 2);
	var litboxLeft = ((arrayPageSize[0] - 20 - width) / 2);
	$("#overlay").height(arrayPageSize[1]).width(arrayPageSize[0]).show();
	$("#litbox").css("top",litboxTop).css("left",litboxLeft);
	//$("#overlay").click(function(){
	//  $("#overlay,#litbox").hide();
	//})
}

function close_overlay() {
	$("#litbox").slideUp(function(){
	  $("#overlay").hide();
	})
}

$(document).ready(function(){
	add_overlay();
})

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
// Gracefully
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

function inline_editing() {
	$(".posts #main .post .post-footer .utils .edit").unbind().click(function(){
		var post = $(this).parents(".post");
		var id = post.attr("id").substring(4);
		other_editing_box = $(".posts #main .post .post-body .fckeditor")
		if (other_editing_box.html() != null) {
			alert("Dude, you're already editing another post. You have to click 'CANCEL' on it first!");
			return false;
		}
		do_overlay(66);
		$("#litbox").html('<img src="/include/images/loading.gif"/>').show();
		topiclink = $("#main h2 a.topic").attr("href")
		$.get(topiclink+"/"+id+"/edit.ajax",null,function(data){
			inline_editing_form_stuff(data,post,id,other_editing_box,topiclink)
		})
		forum_spoilers();
		return false;
	})
}

function inline_editing_form_stuff(data,post,id,other_editing_box,topiclink) {
	if (data == "MessageLocked") {
		alert("A moderator locked this message from editing!");
		close_overlay();
		return false
	}
	else if (data == "TopicLocked") {
		alert("A moderator locked this topic. You cannot edit a post in a locked topic.");
		close_overlay();
		return false
	}
	else if (data == "LoginRequired") {
		alert("You must be logged in before you edit a message!")
		close_overlay();
		return false;
	}
	else if (data == "SecurityError") {
		alert("You are not allowed to edit this message!")
		close_overlay();
		return false;
	}
	else {
		$.getJSON("/forum/message/"+id+".ajax",function(original){
			//$(".posts #main .quick .post-body form .newfck").html("Please click on the 'CANCEL' button if you wish to reply.")
			$(".posts #main .quick").hide()
			if (typeof canceldata == "undefined") canceldata = post.children(".post-body")
			if (typeof canceldatahtml == "undefined") canceldatahtml = post.children(".post-body").html() 
			if (typeof canceldatapollhtml == "undefined" && post.children(".post-body").find("div.poll").length > 0) {
				canceldatapollhtml = '<div class="poll">'+post.children(".post-body").find("div.poll").html()+'</div>'
			}
			else {
				canceldatapollhtml = ""
			}
			post.children(".post-body").html(data);
			post.find(".stopedit").click(function(){
				post.find(".post-body").html(canceldatahtml);
				/*var editFCKeditor = new FCKeditor('message[body_original]', '500px', null, null, null, '/include/FCKEditor/');
				editFCKeditor.Config['CustomConfigurationsPath'] = '/include/FCKEditor/matocode.js';
				$(".posts #main .quick .post-body form .newfck").html(editFCKeditor.CreateHtml());*/
				$(".posts #main .quick").show()
				forum_spoilers();
				return false;
			})
			/*var editFCKeditor = new FCKeditor('message[body_original]', '500px', null, null, original.body_original, '/include/FCKEditor/');
			editFCKeditor.Config['CustomConfigurationsPath'] = '/include/FCKEditor/matocode.js';
			post.find(".fckeditor").html(editFCKeditor.CreateHtml());*/
			close_overlay();
			if ($.browser.msie) {
			  IE7.recalc();
			}
			post.find(".ajaxEdit").click(function(){
				do_overlay(66);
				$("#litbox").html('<img src="/include/images/loading.gif"/>').show();
				output = post.find("form").serializeArray()
				/*for (var i = 0; i < output.length; i++) {
					if (output[i].name == 'message[body_original]') {
						var oEditor = FCKeditorAPI.GetInstance('message[body_original]');
						output[i].value = oEditor.GetData();
					}
				}*/
				$.post(topiclink+"/"+id+"/edit.ajax",output,function(postreturn){
					if (postreturn == "OK!") {
						$.getJSON("/forum/message/"+id+".ajax",function(newdata){
							post.find(".post-body").html(canceldatahtml);
							post.find(".post-body").children("div.message-content").html(canceldatapollhtml+newdata.body);
							if (newdata.show_sig == true) {
								if (post.find(".post-body .sig").length <= 0 && newdata.signature != null) {
									post.find(".post-body").append('<div class="sig"><p>'+newdata.signature+'</p></div>');
								}
								else {
									post.find(".post-body .sig").html('<p>'+newdata.signature+'</p>');
								}
							}
							else {
								post.find(".post-body .sig").html('');
							}
							/*var editFCKeditor = new FCKeditor('message[body_original]', '500px', null, null, null, '/include/FCKEditor/');
							editFCKeditor.Config['CustomConfigurationsPath'] = '/include/FCKEditor/matocode.js';
							$(".posts #main .quick .post-body form .newfck").html(editFCKeditor.CreateHtml());*/
							$(".posts #main .quick").show()
							close_overlay();
							forum_spoilers();
						})
					}
					else inline_editing_form_stuff(postreturn,post,id,other_editing_box,topiclink);
				})
				return false;
			})
		})
	}
}

function quote_users() {
	$("body.posts ul.utils li.quote a").unbind().click(function(){
		id = $(this).parents(".post").attr("id").substring(4)
		if ($(".quick").length > 0) {
			//alert(id);
			do_overlay(66);
			$("#litbox").html('<img src="/include/images/loading.gif"/>').show();
			$.getJSON("/forum/message/"+id+".ajax",function(data){
				$.scrollTo(".quick",200)			
				//alert(data.body);
				/*var oEditor = FCKeditorAPI.GetInstance('message[body_original]');
				/*var bIsWysiwyg = ( oEditor.EditMode == FCK_EDITMODE_WYSIWYG ) ;
				if (!bIsWysiwyg) {
					oEditor.SwitchEditMode();
				}
				oEditor.SetData(oEditor.GetXHTML(true)+"[quote="+id+";"+data.creator+":]"+data.body_original+"[/quote]\n\n");
				oEditor.Focus();*/
				before = $(".quick textarea").eq(0).attr("value")
				if (typeof before == "undefined") {
					before = '';
				}
				$(".quick textarea").focus().attr("value",before+"[quote="+id+";"+data.creator+":]"+data.body_original+"[/quote]\n\n").focus();
				
				close_overlay();
			})
			return false
		}
		else {
			return true
		}
	})
}

function thumbs() {
	$(".posts #main .post .post-footer .scorecard .thumbsup a").click(function(){
		var id = $(this).parents(".post").attr("id").substring(4)
		var thethis = $(this).parent().parent().find(".score")
		var thumb = $(this).parent();
		var tehparent = $(this).parent().parent()
		$.get("/forum/thumbup/"+id+".ajax",null,function(data){
			if (data.match(/-?\d{1,}/)) {
				score = thethis.html();
				scoreint = parseInt(data)
				score = score.replace(/-?\d{1,}/,scoreint)
				thethis.html(score);
				originalcolor = thethis.css("color")
				thethis.css("color","#0000ff").animate( { color:originalcolor }, 1500 )
			}
			else if (data == "SELF") {
				alert("You are not allowed to vote for yourself!")
			}
			else if (data == "RESET"){
				score = thethis.html();
				scoreint = parseInt(score.match(/-?\d{1,}/))
				scoreint = scoreint - 1
				score = score.replace(/-?\d{1,}/,scoreint)
				thethis.html(score);
				originalcolor = thethis.css("color")
				thethis.css("color","#0000ff").animate( { color:originalcolor }, 1500 )
			}
			else if (data.substring(0,5) == "BAD: ") {
			  alert(data.substring(5));
			}
			else {
				alert("There was an error!")
			}
			tehparent.find(".thumbsdown").removeClass("used")
			thumb.addClass("used");
		})
		return false;
	})
	$(".posts #main .post .post-footer .scorecard .thumbsdown a").click(function(){
		var id = $(this).parents(".post").attr("id").substring(4)
		var thumb = $(this).parent();
		var thethis = $(this).parent().parent().find(".score")
		var tehparent = $(this).parent().parent()
		$.get("/forum/thumbdown/"+id+".ajax",null,function(data){
			if (data.match(/-?\d{1,}/)) {
				score = thethis.html();
				scoreint = parseInt(data)
				score = score.replace(/\+?-?\d{1,}/,scoreint)
				thethis.html(score);
				originalcolor = thethis.css("color")
				thethis.css("color","#0000ff").animate( { color:originalcolor }, 1500 )
			}
			else if (data == "SELF") {
				alert("You are not allowed to vote for yourself!")
			}
			else if (data == "RESET"){
				score = thethis.html();
				scoreint = parseInt(score.match(/\+?\-?\d{1,}/))
				scoreint = scoreint + 1
				score = score.replace(/\+?-?\d{1,}/,scoreint)
				thethis.html(score);
				originalcolor = thethis.css("color")
				thethis.css("color","#0000ff").animate( { color:originalcolor }, 1500 )
			}
			else if (data.substring(0,5) == "BAD: ") {
			  alert(data.substring(5));
			}
			else {
				alert("There was an error!")
			}
			tehparent.find(".thumbsup").removeClass("used")
			thumb.addClass("used");
		})
		return false;
	})
}

function sidebar_search() {
	$("#q").click(function(){
		if ($(this).attr("value") == "Click Here to Start!")
			$(this).attr("value","");
	})
	$("#q").bind("keyup",function(){
		input = $(this).parents("form").eq(0).serialize()
		if (typeof searchtimeout == "number") {
			clearTimeout(searchtimeout)
		}
		searchtimeout = setTimeout("do_search(input)",500)
	})
	$("#quicksearch input.just").click(function(){
		input = $(this).parents("form").eq(0).serialize()
		if (typeof searchtimeout == "number") {
			clearTimeout(searchtimeout)
		}
		searchtimeout = setTimeout("do_search(input)",500)
	})
}

function do_search(input){
	$.post("/forum/search.ajax",input,function(data){
		$("#searchresults").html('<button id="searchclear">Clear!</button><br/>'+data);
		$("#searchclear").click(function(){
			$("#searchresults").html('');
		})
	})
}

function get_logged_in_user() {
	$.ajax({
		type: "GET",
		url: "/members/get_logged_in_user",
		async: false,
		dataType: "json",
		success:function(data){
			logged_in_user = data
			render_headerbar_user();
			login_ajax();
		}
	})
}

function render_headerbar_user() {
	if (logged_in_user != null) {
		$("#header .right ul").html('<li id="profile">\n\
							'+user_link(logged_in_user)+'\n\
							<form id="logoutform" method="POST" action="/login/logout/">\n\
  						  <input type="hidden" name="_method" value="delete">\n\
  						  <input id="logout" type="image" src="/include/images/logout.png" alt="Logout" title="Logout" border="0">\n\
  						</form>\n\
						</li>\n\
						<li id="inbox">\n\
							<img class="sprite" style="width: 1.6em; height: 1.6em;" src="/include/images/sprites/sprite1010.gif" alt="Mailbox sprite" title="2 Private Messages" />\n\
							<a href="/forum/inbox">Inbox</a>\n\
						</li>')
	}
	else {
		$("#header .right ul").html('<li id="register">\n\
							<img class="sprite" style="width: 1.6em; height: 1.6em; top: 1.1em; left: 1.2em;" src="/include/images/sprites/sprite1112.gif" alt="Hawkeye sprite" title="Register" /> \n\
							<a href="/login/register" id="registerlink">Register</a>\n\
						</li>\n\
						<li id="login">\n\
							<img class="sprite" style="width: 1.6em; height: 1.6em; top: 1.1em; left: 1.1em;" src="/include/images/sprites/sprite1104.gif" alt="Zappy Mcsprite" title="Login" /> \n\
							<a href="/login/login" id="loginlink">Login</a>\n\
						</li>')
	}
}

function litbox_form(form) {
	return '\n\
<div id="litboxinner">\n\
<div id="litboxheader">\n\
	<h1>Login to Fangamer!</h1>\n\
	<a href="#" id="litboxclose"><img src="/include/images/button-x-close.png" alt="X Icon" title="Close this Window" /></a>\n\
</div>\n\
<div id="litboxbody">\n\
	'+form+'\n\
</div>\n\
</div>'
}

function login_ajax() {
	$("a#loginlink").unbind().click(function(){
		do_loading();
		var form = "";
		$.get("/login/login.ajax",null,function(data){
			form = data
			do_overlay();
	   $("#litbox").html('\n\
<div id="litboxinner">\n\
	<div id="litboxheader">\n\
		<h1>Login to Fangamer!</h1>\n\
		<a href="#" id="litboxclose"><img src="/include/images/button-x-close.png" alt="X Icon" title="Close this Window" /></a>\n\
	</div>\n\
	<div id="litboxbody">\n\
		<div id="loginbad"><p></p></div>\n\
		'+form+'\n\
	</div>\n\
</div>').hide().slideDown();
			$("#user_name").focus();
			$("#litboxclose").click(function(){
				close_overlay();
				return false;
			})
			$("div#litboxinner").find("input#loginsubmit").click(function(){
				$.post("/login/login.ajax",$("form#loginform").serialize(),function(data){
					if (data=="BAD") {
						$("div#loginbad").css("visibility","visible")
						$("div#loginbad p").css("display","block").html("Your username does not exist or your password does not match. Please try again.").show();
					}
					else if (data=="OK!") {
						window.location.reload(true)
						/*get_logged_in_user()
						close_overlay();
						//read_icons();
						if ($("#flash").length == 0) {
							$("#container").prepend('<div id="flash"></div>')
						}
						$("#flash").slideUp("fast",function(){
							$(this).html('<div class="notice"><div class="hide"><a href="#"><img src="/include/images/button-x-close.png" alt="X button image" title="Hide this Message" /></a></div><p>You are now logged in!</p><span class="hide">(<a href="#">hide</a>)</span></div>').slideDown("fast");
							$('#container #flash .hide a').click(function(){
								$(this).parent().parent().parent().slideUp();
								return false;
							});
						})*/
					}
				});
				return false;
			});
		})
		return false;
	})
}

function user_link(user){
	if (user == null) return ""
	outstring = '<a class="member '
	if (user.color == 1) outstring += "mod"
	if (user.color == 2) outstring += "admin"
	outstring += '" href="/members/'+user.permalink+'">'+user.name+'</a>'
	return outstring
}

function preview_button() {
	$(".posts #main #preview").click(function(){
		$.ajax({
			type: "POST",
			url: "/forum/preview",
			data: $("#main .quick form").serialize(),
			async: true,
			dataType: "json",
			success:function(data){
				if (logged_in_user == null) {
					get_logged_in_user();
				}
				preview = $("#postpreview")
				if (preview.length == 0) {
					$("#main .quick").prev().hasClass("odd") ? evenodd = "even" : evenodd = "odd"
					$("#main .quick").before('<div class="post '+evenodd+'" id="postpreview"></div>')
					preview = $("#postpreview")
				}
				preview.html('<div id="previewnotice"><p>This is a preview. It has not been posted yet.</p></div><div class="post-header preview"><h3>'+user_link(logged_in_user)+'</h3></div><div class="post-body"><div class="message-content">'+data.body+'</div></div>');
				forum_spoilers();
			}
		})
		return false;
	})
}

function new_topic_button() {
	$("#create_new_topic").click(function(){
		do_overlay(700);
		$.get($(this).attr("href")+".ajax",function(data){
			$("#litbox").html(litbox_form(data)).show();
			$("#litboxinner").css("width","700px")
			$("#litboxclose").click(function(){
				close_overlay();
				return false;
			})
		})
		return false;
	})
}

function insert_poll_button() {
	$("#insertpoll").unbind().click(function(){
		$("#polls").addClass("tabley").append('<label><span>Title:</span><input id="poll_name" name="poll[name]" size="30" type="text" /></label>\n\
							<label><span>Option 1:</span><input id="poll_option0" name="poll[option0]" size="30" type="text" /></label>\n\
							<label><span>Option 2:</span><input id="poll_option1" name="poll[option1]" size="30" type="text" /></label>\n\
							<label><span>Option 3:</span><input id="poll_option2" name="poll[option2]" size="30" type="text" /></label>\n\
							<label><span>Option 4:</span><input id="poll_option3" name="poll[option3]" size="30" type="text" /></label>\n\
							<label><span>Option 5:</span><input id="poll_option4" name="poll[option4]" size="30" type="text" /></label>\n\
							<label><span>Option 6:</span><input id="poll_option5" name="poll[option5]" size="30" type="text" /></label>\n\
							<label><span>Option 7:</span><input id="poll_option6" name="poll[option6]" size="30" type="text" /></label>\n\
							<label><span>Option 8:</span><input id="poll_option7" name="poll[option7]" size="30" type="text" /></label>\n\
							<label><span>Option 9:</span><input id="poll_option8" name="poll[option8]" size="30" type="text" /></label>\n\
							<label><span>Option 10:</span><input id="poll_option9" name="poll[option9]" size="30" type="text" /></label>')
		$("#insertpoll").hide();
		$("#polls .buttons").append('<a class="button negative" id="cancelpoll">\n\
													<img class="sprite" title="Cancel" alt="Exclamation sprite" src="/include/images/sprites/sprite1123.gif" style="width: 1.6em; height: 1.6em; top: 0.5em; left: -0.6em;"/>\n\
													<span>Cancel Poll</span>\n\
												</a>')
		$("#cancelpoll").unbind().click(function(){
			if (confirm("Are you sure you want to delete this poll? If it's an old poll in use, it will delete it!")) {
				if ($("#polls legend").attr('id')) {
					$.get("/forum/deletepoll/"+$("#polls legend").attr('id').substring(4)+".ajax")
				}
				$("#insertpoll").show();
				$("#cancelpoll").remove();
				$("#polls label").remove();
			}
		})
		return false;
	})
	$("#cancelpoll").unbind().click(function(){
		if (confirm("Are you sure you want to delete this poll? If it's an old poll in use, it will delete it! You will not be able to get it back!")) {
			if ($("#polls legend").attr('id')) {
				$.get("/forum/deletepoll/"+$("#polls legend").attr('id').substring(4)+".ajax")
			}
			$("#insertpoll").show();
			$("#cancelpoll").remove();
			$("#polls label").remove();
		}
	})
}

function insert_smilie() {
	$("#reply div.post-body div.smilies img").unbind().click(function(){
		if (typeof $("#message_body_original").attr("value") != "undefined") {
			newvalue = $("#message_body_original").attr("value")
		}
		else {
			newvalue = ""
		}
		newvalue += $(this).attr("title")
		$("#message_body_original").attr("value",newvalue);
		return false;
	})
}

function changeable_times() {
	$("span.changeabletime").click(function(){
	  $.post("/login/toggle_changeable_time",{authenticity_token:$("body").attr("id")})
		$(".changeabletime").each(function(){
			var temp = $(this).attr("title")
			$(this).attr("title",$(this).html())
			$(this).html(temp)
		})
	})
}

function topic_unseen() {
	// This function emulates a page refresh after 'seeing' a topic. This way, we can have the back button work the same on the old forum, but still locally cache.
	$("#topiclist_table a.topic").mouseup(function(){
		$(this).parents(".unseen").removeClass("unseen")
	})
}

function forum_unseen() {
	// This function emulates a page refresh after 'seeing' a topic. This way, we can have the back button work the same on the old forum, but still locally cache.
	$("body.main #main div.forum-header h2 a").mouseup(function(){
		$(this).parents(".unseen").removeClass("unseen")
	})
}

function forum_spoilers() {
	$("#main button.spoileron").unbind().click(function(){
		$(this).parents(".spoileroncontainer").eq(0).hide();
		$(this).parents(".spoiler_container").eq(0).children(".spoiler").show();
		return false;
	})
	$("#main button.spoileroff").unbind().click(function(){
		$(this).parents(".spoiler").eq(0).hide();
		$(this).parents(".spoiler_container").eq(0).children(".spoileroncontainer").show();
		return false;
	})
}

var spriteselectorid = "";

function hide_spritebox_for_javascripts() {
	$("input.nonJSselector").each(function(){
		$(this).after('<input type="hidden" class="nonJSselector" name="'+$(this).attr("name")+'" value="'+$(this).attr("value")+'" id="'+$(this).attr("id")+'" />').remove();
	})
	$("a.open_sprite_selector").click(function(){
		spriteselectorid = $(this).parent().children(".nonJSselector").eq(0).attr("id");
		window.open('/spriteselector2','mywindow','width=500,height=500,resizable=yes,scrollbars=yes');
		return false;
	})
}

function Wacky_Textile_Finagler() {
    if ($("textarea.wtf").length > 0) {
        $("textarea.wtf").before('	<ul class="buttons wtftabs" style="padding-left: 0;">\n\
        <li class="bold"><a href="#reply"><span style="font-weight:bold;">B</span></a></li>\n\
        <li class="italic"><a href="#reply"><span style="font-style:italic;">I</span></a></li>\n\
        <li class="link"><a href="#reply"><!img class="sprite" style="top: .7em; left: -.4em; width: 1.3em; height: 1.3em;" src="/include/images/forum/button-permalink.png" alt="Link icon" title="Add a Link to your post." /><span style="font-decoration: underline;">Link</span></a></li>\n\
        <li class="ul"><a href="#reply"><span>• List</span></a></li>\n\
        <li class="ol"><a href="#reply"><span>1. List</span></a></li>\n\
        <li class="quote"><a href="#reply"><!img class="sprite" style="top: .7em; left: -.4em; width: 1.3em; height: 1.3em;" src="/include/images/forum/button-quote.png" alt="Quote icon" title="Add a Quote to your post." /><span>Quote</span></a></li>\n\
        <li class="spoilerwtftab"><a href="#reply"><!img class="sprite" style="top: .7em; left: -.4em; width: 1.3em; height: 1.3em;" src="/include/images/forum/button-report.png" alt="Spoiler icon" title="Add a Spoiler to your post." /><span>Spoiler</span></a></li>\n\
        <li class="color"><a href="#reply"><span>Color</span></a></li>\n\
        <li class="size"><a href="#reply"><span>Size</span></a></li>\n\
        </ul>');
        tabs = $("ul.wtftabs")
        tabs.children("li.bold").click(function(){
            textarea = $(this).parents(".wtftabs").eq(0).next("textarea")
            var range = textarea.getSelection();
            textarea.replaceSelection("*"+range.text+"*");
            return false;
        })
        tabs.children("li.italic").click(function(){
            textarea = $(this).parents(".wtftabs").eq(0).next("textarea")
            var range = textarea.getSelection();
            textarea.replaceSelection("_"+range.text+"_");
            return false;
        })
        tabs.children("li.link").click(function(){
            textarea = $(this).parents(".wtftabs").eq(0).next("textarea")
            var range = textarea.getSelection();
            if (range.text.match(/^http\:\/\//)) {
                textarea.replaceSelection("\"Title of Link\":"+range.text);
            }
            else if (range.text.length > 0) {
                textarea.replaceSelection("\""+range.text+"\":http://link.to/your/URL");
            }
            else {
                textarea.replaceSelection("\"Title of Link\":http://link.to/your/URL");
            }
            return false;
        })
        tabs.children("li.ul").click(function(){
            textarea = $(this).parents(".wtftabs").eq(0).next("textarea");
            var range = textarea.getSelection();
            if (range.text.length > 0) {
                textarea.replaceSelection("* "+range.text.replace(/\n(?!\*\s)/g,"\n* "));
            }
            else {
                textarea.replaceSelection(range.text+"\n\n* Item 1\n* Item 2");
            }
            return false;
        })
        tabs.children("li.ol").click(function(){
            textarea = $(this).parents(".wtftabs").eq(0).next("textarea");
            var range = textarea.getSelection();
            if (range.text.length > 0) {
                textarea.replaceSelection("# "+range.text.replace(/\n(?!\#\s)/g,"\n# "));
            }
            else {
                textarea.replaceSelection(range.text+"\n\n# Item 1\n# Item 2");
            }
            return false;
        })
        tabs.children("li.quote").click(function(){
            textarea = $(this).parents(".wtftabs").eq(0).next("textarea");
            var range = textarea.getSelection();
            textarea.replaceSelection("[quote]"+range.text+"[/quote]");
            return false;
        })
        tabs.children("li.spoilerwtftab").click(function(){
            textarea = $(this).parents(".wtftabs").eq(0).next("textarea");
            var range = textarea.getSelection();
            textarea.replaceSelection("[spoiler]"+range.text+"[/spoiler]");
            return false;
        })
        tabs.children("li.color").click(function(){
            textarea = $(this).parents(".wtftabs").eq(0).next("textarea")
            var range = textarea.getSelection();
            textarea.replaceSelection("%{color:#ff00ff;}"+range.text+"%");
            return false;
        })
        tabs.children("li.size").click(function(){
            textarea = $(this).parents(".wtftabs").eq(0).next("textarea")
            var range = textarea.getSelection();
            textarea.replaceSelection("%{font-size:2em;}"+range.text+"%");
            return false;
        })
    }
}

function posting_form() {
  $(function() {
		$('#postingform').uploadProgress({
			/* scripts locations for safari */
			jqueryPath: "/include/javascripts/jquery.js",
			uploadProgressPath: "/include/javascripts/functions.js",
			start:function(){},
			uploading: function(upload) {$('#progressbar').html(upload.percents+'%');},
			interval: 1000
	    });
	});
}

/*function utilities_dropdown() {
  var utils = $('#main ul.utils')
  var dropdown_lis = $('#main ul.utils li.js_dropdown')
  if (dropdown_lis.length > 0) {
    var report = utils.children(".report")
    if (report.length > 0) {
      report.click(function(){
        do_report_popup()
        return false;
      })
    }
    utils.append('<li class="dropdown_link"><a href=""><img src="/include/images/forum/button-report.png"></a></li>')
    utils.parent().after('<div class="dropdown" style="display:none;"><ul class="utils"></ul></div>')
    var dropdown = utils.parent().next(".dropdown").eq(0).children("ul").eq(0)
    //alert(dropdown.html())
    //var text = ""
    dropdown_lis.each(function(){
      $(this).parents(".post").eq(0).children(".dropdown").eq(0).children("ul").eq(0).append($(this))
      //dropdown
      //.appendTo();
    })
    //alert(text);
    //$('#main ul.utils li.js_dropdown').hide();
    utils.children(".dropdown_link").click(function(){
      dropdown_show($(this))
      return false;
    })
  }
}

function do_report_popup() {
  
}

function dropdown_show(thethis){
  thethis.parents(".post").eq(0).children(".dropdown").slideDown()
  thethis.unbind().click(function(){
    dropdown_hide(thethis)
    return false;
  })
  return false;
}

function dropdown_hide(thethis){
  thethis.parents(".post").eq(0).children(".dropdown").slideUp()
  thethis.unbind().click(function(){
    dropdown_show(thethis)
    return false;
  })
  return false;
}*/

function do_report_popup() {
  $('#main ul.utils li.report a').click(function(){
    do_loading();
    $.get($(this).attr("href")+".popup",function(data){
      do_overlay();
      $("#litbox").hide().html(data).slideDown();
      $("#litboxclose").click(function(){
  			close_overlay();
  			return false;
  		})
  		$("#litbox input[type=submit]").click(function(){
  		  form = $(this).parents("form").eq(0);
  		  $.post(form.attr("action"),form.serialize(),function(data){
					if (data.errors) {
					  var output = "There "+(data.errors.length > 1 ? "were" : "was")+" "+data.errors.length+" error"+(data.errors.length > 1 ? "s" : "")+".\n"
					  for (var i = 0; i < data.errors.length; i++) {
					    output += "\n* "+data.errors[i]
					  }
					  alert (output)
					}
					else {
					  $("#litboxbody").html('<div style="margin:2em;font-size:1.5em;">Thank you for submitting report #'+data.id+"! The moderators will respond as soon as possible.</div><div>&nbsp;</div>")
					  setTimeout("close_overlay()",5000)
					}
				},"json")
  		  return false;
  		})
    })
    return false;
  })
  
  $('#main ul.utils li.infract a').click(function(){
    do_loading();
    $.get($(this).attr("href")+".popup",function(data){
      do_overlay();
      $("#litbox").hide().html(data).slideDown();
      $("#litboxclose").click(function(){
  			close_overlay();
  			return false;
  		})
    })
    return false;
  })
}

function do_takereport_popup() {
  do_loading();
  $.get("/forum/reports/open.popup",function(data){
    do_overlay();
    $("#litbox").hide().html(data).slideDown();
    $("#litboxclose").click(function(){
			close_overlay();
			return false;
		})
		$("#report_popup_reference").click(function(){
      do_loading();
		  $.get("/forum/reports/reference/"+$(this).parents("dl").eq(0).attr("id").substring(6)+".popup",function(data2){
		    do_overlay();
		    $("#litbox").hide().html(data2).slideDown();
		    $("#litboxclose").click(function(){
    			do_takereport_popup();
    		})
    		$("#popup_reference_close").click(function(){
    			do_takereport_popup();
    		})
		  })
		  return false;
		})
  })
  return false;
}

function show_deleted_post() {
  $("#main div.post div.deleted.post-not-shown").click(function(){
    $(this).parent().children(".hidden-because-deleted").show();
  })
}

$(document).ready(function(){
  if ($.browser.msie) {
    /*var msie6 = $.browser.version.substring(0,1) == "6";
    
    $('button[@type=submit]').bind('click', function(e) {
      e = $(this);
      if (e.attr('title') != "") {
        e.attr('value',e.attr('title'));
      }
      if (msie6) {
        return confirm("Functionality is limited in IE6. More than likely, it will autopost instead of previewing if you clicked preview. Do you want to continue?")
      }
    });
    
    if (msie6) {
      $('form').submit(function(event) {
        $('button[name!=clicked]').remove();
      });
    }*/
  }
	//new_topic_button();
	setTimeout("insert_poll_button();",0)
	//setTimeout("utilities_dropdown();",0)
	setTimeout("insert_smilie();",10)
	setTimeout("changeable_times()",20)
	setTimeout("show_deleted_post()",20)
	setTimeout("topic_unseen();",30)
	setTimeout("forum_unseen();",40)
	setTimeout("sidebar_search();",50)
	setTimeout("forum_spoilers();",60)
	setTimeout("hide_spritebox_for_javascripts();",70)
	setTimeout("quote_users();",80)
	setTimeout("Wacky_Textile_Finagler();",90)
	setTimeout("posting_form()",100)
	setTimeout("do_report_popup()",110)
});
