var rmb = {};

rmb.settings = {};

$(document).ready(function(){
	rmb.initialize();
});

/********** Initialization Functions *********/
rmb.initialize = function(){
	for(var i in rmb.init){
		rmb.init[i]();
	}
};

// Setup Init
rmb.init = {};

// Overall UI
rmb.init.ui = function(){
	$('a[title]').tipsy({delayIn: 100, gravity: 's'});
};

// Overall Forms
rmb.init.forms = function(){
	$("input[type=text]").placeholder();
};

// Mail Check
rmb.mail = {}
rmb.mail.newcount = 0;
rmb.mail.badge = null;
rmb.init.checkmail = function (){
	//rmb.mail.checkfornew();
	//rmb.mail.badge = $('<span class="badge">').appendTo("header .user nav a.inbox");
};
rmb.mail.checkfornew = function (){
	$.getJSON(rmb.settings.baseurl+"mail/get_new_messages",{},function(data){
		if(data.system.success){
			rmb.mail.newcount = data.data;
			rmb.mail.updatebadge();
		}
	});
};
rmb.mail.updatebadge = function (){
	if(rmb.mail.newcount > 0){
		rmb.mail.badge.text(rmb.mail.newcount).show();
	} else {
		rmb.mail.badge.hide();
	}
};


/********** Comments *********/
rmb.init.commentforms = function(){
	var commentform = $("#addcomment");

	commentform.find("input.intro").focus(function(){
		commentform.addClass("focused");
		commentform.find("textarea").focus();
	}).parent().find("textarea[name=comment]").blur(function(){
		if($(this).val() == ""){
			commentform.removeClass("focused");
		}
	});
};


/********** Alerts *********/
rmb.alert = function(msg,type){
	var alertArea = $("#content");
	switch(type){
		case "alert":
			$('<div class="flashdata alert"><span class="icon alert"></span>'+msg+'</div>').prependTo(alertArea);
		break;
		case "error":
			$('<div class="flashdata error"><span class="icon error"></span>'+msg+'</div>').prependTo(alertArea);
		break;
		default:
			$('<div class="flashdata message"><span class="icon info"></span>'+msg+'</div>').prependTo(alertArea);
		break;
	}
	$("html:not(:animated),body:not(:animated)").animate({ scrollTop: alertArea.offset().top-20}, 500 );
};




/********** Helpers and Plugins *********/
// converted from php helper
function truncate(string, limit) {
	var brk = " ";
	var pad = "...";

	// return with no change if string is shorter than $limit
	if(string.length <= limit) return string;
	if(brk != ""){
		// is $break present between $limit and the end of the string?
		if(false !== (breakpoint = string.indexOf(brk, limit))) {
			if(breakpoint < string.length - 1) {
				string = string.substr(0, breakpoint) + pad;
			}
		}
	} else {
		string = string.substr(0, limit) + pad;
	}
	return string;
}

// Strip Space
function stripSpace(text){
	return text.toLowerCase().replace(/[\']+/g,'').replace(/[^a-z0-9]+/g,'-').replace(/\s/g, '-').replace(/^-+|-+$/g, '');
};

/*!
 * jQuery TextChange Plugin
 * http://www.zurb.com/playground/jquery-text-change-custom-event
 *
 * Copyright 2010, ZURB
 * Released under the MIT License
 */
 (function(a){a.event.special.textchange={setup:function(){a(this).data("lastValue",this.contentEditable==="true"?a(this).html():a(this).val());a(this).bind("keyup.textchange",a.event.special.textchange.handler);a(this).bind("cut.textchange paste.textchange input.textchange",a.event.special.textchange.delayedHandler)},teardown:function(){a(this).unbind(".textchange")},handler:function(){a.event.special.textchange.triggerIfChanged(a(this))},delayedHandler:function(){var b=a(this);setTimeout(function(){a.event.special.textchange.triggerIfChanged(b)},
 25)},triggerIfChanged:function(b){var c=b[0].contentEditable==="true"?b.html():b.val();if(c!==b.data("lastValue")){b.trigger("textchange",b.data("lastValue"));b.data("lastValue",c)}}};a.event.special.hastext={setup:function(){a(this).bind("textchange",a.event.special.hastext.handler)},teardown:function(){a(this).unbind("textchange",a.event.special.hastext.handler)},handler:function(b,c){c===""&&c!==a(this).val()&&a(this).trigger("hastext")}};a.event.special.notext={setup:function(){a(this).bind("textchange",
 a.event.special.notext.handler)},teardown:function(){a(this).unbind("textchange",a.event.special.notext.handler)},handler:function(b,c){a(this).val()===""&&a(this).val()!==c&&a(this).trigger("notext")}}})(jQuery);

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * http://blog.stevenlevithan.com/archives/date-time-format
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat=function(){var token=/d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,timezoneClip=/[^-+\dA-Z]/g,pad=function(val,len){val=String(val);len=len||2;while(val.length<len)val="0"+val;return val;};return function(date,mask,utc){var dF=dateFormat;if(arguments.length==1&&Object.prototype.toString.call(date)=="[object String]"&&!/\d/.test(date)){mask=date;date=undefined;}
date=date?new Date(date):new Date;if(isNaN(date))throw SyntaxError("invalid date");mask=String(dF.masks[mask]||mask||dF.masks["default"]);if(mask.slice(0,4)=="UTC:"){mask=mask.slice(4);utc=true;}
var _=utc?"getUTC":"get",d=date[_+"Date"](),D=date[_+"Day"](),m=date[_+"Month"](),y=date[_+"FullYear"](),H=date[_+"Hours"](),M=date[_+"Minutes"](),s=date[_+"Seconds"](),L=date[_+"Milliseconds"](),o=utc?0:date.getTimezoneOffset(),flags={d:d,dd:pad(d),ddd:dF.i18n.dayNames[D],dddd:dF.i18n.dayNames[D+7],m:m+1,mm:pad(m+1),mmm:dF.i18n.monthNames[m],mmmm:dF.i18n.monthNames[m+12],yy:String(y).slice(2),yyyy:y,h:H%12||12,hh:pad(H%12||12),H:H,HH:pad(H),M:M,MM:pad(M),s:s,ss:pad(s),l:pad(L,3),L:pad(L>99?Math.round(L/10):L),t:H<12?"a":"p",tt:H<12?"am":"pm",T:H<12?"A":"P",TT:H<12?"AM":"PM",Z:utc?"UTC":(String(date).match(timezone)||[""]).pop().replace(timezoneClip,""),o:(o>0?"-":"+")+pad(Math.floor(Math.abs(o)/60)*100+Math.abs(o)%60,4),S:["th","st","nd","rd"][d%10>3?0:(d%100-d%10!=10)*d%10]};return mask.replace(token,function($0){return $0 in flags?flags[$0]:$0.slice(1,$0.length-1);});};}();dateFormat.masks={"default":"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:ss",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"};dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"]};Date.prototype.format=function(mask,utc){return dateFormat(this,mask,utc);};


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}
var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}
expires='; expires='+date.toUTCString();}
var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}
return cookieValue;}};


/*
 * jQuery Smooth Scroll plugin
 * Version 1.1  (March 25, 2010)
 * @requires jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses (just like jQuery):
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
(function($){var version='1.1';var locationPath=filterPath(location.pathname);$.fn.extend({smoothScroll:function(options){this.each(function(){var opts=$.extend({},$.fn.smoothScroll.defaults,options);$(this).bind('click',function(event){var link=this,$link=$(this),hostMatch=((location.hostname===link.hostname)||!link.hostname),pathMatch=opts.scrollTarget||(filterPath(link.pathname)||locationPath)===locationPath,thisHash=link.hash&&'#'+link.hash.replace('#',''),include=true;if(!opts.scrollTarget&&(!hostMatch||!pathMatch||thisHash.length==1)){include=false;}else{var exclude=opts.exclude,elCounter=0,el=exclude.length;while(include&&elCounter<el){if($link.is(exclude[elCounter++])){include=false;}}
var excludeWithin=opts.excludeWithin,ewlCounter=0,ewl=excludeWithin.length;while(include&&ewlCounter<ewl){if($link.parents(excludeWithin[ewlCounter++]+':first').length){include=false;}}}
if(include){opts.scrollTarget=opts.scrollTarget||thisHash;opts.link=link;event.preventDefault();$.smoothScroll(opts);}});});return this;}});$.smoothScroll=function(options,px){var opts,scrollTargetOffset,scrollElem=scrollableElement('html','body');if(typeof options==='number'){opts=$.fn.smoothScroll.defaults;scrollTargetOffset=options;}else{opts=$.extend({},$.fn.smoothScroll.defaults,options);scrollTargetOffset=px||$(opts.scrollTarget).offset()&&$(opts.scrollTarget).offset().top||0;}
opts=$.extend({link:null},opts);$(scrollElem).animate({scrollTop:scrollTargetOffset+opts.offset},{duration:opts.speed,easing:opts.easing,complete:function(){if(opts.afterScroll&&$.isFunction(opts.afterScroll)){opts.afterScroll.call(opts.link,opts);}}});};$.smoothScroll.version=version;$.fn.smoothScroll.defaults={exclude:[],excludeWithin:[],offset:0,scrollTarget:null,afterScroll:null,easing:'swing',speed:400};function scrollableElement(els){for(var i=0,argLength=arguments.length;i<argLength;i++){var el=arguments[i],$scrollElement=$(el);if($scrollElement.scrollTop()>0){return el;}else{$scrollElement.scrollTop(1);var isScrollable=$scrollElement.scrollTop()>0;$scrollElement.scrollTop(0);if(isScrollable){return el;}}}
return[];}
function filterPath(string){return string.replace(/^\//,'').replace(/(index|default).[a-zA-Z]{3,4}$/,'').replace(/\/$/,'');}})(jQuery);


/**
 * jQuery.placeholder - Placeholder plugin for input fields
 * Written by Blair Mitchelmore1 (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2008/10/14
 *
 * @author Blair Mitchelmore
 * @version 1.0.1
 *
 **/
new function($){$.fn.placeholder=function(settings){settings=settings||{};var key=settings.dataKey||"placeholderValue";var attr=settings.attr||"placeholder";var className=settings.className||"placeholder";var values=settings.values||[];var block=settings.blockSubmit||false;var blank=settings.blankSubmit||false;var submit=settings.onSubmit||false;var value=settings.value||"";var position=settings.cursor_position||0;return this.filter(":input").each(function(index){$.data(this,key,values[index]||$(this).attr(attr));}).each(function(){if($.trim($(this).val())==="")
$(this).addClass(className).val($.data(this,key));}).focus(function(){if($.trim($(this).val())===$.data(this,key))
$(this).removeClass(className).val(value)
if($.fn.setCursorPosition){$(this).setCursorPosition(position);}}).blur(function(){if($.trim($(this).val())===value)
$(this).addClass(className).val($.data(this,key));}).each(function(index,elem){if(block)
new function(e){$(e.form).submit(function(){return $.trim($(e).val())!=$.data(e,key)});}(elem);else if(blank)
new function(e){$(e.form).submit(function(){if($.trim($(e).val())==$.data(e,key))
$(e).removeClass(className).val("");return true;});}(elem);else if(submit)
new function(e){$(e.form).submit(submit);}(elem);});};}(jQuery);


// tipsy, facebook style tooltips for jquery
// version 1.0.0a
// (c) 2008-2010 jason frame [jason@onehackoranother.com]
// released under the MIT license
(function($){function Tipsy(element,options){this.$element=$(element);this.options=options;this.enabled=true;this.fixTitle();}
Tipsy.prototype={show:function(){var title=this.getTitle();if(title&&this.enabled){var $tip=this.tip();$tip.find('.tipsy-inner')[this.options.html?'html':'text'](title);$tip[0].className='tipsy';$tip.remove().css({top:0,left:0,visibility:'hidden',display:'block'}).appendTo(document.body);var pos=$.extend({},this.$element.offset(),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight});var actualWidth=$tip[0].offsetWidth,actualHeight=$tip[0].offsetHeight;var gravity=(typeof this.options.gravity=='function')?this.options.gravity.call(this.$element[0]):this.options.gravity;var tp;switch(gravity.charAt(0)){case'n':tp={top:pos.top+pos.height+this.options.offset,left:pos.left+pos.width/2-actualWidth/2};break;case's':tp={top:pos.top-actualHeight-this.options.offset,left:pos.left+pos.width/2-actualWidth/2};break;case'e':tp={top:pos.top+pos.height/2-actualHeight/2,left:pos.left-actualWidth-this.options.offset};break;case'w':tp={top:pos.top+pos.height/2-actualHeight/2,left:pos.left+pos.width+this.options.offset};break;}
if(gravity.length==2){if(gravity.charAt(1)=='w'){tp.left=pos.left+pos.width/2-15;}else{tp.left=pos.left+pos.width/2-actualWidth+15;}}
$tip.css(tp).addClass('tipsy-'+gravity);if(this.options.fade){$tip.stop().css({opacity:0,display:'block',visibility:'visible'}).animate({opacity:this.options.opacity});}else{$tip.css({visibility:'visible',opacity:this.options.opacity});}}},hide:function(){if(this.options.fade){this.tip().stop().fadeOut(function(){$(this).remove();});}else{this.tip().remove();}},fixTitle:function(){var $e=this.$element;if($e.attr('title')||typeof($e.attr('original-title'))!='string'){$e.attr('original-title',$e.attr('title')||'').removeAttr('title');}},getTitle:function(){var title,$e=this.$element,o=this.options;this.fixTitle();var title,o=this.options;if(typeof o.title=='string'){title=$e.attr(o.title=='title'?'original-title':o.title);}else if(typeof o.title=='function'){title=o.title.call($e[0]);}
title=(''+title).replace(/(^\s*|\s*$)/,"");return title||o.fallback;},tip:function(){if(!this.$tip){this.$tip=$('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>');}
return this.$tip;},validate:function(){if(!this.$element[0].parentNode){this.hide();this.$element=null;this.options=null;}},enable:function(){this.enabled=true;},disable:function(){this.enabled=false;},toggleEnabled:function(){this.enabled=!this.enabled;}};$.fn.tipsy=function(options){if(options===true){return this.data('tipsy');}else if(typeof options=='string'){var tipsy=this.data('tipsy');if(tipsy)tipsy[options]();return this;}
options=$.extend({},$.fn.tipsy.defaults,options);function get(ele){var tipsy=$.data(ele,'tipsy');if(!tipsy){tipsy=new Tipsy(ele,$.fn.tipsy.elementOptions(ele,options));$.data(ele,'tipsy',tipsy);}
return tipsy;}
function enter(){var tipsy=get(this);tipsy.hoverState='in';if(options.delayIn==0){tipsy.show();}else{tipsy.fixTitle();setTimeout(function(){if(tipsy.hoverState=='in')tipsy.show();},options.delayIn);}};function leave(){var tipsy=get(this);tipsy.hoverState='out';if(options.delayOut==0){tipsy.hide();}else{setTimeout(function(){if(tipsy.hoverState=='out')tipsy.hide();},options.delayOut);}};if(!options.live)this.each(function(){get(this);});if(options.trigger!='manual'){var binder=options.live?'live':'bind',eventIn=options.trigger=='hover'?'mouseenter':'focus',eventOut=options.trigger=='hover'?'mouseleave':'blur';this[binder](eventIn,enter)[binder](eventOut,leave);}
return this;};$.fn.tipsy.defaults={delayIn:0,delayOut:0,fade:false,fallback:'',gravity:'n',html:false,live:false,offset:0,opacity:0.8,title:'title',trigger:'hover'};$.fn.tipsy.elementOptions=function(ele,options){return $.metadata?$.extend({},options,$(ele).metadata()):options;};$.fn.tipsy.autoNS=function(){return $(this).offset().top>($(document).scrollTop()+$(window).height()/2)?'s':'n';};$.fn.tipsy.autoWE=function(){return $(this).offset().left>($(document).scrollLeft()+$(window).width()/2)?'e':'w';};})(jQuery);
