/*
 * jQuery Autocomplete plugin 1.1
 *
 * Copyright (c) 2009 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
 */;(function($){$.fn.extend({autocomplete:function(urlOrData,options){var isUrl=typeof urlOrData=="string";options=$.extend({},$.Autocompleter.defaults,{url:isUrl?urlOrData:null,data:isUrl?null:urlOrData,delay:isUrl?$.Autocompleter.defaults.delay:10,max:options&&!options.scroll?10:150},options);options.highlight=options.highlight||function(value){return value;};options.formatMatch=options.formatMatch||options.formatItem;return this.each(function(){new $.Autocompleter(this,options);});},result:function(handler){return this.bind("result",handler);},search:function(handler){return this.trigger("search",[handler]);},flushCache:function(){return this.trigger("flushCache");},setOptions:function(options){return this.trigger("setOptions",[options]);},unautocomplete:function(){return this.trigger("unautocomplete");}});$.Autocompleter=function(input,options){var KEY={UP:38,DOWN:40,DEL:46,TAB:9,RETURN:13,ESC:27,COMMA:188,PAGEUP:33,PAGEDOWN:34,BACKSPACE:8};var $input=$(input).attr("autocomplete","off").addClass(options.inputClass);var timeout;var previousValue="";var cache=$.Autocompleter.Cache(options);var hasFocus=0;var lastKeyPressCode;var config={mouseDownOnSelect:false};var select=$.Autocompleter.Select(options,input,selectCurrent,config);var blockSubmit;$.browser.opera&&$(input.form).bind("submit.autocomplete",function(){if(blockSubmit){blockSubmit=false;return false;}});$input.bind(($.browser.opera?"keypress":"keydown")+".autocomplete",function(event){hasFocus=1;lastKeyPressCode=event.keyCode;switch(event.keyCode){case KEY.UP:event.preventDefault();if(select.visible()){select.prev();}else{onChange(0,true);}break;case KEY.DOWN:event.preventDefault();if(select.visible()){select.next();}else{onChange(0,true);}break;case KEY.PAGEUP:event.preventDefault();if(select.visible()){select.pageUp();}else{onChange(0,true);}break;case KEY.PAGEDOWN:event.preventDefault();if(select.visible()){select.pageDown();}else{onChange(0,true);}break;case options.multiple&&$.trim(options.multipleSeparator)==","&&KEY.COMMA:case KEY.TAB:case KEY.RETURN:if(selectCurrent()){event.preventDefault();blockSubmit=true;return false;}break;case KEY.ESC:select.hide();break;default:clearTimeout(timeout);timeout=setTimeout(onChange,options.delay);break;}}).focus(function(){hasFocus++;}).blur(function(){hasFocus=0;if(!config.mouseDownOnSelect){hideResults();}}).click(function(){if(hasFocus++>1&&!select.visible()){onChange(0,true);}}).bind("search",function(){var fn=(arguments.length>1)?arguments[1]:null;function findValueCallback(q,data){var result;if(data&&data.length){for(var i=0;i<data.length;i++){if(data[i].result.toLowerCase()==q.toLowerCase()){result=data[i];break;}}}if(typeof fn=="function")fn(result);else $input.trigger("result",result&&[result.data,result.value]);}$.each(trimWords($input.val()),function(i,value){request(value,findValueCallback,findValueCallback);});}).bind("flushCache",function(){cache.flush();}).bind("setOptions",function(){$.extend(options,arguments[1]);if("data"in arguments[1])cache.populate();}).bind("unautocomplete",function(){select.unbind();$input.unbind();$(input.form).unbind(".autocomplete");});function selectCurrent(){var selected=select.selected();if(!selected)return false;var v=selected.result;previousValue=v;if(options.multiple){var words=trimWords($input.val());if(words.length>1){var seperator=options.multipleSeparator.length;var cursorAt=$(input).selection().start;var wordAt,progress=0;$.each(words,function(i,word){progress+=word.length;if(cursorAt<=progress){wordAt=i;return false;}progress+=seperator;});words[wordAt]=v;v=words.join(options.multipleSeparator);}v+=options.multipleSeparator;}$input.val(v);hideResultsNow();$input.trigger("result",[selected.data,selected.value]);return true;}function onChange(crap,skipPrevCheck){if(lastKeyPressCode==KEY.DEL){select.hide();return;}var currentValue=$input.val();if(!skipPrevCheck&&currentValue==previousValue)return;previousValue=currentValue;currentValue=lastWord(currentValue);if(currentValue.length>=options.minChars){$input.addClass(options.loadingClass);if(!options.matchCase)currentValue=currentValue.toLowerCase();request(currentValue,receiveData,hideResultsNow);}else{stopLoading();select.hide();}};function trimWords(value){if(!value)return[""];if(!options.multiple)return[$.trim(value)];return $.map(value.split(options.multipleSeparator),function(word){return $.trim(value).length?$.trim(word):null;});}function lastWord(value){if(!options.multiple)return value;var words=trimWords(value);if(words.length==1)return words[0];var cursorAt=$(input).selection().start;if(cursorAt==value.length){words=trimWords(value)}else{words=trimWords(value.replace(value.substring(cursorAt),""));}return words[words.length-1];}function autoFill(q,sValue){if(options.autoFill&&(lastWord($input.val()).toLowerCase()==q.toLowerCase())&&lastKeyPressCode!=KEY.BACKSPACE){$input.val($input.val()+sValue.substring(lastWord(previousValue).length));$(input).selection(previousValue.length,previousValue.length+sValue.length);}};function hideResults(){clearTimeout(timeout);timeout=setTimeout(hideResultsNow,200);};function hideResultsNow(){var wasVisible=select.visible();select.hide();clearTimeout(timeout);stopLoading();if(options.mustMatch){$input.search(function(result){if(!result){if(options.multiple){var words=trimWords($input.val()).slice(0,-1);$input.val(words.join(options.multipleSeparator)+(words.length?options.multipleSeparator:""));}else{$input.val("");$input.trigger("result",null);}}});}};function receiveData(q,data){if(data&&data.length&&hasFocus){stopLoading();select.display(data,q);autoFill(q,data[0].value);select.show();}else{hideResultsNow();}};function request(term,success,failure){if(!options.matchCase)term=term.toLowerCase();var data=cache.load(term);if(data&&data.length){success(term,data);}else if((typeof options.url=="string")&&(options.url.length>0)){var extraParams={timestamp:+new Date()};$.each(options.extraParams,function(key,param){extraParams[key]=typeof param=="function"?param():param;});$.ajax({mode:"abort",port:"autocomplete"+input.name,dataType:options.dataType,url:options.url,data:$.extend({q:lastWord(term),limit:options.max},extraParams),success:function(data){var parsed=options.parse&&options.parse(data)||parse(data);cache.add(term,parsed);success(term,parsed);}});}else{select.emptyList();failure(term);}};function parse(data){var parsed=[];var rows=data.split("\n");for(var i=0;i<rows.length;i++){var row=$.trim(rows[i]);if(row){row=row.split("|");parsed[parsed.length]={data:row,value:row[0],result:options.formatResult&&options.formatResult(row,row[0])||row[0]};}}return parsed;};function stopLoading(){$input.removeClass(options.loadingClass);};};$.Autocompleter.defaults={inputClass:"ac_input",resultsClass:"ac_results",loadingClass:"ac_loading",minChars:1,delay:400,matchCase:false,matchSubset:true,matchContains:false,cacheLength:10,max:100,mustMatch:false,extraParams:{},selectFirst:true,formatItem:function(row){return row[0];},formatMatch:null,autoFill:false,width:0,multiple:false,multipleSeparator:", ",highlight:function(value,term){return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)("+term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi,"\\$1")+")(?![^<>]*>)(?![^&;]+;)","gi"),"<strong>$1</strong>");},scroll:true,scrollHeight:180};$.Autocompleter.Cache=function(options){var data={};var length=0;function matchSubset(s,sub){if(!options.matchCase)s=s.toLowerCase();var i=s.indexOf(sub);if(options.matchContains=="word"){i=s.toLowerCase().search("\\b"+sub.toLowerCase());}if(i==-1)return false;return i==0||options.matchContains;};function add(q,value){if(length>options.cacheLength){flush();}if(!data[q]){length++;}data[q]=value;}function populate(){if(!options.data)return false;var stMatchSets={},nullData=0;if(!options.url)options.cacheLength=1;stMatchSets[""]=[];for(var i=0,ol=options.data.length;i<ol;i++){var rawValue=options.data[i];rawValue=(typeof rawValue=="string")?[rawValue]:rawValue;var value=options.formatMatch(rawValue,i+1,options.data.length);if(value===false)continue;var firstChar=value.charAt(0).toLowerCase();if(!stMatchSets[firstChar])stMatchSets[firstChar]=[];var row={value:value,data:rawValue,result:options.formatResult&&options.formatResult(rawValue)||value};stMatchSets[firstChar].push(row);if(nullData++<options.max){stMatchSets[""].push(row);}};$.each(stMatchSets,function(i,value){options.cacheLength++;add(i,value);});}setTimeout(populate,25);function flush(){data={};length=0;}return{flush:flush,add:add,populate:populate,load:function(q){if(!options.cacheLength||!length)return null;if(!options.url&&options.matchContains){var csub=[];for(var k in data){if(k.length>0){var c=data[k];$.each(c,function(i,x){if(matchSubset(x.value,q)){csub.push(x);}});}}return csub;}else
if(data[q]){return data[q];}else
if(options.matchSubset){for(var i=q.length-1;i>=options.minChars;i--){var c=data[q.substr(0,i)];if(c){var csub=[];$.each(c,function(i,x){if(matchSubset(x.value,q)){csub[csub.length]=x;}});return csub;}}}return null;}};};$.Autocompleter.Select=function(options,input,select,config){var CLASSES={ACTIVE:"ac_over"};var listItems,active=-1,data,term="",needsInit=true,element,list;function init(){if(!needsInit)return;element=$("<div/>").hide().addClass(options.resultsClass).css("position","absolute").appendTo(document.body);list=$("<ul/>").appendTo(element).mouseover(function(event){if(target(event).nodeName&&target(event).nodeName.toUpperCase()=='LI'){active=$("li",list).removeClass(CLASSES.ACTIVE).index(target(event));$(target(event)).addClass(CLASSES.ACTIVE);}}).click(function(event){$(target(event)).addClass(CLASSES.ACTIVE);select();input.focus();return false;}).mousedown(function(){config.mouseDownOnSelect=true;}).mouseup(function(){config.mouseDownOnSelect=false;});if(options.width>0)element.css("width",options.width);needsInit=false;}function target(event){var element=event.target;while(element&&element.tagName!="LI")element=element.parentNode;if(!element)return[];return element;}function moveSelect(step){listItems.slice(active,active+1).removeClass(CLASSES.ACTIVE);movePosition(step);var activeItem=listItems.slice(active,active+1).addClass(CLASSES.ACTIVE);if(options.scroll){var offset=0;listItems.slice(0,active).each(function(){offset+=this.offsetHeight;});if((offset+activeItem[0].offsetHeight-list.scrollTop())>list[0].clientHeight){list.scrollTop(offset+activeItem[0].offsetHeight-list.innerHeight());}else if(offset<list.scrollTop()){list.scrollTop(offset);}}};function movePosition(step){active+=step;if(active<0){active=listItems.size()-1;}else if(active>=listItems.size()){active=0;}}function limitNumberOfItems(available){return options.max&&options.max<available?options.max:available;}function fillList(){list.empty();var max=limitNumberOfItems(data.length);for(var i=0;i<max;i++){if(!data[i])continue;var formatted=options.formatItem(data[i].data,i+1,max,data[i].value,term);if(formatted===false)continue;var li=$("<li/>").html(options.highlight(formatted,term)).addClass(i%2==0?"ac_even":"ac_odd").appendTo(list)[0];$.data(li,"ac_data",data[i]);}listItems=list.find("li");if(options.selectFirst){listItems.slice(0,1).addClass(CLASSES.ACTIVE);active=0;}if($.fn.bgiframe)list.bgiframe();}return{display:function(d,q){init();data=d;term=q;fillList();},next:function(){moveSelect(1);},prev:function(){moveSelect(-1);},pageUp:function(){if(active!=0&&active-8<0){moveSelect(-active);}else{moveSelect(-8);}},pageDown:function(){if(active!=listItems.size()-1&&active+8>listItems.size()){moveSelect(listItems.size()-1-active);}else{moveSelect(8);}},hide:function(){element&&element.hide();listItems&&listItems.removeClass(CLASSES.ACTIVE);active=-1;},visible:function(){return element&&element.is(":visible");},current:function(){return this.visible()&&(listItems.filter("."+CLASSES.ACTIVE)[0]||options.selectFirst&&listItems[0]);},show:function(){var offset=$(input).offset();element.css({width:typeof options.width=="string"||options.width>0?options.width:$(input).width(),top:offset.top+input.offsetHeight,left:offset.left}).show();if(options.scroll){list.scrollTop(0);list.css({maxHeight:options.scrollHeight,overflow:'auto'});if($.browser.msie&&typeof document.body.style.maxHeight==="undefined"){var listHeight=0;listItems.each(function(){listHeight+=this.offsetHeight;});var scrollbarsVisible=listHeight>options.scrollHeight;list.css('height',scrollbarsVisible?options.scrollHeight:listHeight);if(!scrollbarsVisible){listItems.width(list.width()-parseInt(listItems.css("padding-left"))-parseInt(listItems.css("padding-right")));}}}},selected:function(){var selected=listItems&&listItems.filter("."+CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);return selected&&selected.length&&$.data(selected[0],"ac_data");},emptyList:function(){list&&list.empty();},unbind:function(){element&&element.remove();}};};$.fn.selection=function(start,end){if(start!==undefined){return this.each(function(){if(this.createTextRange){var selRange=this.createTextRange();if(end===undefined||start==end){selRange.move("character",start);selRange.select();}else{selRange.collapse(true);selRange.moveStart("character",start);selRange.moveEnd("character",end);selRange.select();}}else if(this.setSelectionRange){this.setSelectionRange(start,end);}else if(this.selectionStart){this.selectionStart=start;this.selectionEnd=end;}});}var field=this[0];if(field.createTextRange){var range=document.selection.createRange(),orig=field.value,teststring="<->",textLength=range.text.length;range.text=teststring;var caretAt=field.value.indexOf(teststring);field.value=orig;this.selection(caretAt,caretAt+textLength);return{start:caretAt,end:caretAt+textLength}}else if(field.selectionStart!==undefined){return{start:field.selectionStart,end:field.selectionEnd}}};})(jQuery);

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	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(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		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])];

		// Look for rgb(num%,num%,num%)
		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];

		// Look for #a0b1c2
		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)];

		// Look for #fff
		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)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	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.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 * $Version: 07/06/2008 +r13
 */
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
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);


/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();

/*
Copyright (c) <year> <copyright holders>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Author: Dj Gilcrease

*/
(function($){
    var settings = {
        quality: 'high'
    };
    var events = {
        play_audio: function(evt) {
            var self = $(this);
            var movie = self.data("sound.get_movie")(self.data("sound.settings").id);
            var start = (self.data("sound.paused")) ? self.data("sound.paused") : 0;
            movie.play();
            self.data("sound.isPlaying", true);
        },
        pause_audio: function(evt) {
            var self = $(this);
            var movie = self.data("sound.get_movie")(self.data("sound.settings").id);
            movie.pause();
            self.data("sound.isPlaying", false);
        },
        stop_audio: function(evt) {
            var self = $(this);
            var movie = self.data("sound.get_movie")(self.data("sound.settings").id);
            movie.stop();
            self.data("sound.paused", 0);
            self.data("sound.isPlaying", false);
        },
        volume: function(evt, vol) {
            if(vol > 100) {
                vol = vol - 100;
            }

            var self = $(this);
            var movie = self.data("sound.get_movie")(self.data("sound.settings").id);
            movie.volume(vol);
        },
        load_audio: function(evt, url) {
            var self = $(this);
            var movie = self.data("sound.get_movie")(self.data("sound.settings").id);
            if (movie && movie.load) { movie.load(url); } // in case of flashblock :)
        },
        error: function(evt, err) {
            log(err.msg);
        }
    };

    $.sound_count = 1;

    var methods = {
        sound: function sound(user_settings) {
            var self = $(this);

            if(self.data("sound.settings")) {
                settings = self.data("sound.settings");
            }

            settings = $.extend(user_settings, settings);

            if(user_settings.error) {
                self.unbind("sound.error");
                self.bind("sound.error", user_settings.error);
                delete events.error;
            }

            for(var event in events) {
                self.unbind(event);
                self.bind("sound." + event, events[event]);
            }

            if(!self.data("sound")) {
                settings.id = 'sound_player_' + $.sound_count;

                /*
                var html = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';
                html += ' codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="0" height="0"';
                html += ' id="' + settings.id + '"';
                html += ' align="middle">';
                html += '<param name="movie" value="' + settings.swf + '" />';
                html += '<param name="quality" value="' + settings.quality + '" />';
                html += '<param name="FlashVars" value="id=' + settings.id + '"/>';
                html += '<param name="allowScriptAccess" value="always"/>';
                html += '<embed src="' + settings.swf + '" FlashVars="id='+ settings.id +'"';
                html += ' allowScriptAccess="always" quality="' + settings.quality + '" bgcolor="#ffffff" width="0" height="0"';
                html += ' name="' + settings.id + '" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';

                html += '</object>';
                */

                /* now using swfobject instead of manually composing html */
                var flashparams = {movie:settings.swf,allowscriptaccess:'always',flashvars:'id='+settings.id};
                var flashvars = {id:settings.id};
                var attrs = {id:settings.id};
                swfobject.embedSWF(settings.swf, self.attr('id'), '1', '1', '8.0.0', false, flashvars, flashparams, attrs);

                var get_movie = function(id) {
                    var movie = null;
                    if ($.browser.msie) {
                        movie =  window[id];
                    } else {
                        movie = document[id];
                    }
                    return movie;
                };

                self.data("sound.get_movie", get_movie);

                //self.html(html);
                self.data("sound", true);

                $.sound_count++;
            }

            self.data("sound.settings", settings);

            if(settings.file) {
                var delayed = function() {
                    self.load_audio(settings.file);
                };
                setTimeout(delayed, 250);
            }

            return self;
        },
        play_audio: function() {
            var self = $(this);
            if(self.data("sound")) {
                self.trigger("sound.play");
            } else {
                events.error(null, {msg: "You have not yet bound the sound player to this element"});
            }
        },
        pause_audio: function() {
            var self = $(this);
            if(self.data("sound")) {
                self.trigger("sound.pause");
            } else {
                events.error(null, {msg: "You have not yet bound the sound player to this element"});
            }
        },
        stop_audio: function() {
            var self = $(this);
            if(self.data("sound")) {
                self.trigger("sound.stop");
            } else {
                events.error(null, {msg: "You have not yet bound the sound player to this element"});
            }
        },
        volume: function(vol) {
            var self = $(this);
            if(self.data("sound")) {
                self.trigger("sound.volume", vol);
            } else {
                events.error(null, {msg: "You have not yet bound the sound player to this element"});
            }
        },
        load_audio: function(url) {
            var self = $(this);
            if(self.data("sound")) {
                self.trigger("sound.load_audio", url);
            } else {
                events.error(null, {msg: "have not yet bound the sound player to this element"});
            }
        }
    };
    $.each(methods, function(i) {
        $.fn[i] = this;
    });
})(jQuery);


/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */

var MQ = new function() {

	(function($) {
      $.fn.wait = function(duration) {
        $(this).animate({ dummy: 1 }, duration);
        return this;
      };
      $.fn.disable_enter_key = function() {
        return this.keypress(function(e) { if (e.which == 13) { return false; } });
      };
	    $.fn.yellowFade = function(bg_hex) {
				bg_hex = (bg_hex || "#FFFFFF");
				return this.css({backgroundColor: "#ffffcc"})
						.animate({backgroundColor: bg_hex}, 5000, "linear"); }
      $.fn.marquee = function() {
        var alert_set = this;
        var all_news = jq('.all_news');
        function activate(i) {
          all_news.scrollTo(alert_set[i], {duration:500, onAfter:function() {
            setTimeout(function() { 
              activate((i+1)%alert_set.length);
            }, 5000);
          }});
        }
        activate(0);
      }
      $.fn.floatify = function() {
        var elt = this;
        var sidebar_offset = (elt.offset().top-35);
        jq(window).scroll(function() {
          elt.animate({'marginTop':Math.max(0,(jq(window).scrollTop()-sidebar_offset))}, {queue: false, duration: 350, easing: 'easeOutBack'}); 
        });
      }
  })(jQuery);
  function log(msg) {
    if (MQ.debug) {
      if (typeof console != 'undefined') {
        try {
          console.warn(msg);
        }
        catch (e) {}
      }
    }
  }
  window.log = log;

  this.debug = false;
	this.q_mode = "play"; // or "browse"
	this.current_tag;
	this.menu = new function() {
		function find_menu_container(elt) { return (jq(elt).hasClass('menu_container') ? jq(elt) : jq(elt).parents('.menu_container:first')); }
		this.open = function(elt) { 
      var menu_container = find_menu_container(elt);
      menu_container.data('open',true);
      setTimeout(function(){
        if (menu_container.data('open')) { 
          //menu_container.addClass('hover'); 
          /*jq('.menu:first', menu_container).slideDown('fast');*/
          jq('.menu:first', menu_container).show();
        }
      }, 100);
    }
		this.close = function(elt) { 
      var menu_container = find_menu_container(elt);
      menu_container.data('open',false);
      setTimeout(function(){
        if (!menu_container.data('open')) { 
          /*jq('.menu:first', menu_container).slideUp('fast');*/
          jq('.menu:first', menu_container).hide();
       // menu_container.removeClass('hover'); 
        }
      }, 100);
    }
		//this.toggle = function(elt) { find_menu_container(elt).toggleClass('hover'); }
	}
	this.popup = new function() {
		this.open = function(elt_id_stub, next_url) { 
      MQ.tracker.popup.open(elt_id_stub);
      jq('#'+elt_id_stub+'_popup').jqmShow(); 
      if (next_url) {
        jq('.next_url').val(next_url);
      }
    }
		this.close = function(elt_id_stub) { 
      MQ.tracker.popup.close(elt_id_stub);
      jq('#'+elt_id_stub+'_popup').jqmHide(); 
    }
		this.close_open = function(close_elt_id_stub, open_elt_id_stub) { 
      MQ.popup.close(close_elt_id_stub);
      MQ.popup.open(open_elt_id_stub);
    }
	}
	this.ajax = function(url, params, callback, type) {
	  type = type || 'html';
		jq.post(url,params,callback,type);
	}
	this.close = function(elt, callback) { jq(elt).slideUp('fast', callback); }
	this.open = function(elt, callback) { jq(elt).slideDown({duration:'fast', /*easing:'easeOutBounce',*/complete:callback}); }
	this.questions = [];
	this.comments = [];
	this.find = function(id, type) {
    type = (type || 'questions');
		var result;
		jq.each(MQ[type], function(i,x) {
			if (x.id==id) {
				result=x;
			}
		});
		return result;
	}
  this.answer_hover = function(elt, is_hovering) {
    var tr = jq(elt).parent();
    (is_hovering ? tr.addClass('hover') : tr.removeClass('hover'));
    if (jq('input',tr)[0]) {
      jq('input', tr)[0].checked = is_hovering;
    }
  }

  this.c = function(options) {
		this.id = options.id;
    this.qid = options.qid;
		this.body = jq('#comment_'+this.id);
    if (options && options.vote_state) { this.body.removeClass('unvoted').addClass(options.vote_state); }
    if (options && options.vote_count) { 
      this.body.find('.qscore.unvoted').html(options.vote_count);
      this.body.find('.qscore.liked').html(options.vote_count+1);
      this.body.find('.qscore.disliked').html(options.vote_count-1);
    }
    MQ.comments.push(this);
  }
	this.q = function(qid, options) {
		this.qid = qid;
    this.id = qid; 
		var t0 = new Date();
		this.q_elt = jq('#q'+qid).closest('li.q');
    this.body = this.q_elt;
		this.answered = !this.q_elt.hasClass('unplayed');
    if (options && options.liked) { this.q_elt.find('.favoriter').addClass('on'); }
    if (options && options.vote_state) { this.q_elt.removeClass('unvoted').addClass(options.vote_state); }
    if (options && options.vote_count) { 
      jq('#q'+qid+' .qscore.unvoted').html(options.vote_count);
      jq('#q'+qid+' .qscore.liked').html(options.vote_count+1);
      jq('#q'+qid+' .qscore.disliked').html(options.vote_count-1);
    }
    this.type = ((options && options.type) ? options.type : 'fact');
		this.innards = jq('#q'+qid+'_innards');
		var answers_container = jq('#'+qid+'_answers_container');
		var header = jq('#'+qid+'_header .the_question');
		this.top_drawer = new function() {
			this.elt = jq('#'+qid+'_top_drawer');
			this.open = function() { top_drawer.slideDown('fast'); }
			this.close = function() { top_drawer.slideUp('fast'); }
    }
		this.drawer = new function() {
			this.elt = jq('#'+qid+'_drawer');
			this.update = function() { 
				drawer.load('/questions/fetch_drawer', {'qid':qid}, function(){ 
					//MQ.user.update_leaderboards();
				}); 
			}
			this.open = function() { 
				drawer.slideDown(400); 
				jq('#'+qid+'_drawer_toggle a').toggle();
			}
			this.close = function() { 
				drawer.slideUp(400); 
				jq('#'+qid+'_drawer_toggle a').toggle();
			}
		}
		var drawer = this.drawer.elt;
		var top_drawer = this.top_drawer.elt;

    this.vote = function(elt, is_upvote){ MQ.vote('questions', qid, is_upvote);}
		this.send_feedback = function(category, feedback_type, feedback_elt) {
      if (!MQ.user.logged_in) {
        MQ.popup.open('login_form');
        return false;
      }
			jq(feedback_elt).toggleClass('on');
			var url = "/questions/" + category;
			var params = {type:feedback_type, q:qid};
      if (category=='add_to_favorites') {
        jq(this.q_elt).effect('transfer', {to:jq('.likes_link')}, 750);
        jq('.ui-effects-transfer').css('background','#FDFF4F');
        MQ.utils.increment_html('.likes_count');
      }
			MQ.ajax(url, params, function(r){
        MQ.notice.show(r, 20000);
        if (category=='give_props') {
          MQ.find(qid).fb_share(feedback_type);
        }
      });
      MQ.tracker.question.send_feedback(category, feedback_type);
		}

		// handlers for who knew it - next/prev buttons
    this.whoknew_handlers = new function() {
      var slide = function(jq_elt, direction) {
        jq_elt.animate({left: (direction=='r' ? '+=' : '-=')+jq('#'+qid+'_whoknew').width()});
      }
      this.prev = function() {
        var whoknew_ul = jq('#'+qid+'_whoknew ul');
          if (whoknew_ul.position().left==0) { return false; }
          else { slide(whoknew_ul, 'r') }
      }
      this.next = function() {
        var whoknew_ul = jq('#'+qid+'_whoknew ul');
        slide(whoknew_ul, 'l');
        // get more users, ajaxily
        MQ.ajax('/questions/whoknew',{o:jq("#"+qid+"_whoknew li").length, q:qid}, function(html){
          whoknew_ul.append(html);
        }, 'html');
      }
    }
    this.fadein = function(callback) {
      var thisq = this;
      thisq.body.fadeIn(200, function() {
        if (thisq.next()) {
          thisq.next().fadein();
        }
      });
      if (callback) { callback(); }
    }

		function index(q) { return jq.inArray(q,MQ.questions); } 

		this.prev = function() { return ((index(this)==0) ? null : MQ.questions[index(this)-1]); }
		this.next = function() { return ((index(this)==(MQ.questions.length-1)) ? null : MQ.questions[index(this)+1]); }
		this.hide = function(options) { 
      //MQ.audio.play('card_close');
			this.drawer.close();
      var callback = ((options && options.callback) ? options.callback : false);
			MQ.close(this.innards, callback); 
		}
		this.show = function() { 
      //MQ.audio.play('card_open');
			if (!this.q_elt.is(':visible')) { MQ.open(this.q_elt); }
      var this_drawer = this.drawer;
      var this_innards = this.innards;
			MQ.open(this.innards, function(){
        //if (drawer.html()=='' && MQ.q_mode!='quiz') { this_drawer.update(); }
      });
      var offset = (this_innards.offset().top-jq(document).scrollTop());
      if (MQ.q_mode=='browse' && offset>350) { 
        jq.scrollTo("+="+(offset/3)+"px", 500) 
      }
		}
		this.toggle = function() {
			this.innards.is(':visible') ? this.hide() : this.show();
		}
		this.skip = function() {
			MQ.close(answers_container);
			jq('#'+qid+'_skip .button_m').html('Skipped');
			this.answer_question();
		}
    this.kill = function() {
      if (confirm("Are you sure you want to delete this question?")) {
        MQ.ajax('/questions/delete', {id:qid}, function(r) {
          log(r);
          if (r['ok']) {
            MQ.find(qid).q_elt.html(r.html);
          }
          else {
            MQ.notice.show("Oops, something went wrong.", 5000, 'wrong');
          }
        }, 'json');
      }
    }
		this.destroy = function() {
			this.q_elt.fadeOut('slow').remove();
			MQ.questions.splice(index(this),1);
		}
		this.change_status = function(q_status) {
			this.q_elt.removeClass('unplayed');
			this.q_elt.addClass(q_status);
		}
    function populate_results(answer_ary, response_count) {
      var answer_html = '';
      var pie_data = [];
      var pie_colors = [];
      jq.each(answer_ary, function(i,a) {
        var a_percent = MQ.utils.to_percent(parseFloat(a['response_count'])/parseFloat(response_count));
        pie_data.push(a_percent);
        pie_colors.push(a['pie_color']);
        answer_html += MQ.h("tr",false,[
          MQ.h('td', "valign='top'", MQ.h('div', "class=color style=background:#"+a['pie_color'], '')),
          MQ.h('td', false, MQ.h('p', false, [
            a['text'], 
            (a['user_answer'] ? MQ.h('span','class=red',' &laquo; Your answer') : ''),
            MQ.h('br'), 
            MQ.h('span', false, a['response_count']+(a['response_count']==1 ? ' person' : ' people')+" ("+a_percent+"%)")
          ]))
        ])
      });
      jq('#'+qid+'_qpie').html(MQ.h('img', "src='http://chart.apis.google.com/chart?cht=p&chf=bg,s,FAFAFA&chd=t:"+pie_data.join(',')+"&chs=100x100&chco="+pie_colors.join(',')+"' alt='Pie chart'")), 
      jq('#'+qid+'_qpie_labels').html(MQ.h('table',false,answer_html));
    }
		this.answer_question = function(a) {
      jq('#'+qid+'_q_loading').fadeIn('slow');
      jq('.welcome_msg').slideUp();
			jq('a','#'+qid+'_answers_container').removeAttr('onclick').click(function(){return false;});
			if (MQ.q_mode!='browse' && this.prev()) { this.prev().destroy() };
			this.hide();
			this.answered=true;
			var t1 = new Date();
			var t = (t1.getTime() - t0)/1000; 
			var params = {'a':a,'answered_qid':this.qid,'t':t,'mode':MQ.q_mode};
			if (MQ.current_tag) { params['tag_id'] = MQ.current_tag; }
      if (jq('.quiz_tweet_results').is(':visible')) {
        params['tweet_results'] = jq('.quiz_tweet_results input:checkbox').is(':checked');
        jq('.quiz_tweet_results').hide();
      }
      var guess_url = (MQ.q_mode=='quiz' ? '/quiz/guess' : '/play/guess');
			var callback = function(data) {
        log(data);
        if (data.error) {
          MQ.notice.show(data.error, 10000, "wrong");
          MQ.audio.play('wrong');
          jq('#'+qid+'_q_loading').fadeOut('slow');
          return false;
        }
        if (MQ.q_mode=='quiz') {
          if (jq('.quiz_num_played').html()==jq('.quiz_length').html()) {
            setTimeout(function(){ jq('.quiz_get_results').slideDown();}, 2000);
          } 
          else {
            MQ.utils.increment_html('.quiz_num_played');
            if (jq('.quiz_num_played').html()==jq('.quiz_length').html()) {
              jq('.quiz_tweet_results').show();
            }
          }
        }
				var answered_qid = data.answered_q.qid;
				var answered_q = MQ.find(answered_qid);
        var result = data.answered_q.result;
				answered_q.change_status(result);
				MQ.utils.decrement_html('span.unplayed_count');
				if (result=='skipped') {
					MQ.utils.increment_html('span.skip_count');
					//show skip topics
          jq('#q'+qid+' .block_link').show();
					jq('#q' + answered_qid).prepend(data.answered_q.innards);
          var tooltip = jq('#q'+answered_qid + ' .skiptip');
          var block_link = jq('#q'+answered_qid+' .block_link')[1];
          if (block_link) {
            block_link = jq(block_link);
            tooltip.css({'top':(block_link.position().top-tooltip.height()-7),
                         'left':(block_link.position().left-(tooltip.width()/2)+2)
                });
          }
          setTimeout(function(){tooltip.fadeIn('slow')}, 1500);
					drawer.html('');
				}
				else {
          jq('#q'+answered_qid+' .skipper').hide();
          jq('#q'+answered_qid+' .favoriter').show();
					// answered question
					answered_q.innards.html(data.answered_q.innards);
					jq('#' + answered_qid + "_drawer_toggle").show();
					answered_q.show();
          populate_results(data.answered_q.answers, data.answered_q.response_count);
					// user updates
					if (result=='right' || answered_q.type=='poll') { 
            MQ.audio.play('right');
            jq('#'+answered_qid+'_whoknew_list').prepend("<li>"+MQ.user.userdiv+"</li>");  // add user to whoknew
          } else {
            MQ.audio.play('wrong');
          }
          setTimeout(function() {
            MQ.user.update_score(data.user.points, {type:answered_q.type, level_percent_array:data.user.level_percent_array});
          }, 1000);
					MQ.user.update_pc(result=='right');
          MQ.user.uid = data.user.uid;
          MQ.user.login = (data.user.login || '');
          var top_draw = jq('#'+answered_qid+"_top_drawer");
          if (top_draw.length>0 && FB.XFBML && FB.XFBML.Host && FB.XFBML.Host.parseDomElement) {
            FB.XFBML.Host.parseDomElement(top_draw[0]);
          }
				}
				setTimeout(answered_q.drawer.open, 500);
				// new question
				if (MQ.q_mode!='browse' && data.new_q) { 
					jq("ul#q_list").prepend(data.new_q.innards); 
					answered_q.next().q_elt.hide();
				}
				if (MQ.q_mode=='play') {
          var next_q_timer = jq('#'+answered_qid+'_next_q_timer span');
          var next_q_timer_container = jq('#'+answered_qid+'_next_q_timer');
          next_q_timer.html('3');
          var time_to_next_q = function(){return next_q_timer.html()*1;}
          var count_down = function() {
            if ((time_to_next_q() > 0) && result!='skipped') {
              setTimeout(function() {
                MQ.utils.decrement_html(next_q_timer);
                count_down();
              }, 1000);
            }
            else { 
              if (answered_q.next()) { 
                answered_q.next().show(); 
                setTimeout(answered_q.top_drawer.open, 1000);
                setTimeout(function(){next_q_timer_container.fadeOut('slow');}, 1500);
              } 
            }
          }
          setTimeout(function() {
            next_q_timer_container.fadeIn('slow');
            count_down();
          }, 1000);
				}
        else {
          if (MQ.q_mode=='quiz') {
            if (answered_q.next()) { answered_q.next().show(); }
          }
          else {
            setTimeout(answered_q.top_drawer.open, 1000);
          }
        }
        jq('#'+qid+'_q_loading').fadeOut('slow');
        // track response
        MQ.tracker.track_goal('answer_question');
				if (result=='skipped') { MQ.tracker.question.skip(); }
        else { MQ.tracker.question.answer(); }
			}
      setTimeout((a ? MQ.tracker.question.click_answer : MQ.tracker.question.click_skip), 0);
			MQ.ajax(guess_url, params, callback, 'json');
		}
    this.fb_share = function(prop_type) {
      FB.Connect.ifUserConnected(function() {
        MQ.ajax('/fb/share', {'id':qid, 'prop':prop_type}, null, 'script');
        MQ.tracker.share('fb');
      }, function() {
        //FB.Connect.requireSession(function() { window.location='/account/link_to_fb?next_url=/q/'+qid; }); //#{questionlink(q, {:only_url=>true, :context=>(@tag || nil)})}' });
      });
      return false;
    }

		MQ.questions.push(this);
	}
}

MQ.slider = new function() {
	// hack to fix firefox bug (can't have overflow:auto on an element inside a slider)
	function toggle_overflow(bool) {
		var divs_with_overflow = []; // from widget: ['qtext','qexplanation','qinfo','qexplanation_text'];
		jq.each(divs_with_overflow, function(i, o_id) { 
			var e = jq('#'+o_id);
			if (e) { e.style.overflow=(bool ? 'auto' : 'hidden'); }
		});
	}

	// the main slide mechanics.  usually won't call this directly; use this.slide_to
	// dist is optional -- if false, it'll use the width/height of the element
	this.slide = function(direction, elt_id, number_of_screens, dist) {
		elt_id = '#'+elt_id;
		number_of_screens = (number_of_screens || 0);
		/*
		if (direction=="u" || direction=="d") {
			var v_dist = dist || (direction=="d" ? jq(elt_id).height() : (0-jq(elt_id).height()));
			var h_dist = 0;
		} else {
			var v_dist = 0;
			var h_dist = dist || (direction=="r" ? jq(elt_id).width() : (0-jq(elt_id).width()));
		}
		*/
		jq(elt_id).parent().animate({ left: (direction=='r' ? '+=' : '-=')+(number_of_screens*jq(elt_id).width()) }, 200, null, function(){toggle_overflow(true)});
	}

	var screen_sets = {
		"top10": {
			"current_screen":"alltime",
			"screens":["alltime", "today"],
			"timer_id":null,
			"callback":function(){
				jq("ul#top10_tabs li").removeClass('active');
				jq('#top10_tabs_'+this.current_screen).addClass('active');
			}
		}
	}
	
	// slide to a given screen (arg 2) within the given set's (arg 1) screen ids. define screen and screen ids in var screen_sets.
	this.slide_to = function(set, elt_id) {
		toggle_overflow(false);
		var screen_set = screen_sets[set];
		var slide_from = jq.inArray(screen_set.current_screen, screen_set.screens);//.indexOf(screen_set.current_screen);
		var slide_to = jq.inArray(elt_id, screen_set.screens); //.indexOf(elt_id);
		var slide_count = (slide_to - slide_from);
		MQ.slider.slide(((slide_count>0) ? "l" : "r"),elt_id,Math.abs(slide_count));
		screen_sets[set].current_screen = elt_id;
		if (screen_set.callback) { screen_set.callback(); }
	}
	// slide to the next screen in the given set's screens.
	this.slide_to_next = function(set) {
		var screen_set = screen_sets[set];
		var current_index = screen_set.screens.indexOf(screen_set.current_screen);
		var next_index = (((current_index+1)==screen_set.screens.length) ? 0 : (current_index+1));
		Urtog.effects.slider.slide_to(set, screen_set.screens[next_index]);
	}
	// rotate the given set's screens on a timer (inteval is ms)
	this.automate = function(set, interval, callback) {
		interval = (interval || 10000); 
		screen_sets[set].timer_id = setInterval(function() {
			Urtog.effects.slider.slide_to_next(set);
		}, interval);
		if (callback) { callback(); }
	}
	this.stop_automation = function(set) {
		clearInterval(screen_sets[set].timer_id);
	}
}

// popup notices
MQ.notice = new function() {
  this.hide = function(note_elt) {
		jq(note_elt).slideUp(500, function() { jq(note_elt).remove(); });
  }
  this.show = function(text, timeout, note_type) {
    var note = document.createElement('li');
    note.className = 'notice';
    //jq.each(['notice_t','notice_m','notice_b'],function(i, s){
    jq.each(['notice_m'],function(i, s){
      var elt = document.createElement('div');
      elt.className = s;
			if (note_type) { jq(note).addClass(note_type); }
      elt.innerHTML = (s=='notice_m' ? text : '.');
      note.appendChild(elt);
    });
    note.style.display = 'none';
    jq('#notices').append(note);
    jq(note).slideDown({duration:800, easing:'easeOutElastic'});
    timeout = (timeout || 5000); // default display time is 5s
    setTimeout(function() { MQ.notice.hide(note); }, timeout); // hide the note after timeout
  }
}

MQ.profile = new function() {
  this.set_profile_image = function(img_container, img_name) {
		jq(img_container).parents('table').find('td').removeClass('selected');
		jq(img_container).addClass('selected');
		jq('#image_stock_photo').val(img_name);
  } 

  this.upload_image = new function() {
    this.send = function(){
      jq('.mini_profile .change_image_loader').show();
      jq("form#profile_image_form").submit();
    }
    this.callback = function() {
      jq("form#profile_image_form")[0].reset();
      var response = jq('#image_iframe').contents().find('body');
      if (response.html()) {
        //var img_urls = response.html().split('|||');
        //var big_img = MQ.h('img', "src='"+img_urls[0]+"'");
        //var small_img = MQ.h('img', "src='"+img_urls[1]+"'");
        //var new_img = MQ.h('img', "src='"+response.html()+"'");
        //jq('.mini_profile img.userphoto').replaceWith(new_img); //response.html());
        var new_img_src = response.html();
        jq('.mini_profile img.userphoto').attr('src', new_img_src); //response.html());
        jq('.current_pic').attr('src',new_img_src); //response.html());
        jq('.mini_profile .change_image_loader').hide();
      }
    }
  }

  this.fb_connect = function(next_url) {
    if (!next_url && jq('.next_url').val() && jq('.next_url').val()!='') {
      next_url = MQ.url(jq('.next_url').val());
      //next_url = (next_url=='' ? MQ.url(window.location.pathname) : MQ.url(next_url));
    }
    var url = "/account/link_to_fb";
    if (next_url) {
      url = url+"?next_url="+next_url;
    }
    window.location.href=url;
  }

  this.twitter_connect = function(url) {
    if (!url) {
      var next_url = jq('.next_url').val();
      url = (next_url=='' ? MQ.url(window.location.pathname) : MQ.url(next_url));
    }
    var modal_window = window.open('/account/twitter_auth', '_blank', 'location=1,height=400,width=800,left=300,top=200,resizable=yes', true); 
    var tid = setInterval(function() {
      if (modal_window.closed) {
        clearInterval(tid);
        MQ.notice.show("Hold on...");
        window.location.href=url;
      }
    }, 250);
    MQ.tracker.user.twitter_connect();
  }
}

MQ.audio = new function() {
	this.muted=false;
  var sounds = {
    'card_open':{'file':'book_pageturn06','track':0},//'phwoop05',
    'card_close':{'file':'book_pageturn06','track':1},//'phwoop06',
    'right':{'file':'coin_magic_03','track':0},
    'wrong':{'file':'negativebeep','track':0},
    'level_up':{'file':'carnival_game_win_ding_06','track':2}
  }
	var swf_path = '/swf/audio_player.swf';
	var tracks = []; 
  var current_track = 0;
	this.init = function() {
		tracks = jq('.audio_track');
    jq.each(tracks, function(i,t) { jq(t).sound({swf: swf_path}) });
	}
	this.play = function(trigger) {
		if (!this.muted) {
      sound = sounds[trigger];
      var player = jq(tracks[sound['track']]);
      if (player.load_audio) {
        player.load_audio('/audio/'+sound['file']+'.mp3');
        player.play_audio();
      }
		}
	}
	this.toggle_mute = function(mute) {
		this.muted = mute;
		jq('#audio_controls .mute').toggle();
    MQ.ajax('/play/toggle_mute', {}, function(r) {
        MQ.notice.show(r, 10000, 'right');
        MQ.audio.play('right');
    }, "text");
	}
}

MQ.utils = new function() {

  this.test_cookies = function() {
    if (document.cookie.indexOf('_urtog_session_id') == -1) {
      if (jq.browser.safari) {
        MQ.popup.open('no_safari_cookie');
        var url = document.location.href;
        var url_with_redirect = ('/play/cookie_fix?redirect_to=' + url);

        jq('body').append("<form id='cookie_fix'></form>");
        var f = jq('#cookie_fix')[0];
        f.method = 'POST';
        f.action = url_with_redirect;
        f.submit();
      } else if (top!=self) {
        MQ.popup.open('no_iframe_cookie');
      } else {
        MQ.popup.open('no_cookie');
      }
    }
  } 

  this.to_percent = function(num, precision) {
    precision = (precision || 0);
    return (num*100).toFixed(precision);
  }
  // set up autocomplete fields - run once onload
  this.autocomplete_init = function() {
    jq.each([{id:'.topicsearch_normal, .topicsearch'},
             {id:'.topicsearch_multiple', options:{multiple:true}},
             {id:'.topicsearch_redirect', callback:function(r){window.location.href=MQ.topics.autocomplete_url_format(r);}}, 
             {id:'.topicsearch_subscribe', callback:function(r){
               jq('.topicsearch_subscribe').val('').blur();
               MQ.topics.add(r['id'], false, r['name'], true);
             }},
             {id:'.topicsearch_add_sitetopic',callback: function(r) {
               jq('.topicsearch_add_sitetopic').val('').blur();
               MQ.site.add_topic(r['name'], r['id'], r['type_id']);
             }}],
             function(i, elt) {
               var elt_id=elt.id;
               var callback=elt.callback;
               var options=(elt.options || {});
               options['formatItem'] = (options['formatItem'] || MQ.topics.autocomplete_list_format);
               options['formatResult'] = (options['formatResult'] || MQ.topics.autocomplete_result_format);
               options['width'] = 300;
               jq(elt_id).disable_enter_key().autocomplete('/topics/search', 
                                    //{multiple:elt[1]['multiple'], formatItem: MQ.topics.autocomplete_list_format, formatResult: MQ.topics.autocomplete_result_format })
                                    options)
                               .result(function(e, r) {
                                 if (callback) { 
                                   r=eval('('+r+')'); 
                                   callback(r); 
                                 }
                               });
               })
  }
	this.hide_dummy_inputs = function(input_elt) {
		var form_elt = jq(input_elt).parent();
		jq('input', form_elt).toggle();
		jq('input.real_input', form_elt)[0].focus();
	}

	this.ajax_form_submit = function(form_elt, callback, response_type) {
		MQ.notice.show("Hold on...");
		form_elt = jq(form_elt);
    var disable_submit = form_elt.find('.disable_submit');
    disable_submit.attr('disabled',true);
    loader = form_elt.find('.loading');
    loader.show();
    response_type = (response_type || 'script');
		MQ.ajax(form_elt.attr('action'), form_elt.serialize(), function(r) {
      loader.hide();
      form_elt[0].reset();
      disable_submit.attr('disabled',false);
      if (callback) { callback(r) }
    }, response_type);
		return false;
	}
  // html builder.  attrs is a string.
  // example: MQ.h('div', 'id="blerg"', MQ.h('span', 'class="blarg"', 'hello world'));
  this.h = function(tagname, attrs, rest) {
    var special = jq.grep(['img','input','br','hr'], function(t){return t==tagname;}).length>0;
    var html = "<"+tagname;
    if (attrs) { html+=(" "+attrs); }
    if (special) {
      html+=" />";
    }
    else {
      html+=">";
      if (rest) { html+=(rest.constructor==Array ? rest.join('') : rest+''); }
      html+="</"+tagname+">";
    }
    return html;
  }
  MQ.h=this.h;

	// give it an elt selector and it'll increment the innerhtml (naturally, this assumes the innerhtml is a number!)
	this.increment_html = function(elt_selector) {
		var elt=jq(elt_selector);
		elt.html(((1*elt.html())+1)+'');
	}
	this.decrement_html = function(elt_selector) {
		var elt=jq(elt_selector);
		elt.html(((1*elt.html())-1)+'');
	}
	
  this.show_tab = function(group_name, group_class, tab_elt) {
    jq('.'+group_name+'_tabs a').removeClass('selected');
    jq(tab_elt).addClass('selected');
    jq('.'+group_name+'_container').hide();
    jq('.'+group_class).show();
  }

	// get remote javascript data from a url, by appending a <script> tag to the head  
	this.dynascript = function(url) {
		jq('#dynascript').remove();
		s = document.createElement('script');
		s.type = 'text/javascript';
		s.id = 'dynascript';
		s.src = url;
		document.getElementsByTagName('head')[0].appendChild(s);
	}

	// run this onload, finds all inputs with class 'inactive' and sets them up to clear text onfocus and restore default text onblur
	this.activate_inputs = function() {
		jq('.inactive').focus(function() { if (this.value==this.defaultValue) { this.value=''; }})
			.blur(function() { if (!this.value.length) { this.value=this.defaultValue; }});
	}
	
  /* old question form
	this.validate_qinput = function(field, value) {
		var params = "field="+field+"&value="+encodeURIComponent(value);
		MQ.ajax("/questions/validate_qinput", params, false, "script");
	}
  */

	this.images = new function() {
		// grab images using the yahoo api
		this.grab = function(input_elt) {
      var search = jq(input_elt).val();
			if ((search == "") || (search == "Search for images")) { return false; }
			//else { var search = jq(input_elt).val(); }
			if ( input_elt.match("_tag_list") ) { 
				search = search.split(',')[0]; 
				jq("#image_search").val(search);
			}
			var resturl = "http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=5nRSMHTV34GPZTM0npYuIZCFWRlpQreInoXfP5YFvgjgzYgiroOqOvpQf5bglUMqag0xSg&results=50&type=any&output=json&callback=MQ.utils.images.parse&query=";
			// only search on the first topic
			jq('#images_error').hide();
			jq('#images_loading').show();
			MQ.utils.dynascript( resturl + encodeURIComponent( search ));
		}

		// parse json from yahoo api to display image results (6 at a time, with paging)
		this.parse = function(data, start_index) {
			image_data = data;
			total_results = data.ResultSet.totalResultsReturned;
			if ( data.Error || total_results == 0 ) {
				jq('#images_error').show();
			}
			else {
				if ( !start_index || (start_index+6 > total_results) ) { 
					start_index = 0;
				}
				jq('#image_search_container').show();
				var image_container = jq('#images')[0];
				// delete existing images
				while (image_container.rows.length > 0) {
					image_container.deleteRow(-1);
				}
				// create and append dom elements for 6 images
				var img_table = jq('#images')[0];
				var img_row = img_table.insertRow(0);
				jq.each(data.ResultSet.Result, function( i, p ) {
						if (i%2==0) { img_row = img_table.insertRow(jq('#images tr').length); }
						var img_container = img_row.insertCell(i%2);//document.createElement('td');
						img_container.className = 'image';
						var img = document.createElement('img');
						img.src = p.Thumbnail.Url;
						img.height = p.Thumbnail.Height;
						img.width = p.Thumbnail.Width;
						img_container.appendChild( img );
						jq(img_container).click(function() {
							MQ.utils.images.set(img_container, i);
						});
        });
			}
			jq('#images_loading').hide();
			if (MQ && MQ.OS) { gadgets.window.adjustHeight(); }
		}
		
		// select an image when you're writing a question
		this.set = function(img_container, img_id) {
			//var selected = select_image(img_container);
			var img = jq(img_container);
			var selected = img.hasClass('selected');
			jq('#images td').removeClass('selected');
			if (selected) {
				img.removeClass('selected');
				jq('#image_image_url').val("");
				jq('#image_y_thumb_url').val("");
			}
			else {
				//Element.addClassName( img_container, 'selected' );
				img.addClass('selected');
				jq('#image_image_url').val(image_data.ResultSet.Result[img_id].Url);
				jq('#image_y_thumb_url').val(image_data.ResultSet.Result[img_id].Thumbnail.Url);
			}
      if (MQ.quizbuilder) { MQ.quizbuilder.validate_bonus('pic'); }
			return false;
		}

		this.build_browse_link = function(link_text, index) {
			var link = document.createElement('a');
			link.href = "#";
			link.innerHTML = link_text;
			jq(link).click(function() {
				MQ.utils.images.parse( image_data, index );
			});
			link.onclick = function() { return false; };
			return link;
		}
	}
}

MQ.user = new function() {

  this.logged_in = null;
	this.userdiv = null; // holds the html for the who_knew_it section

	this.set_alert_pref = function(wants_email) {
		MQ.ajax('/account/set_alert_pref', {email:wants_email}, function(r) { MQ.notice.show(r, 10000); });
	}
  this.set_password = function() {
    MQ.utils.ajax_form_submit('#change_password_form', function(data){
      MQ.notice.show(data['msg'], 5000, (data['ok'] ? 'right' : 'wrong'));
      jq('#change_password_form').hide()[0].reset();
    }, 'json');
  }
  this.set_email = function() {
    MQ.utils.ajax_form_submit('#new_email_form', function(data){
      MQ.notice.show(data['msg'], 10000, (data['ok'] ? 'right' : 'wrong'));
      if (data['ok']) {
        jq('#new_email').val(data['email']);
        jq('.current_email').html(data['email']);
        jq('.current_email_section, .new_email_section').toggle();
      };
    }, 'json');
    return false;
  }
  this.send_feedback = function() {
    MQ.utils.ajax_form_submit("#feedback_form", function(data) {
      MQ.notice.show(data['msg'], 5000);
      if (data['bonus']) {
        jq('.feedback_inputs').toggle();
        jq('#feedback_form')[0].reset();
        MQ.user.update_score(data['bonus'], {no_notice:true});
      }
    }, 'json');
  }
  this.level_up = function(n) {
    n = (n || 1);
    MQ.ajax('/play/level_up', {level:n}, false, 'script');
  }
	this.update_leaderboards = function() {
		jq('#leaderboards').load('/play/update_leaderboards');
	}
	this.update_progress_bar = function(percent) {
		var mercury = jq('.mercury', 'div.mini_profile');
		if (mercury.length!=0) {
			if (percent==100) {
			//	var dy = (percent-100);
				mercury.animate({width:'100%'}, 'slow', 'swing', function(){
					mercury.css({width:'0%'});
          MQ.audio.play('level_up');
					MQ.notice.show("Congratulations! You've reached Level "+ jq('.next_level').html() + "!", 20000);
          MQ.ajax('/play/level_up', {level:jq('.next_level').html()}, false, 'script');
					jq.each(['.current_level','.next_level'],function(i,l){ MQ.utils.increment_html(l); });
					//MQ.user.update_progress_bar(dy);
				});
			}
			else { mercury.animate({width:percent+'%'}); }
		}
	}

	// spin the user's score the given number of points.
	// opt 2nd arg is the percent to pass to update_progress_bar
	this.update_score = function(points, options) {//level_percent_array, no_notice) {
    options = (options || {});
		var upmod = (points > 0);
    if (!options['no_notice']) {
      var msg = ((options['type'] && options['type']=='fact') ? (upmod ? "RIGHT! +" : "WRONG! ") : "THANKS! +");
      setTimeout(function(){
        MQ.notice.show(msg + points + " points", 5000, (upmod ? "right" : "wrong"));
      }, 0);
    }
		var score_tag = jq('div.mini_profile .my_score');
		function mod(remaining_points) {
			var current_score = 1*score_tag.html();
			if (remaining_points==0 || (current_score == 0 && !upmod)) { return false; }
			else {
				score_tag.html((current_score += (upmod ? 1 : -1))+'');
				setTimeout(function() { mod(remaining_points-1); }, 50); 
			}
		}
		mod(Math.abs(points));
		if (options['level_percent_array']) { //typeof level_percent_array != 'undefined') {
			jq.each(options['level_percent_array'], function(i, level_percent) {
				MQ.user.update_progress_bar(level_percent);
			});
		}
	}

	// arg is a boolean; if true, increments number correct
	this.update_pc = function(correct) {
		MQ.utils.increment_html('.my_pc_t', 'div.mini_profile');
		if (correct) { MQ.utils.increment_html('.my_pc_c', 'div.mini_profile') };
		var number_played = jq('.my_pc_t', 'div.mini_profile').html()*1;
		jq('.my_pc_p', 'div.mini_profile').html((((1*jq('.my_pc_c', 'div.mini_profile').html())/(1*jq('.my_pc_t', 'div.mini_profile').html()))*100).toFixed()+'%');
	}
}

MQ.topics = new function() {
	this.add = function(t_id, add_to_blacklist, t_name, search) {
    if (MQ.user.logged_in) {
      if (jq('.edit_topics_uber').length==0) { jq('.topbar_my_topics_container').slideDown('normal'); }
      jq('.edit_topics_'+t_id+', #search_topic_'+t_id).removeClass('blocked subscribed').addClass(add_to_blacklist ? 'blocked' : 'subscribed');
      if (!add_to_blacklist) { MQ.utils.increment_html('.sub_count_'+t_id);}
      var transfer_elt = (search ? '.topicsearch_subscribe' : '.edit_topics_'+t_id+(add_to_blacklist ? ' .block_on' : ' .sub_on'))
      jq(transfer_elt).effect('transfer', {to:jq((add_to_blacklist ? '.blocked_container' : '.subscribed_container')+' .manage_topics_window:first')}, 750);
      jq('.ui-effects-transfer').css('background', (add_to_blacklist ? '#8787E2' : '#FF2312'));
      var elt_stub = ('.manage_topics_container'+(add_to_blacklist ? '.blocked_container ' : '.subscribed_container '));
      jq(elt_stub + ' h3 img').show();
      jq('.my_topic_'+t_id).remove();
      MQ.ajax('/play/add_topic', {tag_id:t_id, blacklist:add_to_blacklist}, function(data) {
        MQ.audio.play('right');
        jq(elt_stub+' li.none').hide();
        MQ.notice.show(data.notice, 5000);
        if (data.topic_html!='') {
            jq(elt_stub + ' .manage_topics_window')
              .scrollTo(0,500)
              .find('ul')
                .prepend(data.topic_html).hide()
                .slideDown('slow');
            jq(elt_stub + ' h3 img').hide();
        }
        MQ.tracker.topic[(add_to_blacklist ? 'blacklist' : 'subscribe')](t_name);
      }, "json");
      setTimeout(function(){jq('.topbar_my_topics_container').slideUp('normal')}, 5000);
    } else {
      var next_url = jq('.next_url').val('/play/add_topic?tag_id='+t_id+'&next='+document.location.href);
      MQ.popup.open('login_form');
    }
	}
	this.remove = function(t_id, x_elt, reload_page) {
		if (x_elt) {
			var topic_elt = x_elt.parentNode;
			topic_elt.parentNode.removeChild(topic_elt);
		}
    jq('.my_topic_'+t_id).slideUp({duration:500, callback:jq(this).remove});
    jq('.edit_topics_'+t_id).removeClass('blocked subscribed');
		MQ.ajax('/play/remove_topic', {tag_id:t_id}, function(data) {
			MQ.notice.show(data.notice);
      if (reload_page) { window.location.reload() }
		}, "json");
	}
	this.autocomplete_result_format = function(data) {
		data = eval("("+data+")");
		return data["name"];
	}
  /*
	this.autocomplete_list_format = function(data) {
		data = eval("("+data+")");
    var result_text = (data.type_id==0 ? data.name : ((data.type_id==1 ? "Questions by " : "Questions from ") + data.name))
		return (result_text + "<br />" + data["number"] + " questions");
	}
  */
  this.autocomplete_list_format = function(data) {
		data = eval("("+data+")");
    return MQ.h("table", ("class='search_topic' id='search_topic_"+data.id+"'"), [
      MQ.h('tr', null, [
        MQ.h('td', null, [
          MQ.h('div', "class='midcol subscribe_buttons'", [
            MQ.h('a', "class='sub_off round'", "Subscribe"),
            MQ.h('a', "class='sub_on round'", "Unsubscribe")
          ])
        ]),
        MQ.h('td', null, [
          MQ.h('p', "class='title'", [MQ.h('a', "href='"+MQ.topics.autocomplete_url_format(data)+"' onclick='return false;'", (data.type_id==0 ? data.name : ((data.type_id==1 ? "Questions by " : "Questions from ") + data.name))), MQ.h('span', null, " ("+data["number"]+"&nbsp;questions)")])
        ])
      ])
    ]);
  }
	this.autocomplete_url_format = function(data) {
		//data = eval("("+data+")");
    return "/topic/"+data.name+"/"+data.id;
  }
}

MQ.vote = function(voteable_type, voteable_id, is_upvote) {
  var thing = MQ.find(voteable_id, voteable_type);
  if (voteable_type=='questions', thing.body.hasClass('unplayed')) {
    MQ.notice.show("First, answer the question!", 10000);
  } else {
    if (MQ.user.logged_in) {
      var rescinding = (is_upvote && thing.body.hasClass('upvoted') || (!is_upvote && thing.body.hasClass('downvoted'))); 
      thing.body.removeClass('upvoted unvoted downvoted').addClass(rescinding ? 'unvoted' : (is_upvote ? 'upvoted' : 'downvoted'));
      if (voteable_type=='questions') {
        thing.send_feedback('vote', (is_upvote ? 'upvote' : 'downvote'));
      } else if (voteable_type=='comments') {
        MQ.ajax("/comments/vote", {type:(is_upvote ? 'upvote' : 'downvote'), id:thing.id}, function(r){
          MQ.notice.show(r, 10000);
        });
      }
    } else {
      var next_url = jq('.next_url').val('/q/'+thing.qid);
      MQ.popup.open('login_form');
    }
  }
  return false;
}

// helpers for analytics
MQ.tracker = new function() {
  this.goal_map = {}
  this.reset = function() {
    clicky_custom.pageview_disable = 1;
    clicky.init();
  }

  this.track_goal = function(key) {
    var goal_id = MQ.tracker.goal_map[key];
    if (goal_id) {
      log('tracking goal: ' + key);
      clicky.goal(goal_id+'');
    } else {
      log("unknown goal id!");
    }
  }
  this.track = function(url, name, type) {
    log('Tracking: '+name);
    type = (type || "pageview");
    // sync clicky_custom with user session
    if (typeof clicky_custom.session.uid == 'undefined' && MQ.user.uid) {
      clicky_custom.session.uid = (MQ.user.uid + '');
      MQ.tracker.reset();
    }
    if (typeof clicky_custom.session.username == 'undefined' && MQ.user.login && MQ.user.login.length>0) {
      clicky_custom.session.username = MQ.user.login;
      clicky_custom.session.anonymous = 0;
      MQ.tracker.reset();
    }
    setTimeout(function() {
      if (clicky.log) {
        clicky.log(url, name, type);
      }
    }, 500);
  }
  this.question = new function() {
    this.click_answer = function() { MQ.tracker.track('/question/click_answer', 'Clicked answer question'); }
    this.click_skip = function() { MQ.tracker.track('/question/click_skip', 'Clicked skip question'); }
    this.answer = function() { MQ.tracker.track('/question/answer', 'Answer question'); }
    this.skip = function() { MQ.tracker.track('/question/skip', 'Skip question'); }
    this.send_feedback = function(category) { MQ.tracker.track('/question/'+category, (category[0].toUpperCase()+category.slice(1).replace(/_/g," "))); };
  }
  this.topic = new function() {
    this.subscribe = function(t_name) { MQ.tracker.track('/topic/subscribe', "Subscribe to topic: "+t_name); }
    this.blacklist = function(t_name) { MQ.tracker.track('/topic/blacklist', "Blacklist topic: "+t_name); }
  }
  this.share = function(share_type) {
    MQ.tracker.track('/share/', "Share via "+share_type)
  }
  this.user = new function() {
    this.continue_without_saving = function(context) { MQ.tracker.track('/user/continue_without_saving', "Continue without saving: "+(context || ''));}
    this.twitter_connect = function() { MQ.tracker.track('/user/login/twitter', "Log in with Twitter"); }
  }
  this.popup = new function() {
    this.open = function(type) { MQ.tracker.track('/popup/open/', 'Show popup: '+type); }
    this.close = function(type) { MQ.tracker.track('/popup/close/', 'Close popup: '+type); }
  }
  this.quiz = new function() {
    this.home = function() { MQ.tracker.track('/quiz/home/', 'View quiz home'); }
    this.result = function() { MQ.tracker.track('/quiz/result/', 'View quiz result'); }
  }
}
