﻿// For toggling input boxes
jQuery.fn.toggleVal=function(focusClass){this.each(function(){$(this).focus(function()
{if($(this).val()==this.defaultValue){$(this).val("")}if(focusClass)
{$(this).addClass(focusClass)}}).blur(function(){if($(this).val()=="")
{$(this).val(this.defaultValue);$(this).removeClass('no_bg')} else {$(this).addClass('no_bg')}
if(focusClass){$(this).removeClass(focusClass)}})})}

// Fix clear type on MSIE
jQuery.fn.fixClearType = function(){return this.each(function(){if(typeof this.style.filter  && this.style.removeAttribute)this.style.removeAttribute("filter");})}

// Override javascript alert with a modal box
function alert(msg) {$('#alert').jqmShow().find('div.content').html(msg);}

$(document).ready(function(){

    $.ajaxSetup ({cache: false});  

	$(".toggle").toggleVal("active");
	if ($(".toggle").val() != '') {$(this).removeClass('no_bg');}
	
	$('.message, .flashMessage').click(function() {$(this).fadeOut('fast');});


	$('textarea').autogrow().textlimit('span.counter',250);
	$('.username').alphanumeric({allow:'-_@.'});
	
	//$("#UserAddForm, #UserLoginForm").validationEngine();

	//$('div.slide_content').hide();
		
	//Toggle the divs
	$('.slider').toggle (function() {
		$('#header').animate({marginTop: "72px"}, 200 ).removeClass('shadow');
		$(this).removeClass('slidedown_bar').addClass('slideup_bar').addClass('shadow').animate({marginBottom: "72px"}, 200 );
	}, function() {
		$('#header').animate({marginTop: "0px"}, 200 ).addClass('shadow');	
		$(this).removeClass('slideup_bar').addClass('slidedown_bar').removeClass('shadow').animate({marginBottom: "0px"}, 200 );
	});


	$('li.all a').click (function() {
		$('.box').show();
		$(this).parents('ul').find('a').removeClass();
		$(this).addClass('focused');
		return false;
	});
		
	$('li.good>a').click (function() {
		$('div[class*=box_bad], div[class*=box_neutral]').fadeOut('fast'); 
		$('.box_good').show();
		$(this).parents('ul').find('a').removeClass();
		$(this).addClass('good_focused');
		return false;
	});
	
	$('li.bad a').click (function() {
		$('.box_good, div[class*=box_neutral]').fadeOut('fast');
		$('.box_bad').show();
		$(this).parents('ul').find('a').removeClass();
		$(this).addClass('bad_focused');	
		return false;
	});
	
	// Rating
	$('.neg, .pos').click (function() {
		rating = $('a',this).attr('title');
		id = ($(this).parents('.box').attr('id')).substr(2);
		user_id = ($(this).parents('.box').children('.author').attr('id')).substr(2);
		str = rating+','+id+','+user_id;
		
		if ($('#karma_box>.karma').text() > 0) {
			 $.post('/deeds/ajax_rate', {
				field: 'content',
				value: str,
				},
				function(response) {
					$('#karma_box>.karma').text($('#karma_box>.karma').text()-Math.abs(rating));
					rate = parseInt($('#d_'+id).find('.rating').text())+parseInt(rating);
					$('#d_'+id).find('.rating').text(rate);
					if (rate > 0) {
						$('#d_'+id).removeClass('box_bad');
						$('#d_'+id).addClass('box_good');
					} else {
						$('#d_'+id).addClass('box_bad');
					}
					alert(response);
			   });
		} else {
			alert('You have no Karma left');
		}
		return false;
	});
		
	$('.rater').hide();
	
    $(".rate").hover(
      function () {
		$(this).children('.rating').hide();
		$(this).children('.rater').show();
      }, 
      function () {
	  	$(this).children('.rater').hide();
	  	$(this).children('.rating').show();
      }
    );

		
	var fadeAlert=function(hash){
	//hash.w.show().fadeOut('4000', function() {hash.o.remove();}); 
	hash.w.show();
	//hash.w.fadeIn('slow', function() {$(this).fadeOut('slow');hash.o.hide();});
	//setTimeout (hash.w.remove(),2000);
	};
	


	
	// Modal boxes
	$('#jLogin').jqm({modal: false, trigger: 'a.login_link'});	
	$('#jSignup').jqm({modal: false, trigger: 'a.signup_link'});	
	$('#jNew').jqm({modal: false, trigger: 'a.new_link'});	

	// Replace default alertbox
	$('#alert').jqm({modal: false, trigger: false,onShow: fadeAlert});

	// Add a new deed
	$('#DeedAddForm').submit(function() {	
		content = $("textarea#DeedContent").val();
		button = $('input[type=submit]', this).attr('disabled');
		if (button == true) {return false;}
		if (content == 'Add a new deed here' || content.length <= 10) {alert('You gotta enter something more substantial.');return false;}
		
		 $.post('/deeds/ajax_add', {
            field: 'content',
            value: content,
            },
               function(response) {
					if (response != 'error') {
						$('.temp_clear').remove();
						$('.box_add').after(
				'<div class="box box_neutral grid_5"><div class="bubble"><a class="delete_this" onclick="return confirm(\'Are you sure you want to delete this deed?\');" href="/deeds/delete/66">X</a>'+response+
				'<div class="rate"><p class="rating">0</p></div></div><div class="author grid_3">by Me <span class="date">Just now</span></div></div>'
				);
						$('#DeedContent').val('Add a new deed here');
						//alert('Deed added');
					} else {
						alert('Oops sorry, something went wrong');
					}
					
               });
			   
		$('input[type=submit]', this).attr('disabled', 'disabled').attr("value", "Wait a sec..."); 
		setTimeout(function(){ $('#submit').removeAttr("disabled"); $('#submit').attr("value", "Add This");}, 5000);
			
		 return false;
	});

	// Check if username already taken
    $('#UserAddForm input#UserUsername').blur( function () {
		$(this).removeClass('required');
		fieldName = $(this).attr('id');
        fieldValue = $(this).val();

		$.post('/users/ajax_validate', {
            field: 'username',
            value: fieldValue
            },
               function(error) {
                   if(error.length != 0) {                
                       //$('#UserAddForm input#UserUsername').after('<div class="error" id="'+ fieldName +'-exists">' + error + '</div>');
                       $('#UserAddForm input#UserUsername').addClass('required').after('<a href="#" class="tooltip error_float" id="'+fieldName+'-exists"><b>'+error+'</b>X</a>');
                   }
                   else {
                       $('#' + fieldName + '-exists').remove();
                   }
        });		   
     });   

	 
}); /* End init */


function loadPiece(href,divName) {    
    $(divName).load(href, {}, function(){
        var divPaginationLinks = divName+" #pagination a";
        $(divPaginationLinks).click(function() {     
            $('deedList').html('<img src=img/ajax-loader.gif />');
			var thisHref = $(this).attr("href");
            loadPiece(thisHref,divName);
            return false;
        });
    });
} 

/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqmodal/)
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * $Version: 07/06/2008 +r13
 */
(function($){$.fn.jqm=function(o){var p={overlay:50,overlayClass:'jqmOverlay',closeClass:'jqmClose',trigger:'.jqModal',ajax:F,ajaxText:'<div align=\"center\"><br /><br /><img src=\"files/loader.gif\" title=\"\"  alt=\"Loading...\"/></div><br />',target:F,modal:F,toTop:F,onShow:F,onHide:F,onLoad:F};return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};if(p.trigger)$(this).jqmAddTrigger(p.trigger);});};$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};$.fn.jqmShow=function(t){return this.each(function(){$.jqm.open(this._jqm,t);});};$.fn.jqmHide=function(t){return this.each(function(){$.jqm.close(this._jqm,t)});};$.jqm={hash:{},open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);if(c.modal){if(!A[0])L('bind');A.push(s);}
else if(c.overlay>0)h.w.jqmAddClose(o);else o=F;h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in{Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}
if(c.ajax){var r=c.target||h.w,u=c.ajax,r=(typeof r=='string')?$(r,h.w):$(r),u=(u.substr(0,1)=='@')?$(t).attr(u.substring(1)):u;r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
else if(cc)h.w.jqmAddClose($(cc,h.w));if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);(c.onShow)?c.onShow(h):h.w.show();e(h);return F;},close:function(s){var h=H[s];if(!h.a)return F;h.a=F;if(A[0]){A.pop();if(!A[0])L('unbind');}
if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();}return F;},params:{}};var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version=="6.0"),F=false,i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i);f(h);},f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return!r;},hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function(){if(!this[c]){this[c]=[];$(this).click(function(){for(var i in{jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};})(jQuery);


/* Text area limiter */
jQuery.fn.textlimit=function(counter_el,thelimit,speed){var charDelSpeed=speed||15;var toggleCharDel=speed!=-1;var toggleTrim=true;var that=this[0];updateCounter();function updateCounter(){jQuery(counter_el).text(thelimit-that.value.length);};this.keypress(function(e){if(this.value.length>=thelimit&&e.charCode!='0')e.preventDefault()}).keyup(function(e){updateCounter();if(this.value.length>=thelimit&&toggleTrim){if(toggleCharDel){that.value=that.value.substr(0,thelimit+100);var init=setInterval
(function(){if(that.value.length<=thelimit){init=clearInterval(init);updateCounter()}
else{that.value=that.value.substring(0,that.value.length-1);jQuery(counter_el).text('trimming...  '+(thelimit-that.value.length));};},charDelSpeed);}
else this.value=that.value.substr(0,thelimit);}});};


/* Textarea Autogrow */
(function(jQuery){var self=null;jQuery.fn.autogrow=function(o)
{return this.each(function(){new jQuery.autogrow(this,o);});};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;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');}
var html=this.textarea.val().replace(/(<|>)/g,'');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);

//Restrict Alphanumeric
(function($){$.fn.alphanumeric=function(p){p=$.extend({ichars:"!@#$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",nchars:"",allow:""},p);return this.each
(function()
{if(p.nocaps)p.nchars+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";if(p.allcaps)p.nchars+="abcdefghijklmnopqrstuvwxyz";s=p.allow.split('');for(i=0;i<s.length;i++)if(p.ichars.indexOf(s[i])!=-1)s[i]="\\"+s[i];p.allow=s.join('|');var reg=new RegExp(p.allow,'gi');var ch=p.ichars+p.nchars;ch=ch.replace(reg,'');$(this).keypress
(function(e)
{if(!e.charCode)k=String.fromCharCode(e.which);else k=String.fromCharCode(e.charCode);if(ch.indexOf(k)!=-1)e.preventDefault();if(e.ctrlKey&&k=='v')e.preventDefault();});$(this).bind('contextmenu',function(){return false});});};$.fn.numeric=function(p){var az="abcdefghijklmnopqrstuvwxyz";az+=az.toUpperCase();p=$.extend({nchars:az},p);return this.each(function()
{$(this).alphanumeric(p);});};$.fn.alpha=function(p){var nm="1234567890";p=$.extend({nchars:nm},p);return this.each(function()
{$(this).alphanumeric(p);});};})(jQuery);