function postCase(){
	$('#caseForm').submit();
	$('#captchaMain').hide();
	jQuery(document).trigger('close.facebox')
}
function postComment(){
	$('#commentForm_'+currentKey).submit();
	$('.captcha').hide();
	jQuery(document).trigger('close.facebox')
}
function createApp(which){
	$('#appForm').submit();
	jQuery(document).trigger('close.facebox')
	$('#create_app').hide();
	$('#app_created').show()
}
function submitApp(){
	$('#appForm').submit();
	$('#create_app').hide();
	$('#app_created').show();
}
function quickLight(elm){
	bgcol = elm.css("borderColor")
	elm.css("borderColor","orange");
	setTimeout(function(){
		elm.css("borderColor", bgcol);
	}, 1050);
		
}
function fclick(){
	$('.followLink').click(function(){
		$(this).unbind('click');
		$(this).css("color","gray").css("fontWeight","bold");
		$.get("/follow",{key:$(this).attr('key')},function(data){
			var dog = "nothing";
		});
	});
}
function report(case_id,comment_id){
	$.get("/admin/report",{caseid:case_id,commentid:comment_id},function(data){
		$('#report_'+data).css({"color":"gray","fontWeight":"bold"});
	});
}
function jclick(){
	$('.judgement').click(function(){
		$(this).css("fontWeight","bold");
		$('.j'+$(this).attr('key')).css("color","gray");
		var action = $(this).attr('action');
		var key = $(this).attr('key');
		if(action=="judge"){
			var c = parseInt($("#j_"+key).html())+1;
			$("#j_"+key).html(c);
		}else{
			var c = parseInt($("#nj_"+key).html())+1;
			$("#nj_"+key).html(c);
		}
		$.get("/judge/"+$(this).attr('key'),{action:$(this).attr('action')},function(data){
			var dog = "nothing";
		});
		getComments($(this).attr('key'),$(this).attr("action"));
		$(".j"+key).unbind('click').css("cursor","default");
	})
}
function showRecaptcha(element, themeName) {
  Recaptcha.create("6LdXCgoAAAAAADNGv61Jv0wgvBHf-pyKw4sZPZUJ", element, {
        theme: themeName,
        tabindex: 0,
        callback: Recaptcha.focus_response_field
  });
}
function recapt(key){
	alert(key);
	Recaptcha.create("6LdXCgoAAAAAADNGv61Jv0wgvBHf-pyKw4sZPZUJ", "chtml"+key, {
	        theme: 'red',
	        tabindex: 0,
	        callback: Recaptcha.focus_response_field
	  });
}
var currentKey = "";
function getComments(key,action){
	if(loggedIn){
		$('.loggedOut').hide();
		$('.loggedInVal').val(loggedInPseudo);
	}else{
		$('.loggedIn').hide();
	}
	$('#loader_'+key).show();
	currentKey = key;
	$.get("/comments",{key:key,judgement:action},function(data){
		$("#comments_"+currentKey+",#comments_"+currentKey+"_search").html(data);
		$('#loader_'+key).hide();
		textExpander();
		$('#commentForm_'+currentKey).ajaxForm(function(data) {
			if(data=="captchafail"){
				showRecaptcha('chtml'+currentKey, 'red');
				$('.captchamsg').css('color','red');
			}else{
				$('#postComment_'+currentKey).after(data);
				$('.postInput').val("");
				$('.blurred').show();
				$('.expanding').hide();
				$('.hiddenPost').hide();		
				$('.captcha').hide();
				$('.captchamsg').css('color','black');	
				jclick();
			}
		});
	});
}
function moreCases(offset,view){
	$.get("/"+view,{offset:offset},function(data){
		$('#more_'+offset).after(data);
		$('#more_'+offset).remove();
		cclick();
	});
	
}
function cclick(){
	$('.commentLink').click(function(){
		var key = $(this).attr('key');
		$('#loader_'+key).show();
		currentKey = key;
		$.get("/comments",{key:$(this).attr('key')},function(data){
			$("#comments_"+currentKey+",#comments_"+currentKey+"_search").html(data);
			$('#loader_'+key).hide();
			if(loggedIn){
				$('.loggedOut').hide();
				$('.loggedInVal').val(loggedInPseudo);
			}else{
				$('.loggedIn').hide();
			}
			textExpander();
			$('#commentForm_'+currentKey).ajaxForm(function(data) {
				if(data=="captchafail"){
					showRecaptcha('chtml'+currentKey, 'red');
					$('.captchamsg').css('color','red');
				}else{
					$('#postComment_'+currentKey).after(data);
					$('.postInput').val("");
					$('.blurred').show();
					$('.expanding').hide();
					$('.hiddenPost').hide();
					$('.captcha').hide();					
					$('.captchamsg').css('color','black');
					jclick();
				}
			});
		});
	});
}
function textExpander(){
	$('textarea.blurred').focus(function(){
		$(this).hide();
		if(jQuery.browser.msie){
			$('#'+$(this).attr('which')+" "+'.hiddenPost').show();
			$('#'+$(this).attr('which')+" "+'textarea.expanding').css("height","90px");
			$('#'+$(this).attr('which')+" "+'textarea.expanding').keyup(function(event){
				$('#charCount').html($(this).val().length);
			});
			$('#'+$(this).attr('which')+" "+'textarea.expanding').show().focus();
		}else{
			$('#'+$(this).attr('which')+" "+'.hiddenPost').show();
			$('#'+$(this).attr('which')+" "+'textarea.expanding').show().focus();
			$('textarea.expanding').keyup(function(event){
				$('#charCount').html($(this).val().length);
			});
		}
		
	})
}
function delete_cookie ( cookie_name ){
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  var cookie_string = cookie_name + "=; path=/;expires=" + cookie_date.toGMTString();
  cookie_name += cookie_string;
  document.cookie = cookie_string;
}
function destroySession(){
	pCOOKIES = new Array();
	pCOOKIES = document.cookie.split('; ');
	for(bb = 0; bb < pCOOKIES.length; bb++){
		var NmeVal  = pCOOKIES[bb].split('=');
		if(NmeVal[0]){
			delete_cookie(NmeVal[0]);
		}
	}
}

function expand(elm){
	elm.hide();
	$('#'+elm.attr('which')+" "+'.hiddenPost').show();
	$('#'+elm.attr('which')+" "+'textarea.expanding').show();
}
function atClick(case_id,comment_id,comment_pseudo){
	var elm = $('#blurred_'+case_id);
	elm.hide();
	$('#'+elm.attr('which')+" "+'.hiddenPost').show();
	$('#atPseudo_'+case_id).html(comment_pseudo).attr("href","#"+case_id+"_"+comment_id);
	$('#atPseudo_'+case_id).unbind("click").click(function(){
		quickLight($("#comment_"+case_id+"_"+comment_id));
	});
	$('#at_id_'+case_id).val(comment_id);
	$('#at_pseudo_'+case_id).val(comment_pseudo);
	$('#atContainer_'+case_id).show();
}
var baseService;
function setupBaseService() {baseService = new google.gdata.gbase.GoogleBaseService('5ndr Market');}
function logMeIn(){var scope = 'http://www.google.com/base/feeds';var token = google.accounts.user.login(scope);}
function initFunc() {setupBaseService();logMeIn();}
function showLocalDate(timestamp){
  var dt = new Date(timestamp * 1000);
  var mm = mmToMonth[dt.getMonth()];
  return dt.getDate() + "-" + mm + "-" + dt.getFullYear()+ " "+ dt.getHours() +":" +dt.getMinutes();
}
var refineSearch = false;
var currentFilter = "";
var currentSorter = "";
function stripTags(content){
	var strInputCode = content;
 	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
	 	return (p1 == "lt")? "<" : ">";
	});
	return strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
}
function asearch(tq,filter,sorter){
	setupBaseService();
	var base_query = new google.gdata.gbase.SnippetsQuery('http://www.google.com/base/feeds/snippets');
	var handleError = function(error) {
	  alert(error.message);
	};
	var handleFeed = function(result){
		$('#content').hide();
		var entries = result.feed.entry;
		var term = $('#search').val();
		var totalString = result.feed.getTotalResults().getValue()
		var resultsList = "";
		for(var i = 0, entry; entry = entries[i]; ++i){
			//try{
				var nodetype = entry.getAttribute("nodetype").getValue();
				
				var body = entry.content.getText();
				var shorted = stripTags(body)
				shorted = shorted.substr(0,98)+"..";
				var link = entry.getHtmlLink().href;
				if(nodetype=="comment"){
					var spl = link.split("#comment_");
					var cid = spl[1];
					var caseid = entry.getAttribute("case").getValue();
					var postLi = $('#commentTemplate').html().replace("XcommentlinkX","/posts/"+caseid+"#comment_"+caseid+"_"+cid).replace("XcidX",cid);
					var atlink = "";
					try{
						var atx = entry.getAttribute("at").getValue();
						var at = eval("("+atx+")");
						var atlink = "@<a style='color:green' href='/posts/"+caseid+"#comment_"+caseid+"_"+at.id+"'>"+at.pseudo+"</a> ";
					}catch(err){
						var dog = "nothing";
					}
					body = atlink + "@<a href='/posts/"+caseid+"'>case #"+caseid+"</a> "+body;
				}else{
					var actionA = "Judge me";
					var actionB = "Don't judge me, judger";
					var appid = "Don't Judge Me, Judger";
					try{
						actionA = entry.getAttribute("actiona").getValue();
						actionB = entry.getAttribute("actionb").getValue();
					}catch(err){
						var dog = "nothing";
					}
					try{
						appid = entry.getAttribute("appid").getValue();
					}catch(err){
						var dog = "nothing";
					}
					
					var postLi = $('#postTemplate').html();
					postLi = postLi.replace(/XactionAX/g,actionA).replace(/XactionBX/g,actionB).replace(/XappidX/g,appid);
				}
				var pseudo = entry.getAttribute('pseudo').getValue();
				var time = entry.published;
				time = time.getValue().getDate();
				var month = parseInt(time.getMonth())
				month = (month+1).toString();
				var datex = month+"/"+time.getDate()+"/"+time.getFullYear();
				var hours = time.getHours()-12;
				var ampm = "PM"
				if(hours<0){
					hours = Math.abs(hours);
					ampm = "AM"
				}
				var timex = hours+":"+time.getMinutes()+ampm;
				try{
					var caseid = entry.getAttribute('caseid').getValue();
				}catch(err){
					var split = entry.getTitle().getText().split("#");
					var splitB = split[1].split(":");
					caseid = splitB[0];
				}
				postLi = postLi.replace(/XlinkX/g,link).replace(/XshortX/g,shorted).replace(/XpseudoX/g,pseudo).replace(/XcaseidX/g,caseid).replace(/XcasetextX/g,body).replace(/XcasedateX/g,datex).replace(/XcasetimeX/g,timex);
				resultsList = resultsList + postLi;
				if(nodetype=="case"){
					
				}else{
					var ppop = "";
				}
			//}catch(err){
			//	var dog = "nothing";
			//}
		}
		if(!refineSearch){
			$('#searchResults').html(resultsList+"</div>")
		}else{
			$('#refine').html(resultsList).show();
		}
		$('#searchContainer').show();
		var lights = $('#search').val().split(' ');
		for(var l in lights){
			var light = lights[l];
			if(light.length > 2){
				if(!refineSearch){
					$('#searchResults').highlight(light);
					refineSearch = true;
				}else{
					$('#refine').highlight(light);
					$('#resultCount').html(totalString);
				}
			}
		}
		
		jclick();
		cclick();
		fclick();
	}
	//alert(textQuery);
	nodeType = "";
	var hash = "/hot";
	if(currentFilter){
		filter = currentFilter;
	}
	if(currentSorter){
		sorter = currentSorter;
	}
	if(filter){
		nodeType="[nodetype:"+filter+"]";
		hash = hash + "&filter="+filter;
	}
	
	base_query.setBq(tq+' [item type:anekdotzNode]'+nodeType);
	base_query.setCrowdby("uid(text):1");
	
	base_query.setOrderby("heat(float)");

	base_query.setMaxResults(100);
	document.location.hash = hash;
	baseService.getSnippetsFeed(base_query, handleFeed, handleError);
}
function dsearch(tq,filter,sorter){
	setupBaseService();
	var base_query = new google.gdata.gbase.SnippetsQuery('http://www.google.com/base/feeds/snippets');
	var handleError = function(error) {
	  alert(error.message);
	};
	var handleFeed = function(result){
		$('#content').hide();
		var entries = result.feed.entry;
		var term = $('#search').val();
		var totalString = result.feed.getTotalResults().getValue()
		var resultsList = "";
		
		for(var i = 0, entry; entry = entries[i]; ++i){
			//try{
				var nodetype = entry.getAttribute("nodetype").getValue();
				
				var body = entry.content.getText();
				var shorted = stripTags(body)
				shorted = shorted.substr(0,98)+"..";
				var link = entry.getHtmlLink().href;
				try{
					var appid = entry.getAttribute("appid").getValue();
				}catch(err){
					var appid = "whenyouknew";
				}
				if(nodetype=="comment"){
					var spl = link.split("#comment_");
					var cid = spl[1];
					var caseid = entry.getAttribute("case").getValue();
					var postLi = $('#commentTemplate').html().replace("XcommentlinkX","/posts/"+caseid+"#comment_"+caseid+"_"+cid).replace("XcidX",cid);
					var atlink = "";
					try{
						var atx = entry.getAttribute("at").getValue();
						var at = eval("("+atx+")");
						var atlink = "@<a style='color:green' href='/posts/"+caseid+"#comment_"+caseid+"_"+at.id+"'>"+at.pseudo+"</a> ";
					}catch(err){
						var dog = "nothing";
					}
					body = atlink + "@[<b>"+appid+"</b>]<a href='/posts/"+caseid+"'>case #"+caseid+"</a> "+body;
				}else{
					var actionA = "Judge me";
					var actionB = "Don't judge me, judger";
					try{
						actionA = entry.getAttribute("actiona").getValue();
						actionB = entry.getAttribute("actionb").getValue();
					}catch(err){
						var dog = "nothing";
					}
					
					var postLi = $('#postTemplate').html();
					postLi = postLi.replace(/XactionAX/g,actionA).replace(/XactionBX/g,actionB);
				}

				var pseudo = entry.getAttribute('pseudo').getValue();
				var time = entry.published;
				time = time.getValue().getDate();
				var month = parseInt(time.getMonth())
				month = (month+1).toString();
				var datex = month+"/"+time.getDate()+"/"+time.getFullYear();
				var hours = time.getHours()-12;
				var ampm = "PM"
				if(hours<0){
					hours = Math.abs(hours);
					ampm = "AM"
				}
				var timex = hours+":"+time.getMinutes()+ampm;
				try{
					var caseid = entry.getAttribute('caseid').getValue();
				}catch(err){
					var split = entry.getTitle().getText().split("#");
					var splitB = split[1].split(":");
					caseid = splitB[0];
				}
				postLi = postLi.replace(/XlinkX/g,link).replace(/XappidX/g,appid).replace(/XshortX/g,shorted).replace(/XpseudoX/g,pseudo).replace(/XcaseidX/g,caseid).replace(/XcasetextX/g,body).replace(/XcasedateX/g,datex).replace(/XcasetimeX/g,timex);
				resultsList = resultsList + postLi;
				if(nodetype=="case"){
					
				}else{
					var ppop = "";
				}
			//}catch(err){
			//	var dog = "nothing";
			//}
		}

		$('#searchResults').html(resultsList+"</div>")
		$('#resultCount').html(totalString);
		$('#searchContainer').show();
		var lights = $('#search').val().split(' ');
		for(var l in lights){
			var light = lights[l];
			if(light.length > 2){
				if(!refineSearch){
					$('#searchResults').highlight(light);
					refineSearch = true;
				}else{
					$('#refine').highlight(light);
					$('#resultCount').html(totalString);
				}
			}
		}
		$('.navActive').removeClass('navActive');
		jclick();
		cclick();
		fclick();
	}
	//alert(textQuery);
	nodeType = "";
	var hash = "/search?q="+tq;
	if(currentFilter){
		filter = currentFilter;
	}
	if(currentSorter){
		sorter = currentSorter;
	}
	if(filter){
		nodeType="[nodetype:"+filter+"]";
		hash = hash + "&filter="+filter;
	}else{
		$('.sortActive').addClass('sortInActive').removeClass('sortActive');
		$('#sort_rel').addClass('sortActive');
	}
	
	base_query.setBq(tq+' [item type:judgeNode]'+nodeType);
	
	if(!tq){
		base_query.setOrderby("modification_time");
		hash = hash + "&sort=time";
	}else if(sorter){
		base_query.setOrderby("modification_time");
		hash = hash + "&sort=time";
	}
	base_query.setMaxResults(100);
	document.location.hash = hash;
	baseService.getSnippetsFeed(base_query, handleFeed, handleError);
}
function filter(which,elm){
	currentFilter = which;
	dsearch($('#search').val(),which);
	$('.searchActive').addClass('searchInActive').removeClass('searchActive');
	elm.addClass('searchActive').removeClass('searchInActive');
}
function sorter(which,elm){
	currentSorter = which;
	dsearch($('#search').val(),"",which);
	$('.sortActive').addClass('sortInActive').removeClass('sortActive');
	elm.addClass('sortActive').removeClass('sortInActive');
}
function getSelText(){
	var txt = '';
	if(window.getSelection){
		txt = window.getSelection();
	}else if(document.getSelection){
		txt = document.getSelection();
	}else if(document.selection){
		txt = document.selection.createRange().text;
	}
	return txt;
}
jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
	spannode.id = "highlighted";
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 });
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};

(function(jQuery) {
		  
	var self = null;
 
	jQuery.fn.autogrow = function(o)
	{	
		return this.each(function() {
			new jQuery.autogrow(this, o);
		});
	};
	

    /**
     * The autogrow object.
     *
     * @constructor
     * @name jQuery.autogrow
     * @param Object e The textarea to create the autogrow for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/autogrow
     */
	
	jQuery.autogrow = function (e, o)
	{
		this.options		  	= o || {};
		this.dummy			  	= null;
		this.interval	 	  	= null;
		this.line_height	  	= this.options.lineHeight || parseInt(jQuery(e).css('line-height'));
		this.min_height		  	= this.options.minHeight || parseInt(jQuery(e).css('min-height'));
		this.max_height		  	= this.options.maxHeight || parseInt(jQuery(e).css('max-height'));;
		this.textarea		  	= jQuery(e);
		
		if(this.line_height == NaN)
		  this.line_height = 0;
		
		// Only one textarea activated at a time, the one being used
		this.init();
	};
	
	jQuery.autogrow.fn = jQuery.autogrow.prototype = {
    autogrow: '1.2.2'
  };
	
 	jQuery.autogrow.fn.extend = jQuery.autogrow.extend = jQuery.extend;
	
	jQuery.autogrow.fn.extend({
						 
		init: function() {			
			var self = this;			
			this.textarea.css({overflow: 'hidden', display: 'block'});
			this.textarea.bind('focus', function() { self.startExpand() } ).bind('blur', function() { self.stopExpand() });
			this.checkExpand();	
		},
						 
		startExpand: function() {				
		  var self = this;
			this.interval = window.setInterval(function() {self.checkExpand()}, 400);
		},
		
		stopExpand: function() {
			clearInterval(this.interval);	
		},
		
		checkExpand: function() {
			
			if (this.dummy == null)
			{
				this.dummy = jQuery('<div></div>');
				this.dummy.css({
												'font-size'  : this.textarea.css('font-size'),
												'font-family': this.textarea.css('font-family'),
												'width'      : this.textarea.css('width'),
												'padding'    : this.textarea.css('padding'),
												'line-height': this.line_height + 'px',
												'overflow-x' : 'hidden',
												'position'   : 'absolute',
												'top'        : 0,
												'left'		 : -9999
												}).appendTo('body');
			}
			
			// Strip HTML tags
			var html = this.textarea.val().replace(/(<|>)/g, '');
			
			// IE is different, as per usual
			if ($.browser.msie)
			{
				html = html.replace(/\n/g, '<BR>new');
			}
			else
			{
				html = html.replace(/\n/g, '<br>new');
			}
			
			if (this.dummy.html() != html)
			{
				this.dummy.html(html);	
				
				if (this.max_height > 0 && (this.dummy.height() + this.line_height > this.max_height))
				{
					this.textarea.css('overflow-y', 'auto');	
				}
				else
				{
					this.textarea.css('overflow-y', 'hidden');
					if (this.textarea.height() < this.dummy.height() + this.line_height || (this.dummy.height() < this.textarea.height()))
					{	
						this.textarea.animate({height: (this.dummy.height() + this.line_height) + 'px'}, 100);	
					}
				}
			}
		}
						 
	 });
})(jQuery);
