if(!("console"in window)||!("firebug"in console))
{var names=["log","debug","info","warn","error","assert","dir","dirxml","group","groupEnd","time","timeEnd","count","trace","profile","profileEnd"];window.console={};for(var i=0;i<names.length;++i)
window.console[names[i]]=function(){}}
(function($){var allowed={};$.each(['click','dblclick','mousedown','mouseup','mousemove','mouseover','mouseout','keydown','keypress','keyup'],function(i,eventName){allowed[eventName]=true;});$.fn.extend({delegate:function(event,selector,f){return $(this).each(function(){if(allowed[event])
$(this).bind(event,function(e){var el=$(e.target),result=false;while(!$(el).is('html')){if($(el).is(selector)){result=f.apply($(el)[0],[e]);if(result===false)
e.preventDefault();return;}
el=$(el).parent();}});});},undelegate:function(event){return $(this).each(function(){$(this).unbind(event);});}});})(jQuery);;(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]);select.hide(true);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();}
options.onTextChange();};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:", ",combo:false,onTextChange:function(){},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(force){if(options.combo&&!force){return}
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.extend({param:function(a){var s=[];function add(key,value){s[s.length]=encodeURIComponent(key)+'='+encodeURIComponent(value);}
if(jQuery.isArray(a)||a.jquery){jQuery.each(a,function(){add(this.name,this.value);});}else{function buildParams(obj,prefix)
{if(jQuery.isArray(obj)){for(var i=0,length=obj.length;i<length;i++){buildParams(obj[i],prefix);};}else if(typeof(obj)=="object"){for(var j in obj){var postfix=((j.indexOf("[]")>0)?"[]":"");buildParams(obj[j],(prefix?(prefix+"["+j.replace("[]","")+"]"+postfix):j));}}else{add(prefix,jQuery.isFunction(obj)?obj():obj);}}
buildParams(a);}
return s.join("&").replace(/%20/g,"+");}});(function($)
{$.fn.watermark=function(text,css_options){css=$.extend({color:'#999',left:4},css_options);return this.each(function()
{if(this.nodeName.toUpperCase()=='SELECT'){return;}
var input_marked=$(this);var label_text=text===undefined?$(this).attr('title'):text;var watermark_container=$('<span class="watermark_container" style="position: relative"></span>');var watermark_label=$('<span class="watermark">'+label_text+'</span>');watermark_container.css({float:input_marked.css('float')});$(this).wrap(watermark_container);var height=$(this).outerHeight();checkVal($(this).val(),watermark_label);var new_css={position:'absolute',fontFamily:$(this).css('font-family'),fontSize:$(this).css('font-size'),color:css.color,left:(parseInt($(this).css('padding-left'))+css.left)+'px',top:'50%',height:height+'px',lineHeight:height+'px',marginTop:'-'+(height/2)+'px'};if(this.nodeName.toUpperCase()=='TEXTAREA'){var pos=$(this).position();$.extend(new_css,{lineHeight:$(this).css('line-height'),top:pos.top+'px',left:pos.left+'px',marginTop:0});}
watermark_label.css(new_css);watermark_label.click(function()
{$(this).next().focus();})
$(this).before(watermark_label).focus(function()
{checkVal($(this).val(),watermark_label);watermark_label.css({opacity:this.nodeName.toUpperCase()=='TEXTAREA'?0.0:0.7});}).blur(function()
{checkVal($(this).val(),watermark_label);watermark_label.css({opacity:1});}).keydown(function(e)
{$(watermark_label).hide();}).keyup(function(e)
{checkVal($(this).val(),watermark_label);});});};checkVal=function(val,elem)
{if(val=='')
$(elem).show();else
$(elem).hide();};})(jQuery);(function($){$.fn.TextAreaExpander=function(minHeight,maxHeight){var hCheck=!($.browser.msie||$.browser.opera);function ResizeTextarea(e){e=e.target||e;var vlen=e.value.length,ewidth=e.offsetWidth;if(vlen!=e.valLength||ewidth!=e.boxWidth){if(hCheck&&(vlen<e.valLength||ewidth!=e.boxWidth))e.style.height="0px";var h=Math.max(e.expandMin,Math.min(e.scrollHeight,e.expandMax));e.style.overflow=(e.scrollHeight>h?"auto":"hidden");e.style.height=h+"px";e.valLength=vlen;e.boxWidth=ewidth;}
return true;};this.each(function(){if(this.nodeName.toLowerCase()!="textarea")return;var p=this.className.match(/expand(\d+)\-*(\d+)*/i);this.expandMin=minHeight||(p?parseInt('0'+p[1],10):0);this.expandMax=maxHeight||(p?parseInt('0'+p[2],10):99999);ResizeTextarea(this);if(!this.Initialized){this.Initialized=true;$(this).css("padding-top",0).css("padding-bottom",0);$(this).bind("keyup",ResizeTextarea).bind("focus",ResizeTextarea);}});return this;};})(jQuery);jQuery(document).ready(function(){jQuery("textarea[class*=expand]").TextAreaExpander();});(function(c){var d=[];c.tools=c.tools||{};c.tools.tooltip={version:"1.1.2",conf:{effect:"toggle",fadeOutSpeed:"fast",tip:null,predelay:0,delay:30,opacity:1,lazy:undefined,position:["top","center"],offset:[0,0],cancelDefault:true,relative:false,oneInstance:true,events:{def:"mouseover,mouseout",input:"focus,blur",widget:"focus mouseover,blur mouseout",tooltip:"mouseover,mouseout"},api:false},addEffect:function(e,g,f){b[e]=[g,f]}};var b={toggle:[function(e){var f=this.getConf(),g=this.getTip(),h=f.opacity;if(h<1){g.css({opacity:h})}g.show();e.call()},function(e){this.getTip().hide();e.call()}],fade:[function(e){this.getTip().fadeIn(this.getConf().fadeInSpeed,e)},function(e){this.getTip().fadeOut(this.getConf().fadeOutSpeed,e)}]};function a(f,g){var p=this,k=c(this);f.data("tooltip",p);var l=f.next();if(g.tip){l=c(g.tip);if(l.length>1){l=f.nextAll(g.tip).eq(0);if(!l.length){l=f.parent().nextAll(g.tip).eq(0)}}}function o(u){var t=g.relative?f.position().top:f.offset().top,s=g.relative?f.position().left:f.offset().left,v=g.position[0];t-=l.outerHeight()-g.offset[0];s+=f.outerWidth()+g.offset[1];var q=l.outerHeight()+f.outerHeight();if(v=="center"){t+=q/2}if(v=="bottom"){t+=q}v=g.position[1];var r=l.outerWidth()+f.outerWidth();if(v=="center"){s-=r/2}if(v=="left"){s-=r}return{top:t,left:s}}var i=f.is(":input"),e=i&&f.is(":checkbox, :radio, select, :button"),h=f.attr("type"),n=g.events[h]||g.events[i?(e?"widget":"input"):"def"];n=n.split(/,\s*/);if(n.length!=2){throw"Tooltip: bad events configuration for "+h}f.bind(n[0],function(r){if(g.oneInstance){c.each(d,function(){this.hide()})}var q=l.data("trigger");if(q&&q[0]!=this){l.hide().stop(true,true)}r.target=this;p.show(r);n=g.events.tooltip.split(/,\s*/);l.bind(n[0],function(){p.show(r)});if(n[1]){l.bind(n[1],function(){p.hide(r)})}});f.bind(n[1],function(q){p.hide(q)});if(!c.browser.msie&&!i&&!g.predelay){f.mousemove(function(){if(!p.isShown()){f.triggerHandler("mouseover")}})}if(g.opacity<1){l.css("opacity",g.opacity)}var m=0,j=f.attr("title");if(j&&g.cancelDefault){f.removeAttr("title");f.data("title",j)}c.extend(p,{show:function(r){if(r){f=c(r.target)}clearTimeout(l.data("timer"));if(l.is(":animated")||l.is(":visible")){return p}function q(){l.data("trigger",f);var t=o(r);if(g.tip&&j){l.html(f.data("title"))}r=r||c.Event();r.type="onBeforeShow";k.trigger(r,[t]);if(r.isDefaultPrevented()){return p}t=o(r);l.css({position:"absolute",top:t.top,left:t.left});var s=b[g.effect];if(!s){throw'Nonexistent effect "'+g.effect+'"'}s[0].call(p,function(){r.type="onShow";k.trigger(r)})}if(g.predelay){clearTimeout(m);m=setTimeout(q,g.predelay)}else{q()}return p},hide:function(r){clearTimeout(l.data("timer"));clearTimeout(m);if(!l.is(":visible")){return}function q(){r=r||c.Event();r.type="onBeforeHide";k.trigger(r);if(r.isDefaultPrevented()){return}b[g.effect][1].call(p,function(){r.type="onHide";k.trigger(r)})}if(g.delay&&r){l.data("timer",setTimeout(q,g.delay))}else{q()}return p},isShown:function(){return l.is(":visible, :animated")},getConf:function(){return g},getTip:function(){return l},getTrigger:function(){return f},bind:function(q,r){k.bind(q,r);return p},onHide:function(q){return this.bind("onHide",q)},onBeforeShow:function(q){return this.bind("onBeforeShow",q)},onShow:function(q){return this.bind("onShow",q)},onBeforeHide:function(q){return this.bind("onBeforeHide",q)},unbind:function(q){k.unbind(q);return p}});c.each(g,function(q,r){if(c.isFunction(r)){p.bind(q,r)}})}c.prototype.tooltip=function(e){var f=this.eq(typeof e=="number"?e:0).data("tooltip");if(f){return f}var g=c.extend(true,{},c.tools.tooltip.conf);if(c.isFunction(e)){e={onBeforeShow:e}}else{if(typeof e=="string"){e={tip:e}}}e=c.extend(true,g,e);if(typeof e.position=="string"){e.position=e.position.split(/,?\s/)}if(e.lazy!==false&&(e.lazy===true||this.length>20)){this.one("mouseover",function(h){f=new a(c(this),e);f.show(h);d.push(f)})}else{this.each(function(){f=new a(c(this),e);d.push(f)})}return e.api?f:this}})(jQuery);;(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);(function($){$.extend({tmpl:function(tmpl,vals,opts){var rgxp,repr;opts=opts||{escape:true};tmpl=tmpl||'';vals=vals||{};rgxp=/#\{([^{}]*)}/g;repr=function(str,match){return typeof vals[match]==='string'||typeof vals[match]==='number'?(opts.escape?$.escapeHTML(vals[match]):vals[match]):str;};return tmpl.replace(rgxp,repr);}});})(jQuery);Date.CultureInfo={name:"en-US",englishName:"English (United States)",nativeName:"English (United States)",dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbreviatedDayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shortestDayNames:["Su","Mo","Tu","We","Th","Fr","Sa"],firstLetterDayNames:["S","M","T","W","T","F","S"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],abbreviatedMonthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:0,twoDigitYearMax:2029,dateElementOrder:"mdy",formatPatterns:{shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss GMT",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},regexPatterns:{jan:/^jan(uary)?/i,feb:/^feb(ruary)?/i,mar:/^mar(ch)?/i,apr:/^apr(il)?/i,may:/^may/i,jun:/^jun(e)?/i,jul:/^jul(y)?/i,aug:/^aug(ust)?/i,sep:/^sep(t(ember)?)?/i,oct:/^oct(ober)?/i,nov:/^nov(ember)?/i,dec:/^dec(ember)?/i,sun:/^su(n(day)?)?/i,mon:/^mo(n(day)?)?/i,tue:/^tu(e(s(day)?)?)?/i,wed:/^we(d(nesday)?)?/i,thu:/^th(u(r(s(day)?)?)?)?/i,fri:/^fr(i(day)?)?/i,sat:/^sa(t(urday)?)?/i,future:/^next/i,past:/^last|past|prev(ious)?/i,add:/^(\+|after|from)/i,subtract:/^(\-|before|ago)/i,yesterday:/^yesterday/i,today:/^t(oday)?/i,tomorrow:/^tomorrow/i,now:/^n(ow)?/i,millisecond:/^ms|milli(second)?s?/i,second:/^sec(ond)?s?/i,minute:/^min(ute)?s?/i,hour:/^h(ou)?rs?/i,week:/^w(ee)?k/i,month:/^m(o(nth)?s?)?/i,day:/^d(ays?)?/i,year:/^y((ea)?rs?)?/i,shortMeridian:/^(a|p)/i,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt)/i,ordinalSuffix:/^\s*(st|nd|rd|th)/i,timeContext:/^\s*(\:|a|p)/i},abbreviatedTimeZoneStandard:{GMT:"-000",EST:"-0400",CST:"-0500",MST:"-0600",PST:"-0700"},abbreviatedTimeZoneDST:{GMT:"-000",EDT:"-0500",CDT:"-0600",MDT:"-0700",PDT:"-0800"}};Date.getMonthNumberFromName=function(name){var n=Date.CultureInfo.monthNames,m=Date.CultureInfo.abbreviatedMonthNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};Date.getDayNumberFromName=function(name){var n=Date.CultureInfo.dayNames,m=Date.CultureInfo.abbreviatedDayNames,o=Date.CultureInfo.shortestDayNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};Date.isLeapYear=function(year){return(((year%4===0)&&(year%100!==0))||(year%400===0));};Date.getDaysInMonth=function(year,month){return[31,(Date.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];};Date.getTimezoneOffset=function(s,dst){return(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST[s.toUpperCase()]:Date.CultureInfo.abbreviatedTimeZoneStandard[s.toUpperCase()];};Date.getTimezoneAbbreviation=function(offset,dst){var n=(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST:Date.CultureInfo.abbreviatedTimeZoneStandard,p;for(p in n){if(n[p]===offset){return p;}}
return null;};Date.prototype.clone=function(){return new Date(this.getTime());};Date.prototype.compareTo=function(date){if(isNaN(this)){throw new Error(this);}
if(date instanceof Date&&!isNaN(date)){return(this>date)?1:(this<date)?-1:0;}else{throw new TypeError(date);}};Date.prototype.equals=function(date){return(this.compareTo(date)===0);};Date.prototype.between=function(start,end){var t=this.getTime();return t>=start.getTime()&&t<=end.getTime();};Date.prototype.addMilliseconds=function(value){this.setMilliseconds(this.getMilliseconds()+value);return this;};Date.prototype.addSeconds=function(value){return this.addMilliseconds(value*1000);};Date.prototype.addMinutes=function(value){return this.addMilliseconds(value*60000);};Date.prototype.addHours=function(value){return this.addMilliseconds(value*3600000);};Date.prototype.addDays=function(value){return this.addMilliseconds(value*86400000);};Date.prototype.addWeeks=function(value){return this.addMilliseconds(value*604800000);};Date.prototype.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,this.getDaysInMonth()));return this;};Date.prototype.addYears=function(value){return this.addMonths(value*12);};Date.prototype.add=function(config){if(typeof config=="number"){this._orient=config;return this;}
var x=config;if(x.millisecond||x.milliseconds){this.addMilliseconds(x.millisecond||x.milliseconds);}
if(x.second||x.seconds){this.addSeconds(x.second||x.seconds);}
if(x.minute||x.minutes){this.addMinutes(x.minute||x.minutes);}
if(x.hour||x.hours){this.addHours(x.hour||x.hours);}
if(x.month||x.months){this.addMonths(x.month||x.months);}
if(x.year||x.years){this.addYears(x.year||x.years);}
if(x.day||x.days){this.addDays(x.day||x.days);}
return this;};Date._validate=function(value,min,max,name){if(typeof value!="number"){throw new TypeError(value+" is not a Number.");}else if(value<min||value>max){throw new RangeError(value+" is not a valid value for "+name+".");}
return true;};Date.validateMillisecond=function(n){return Date._validate(n,0,999,"milliseconds");};Date.validateSecond=function(n){return Date._validate(n,0,59,"seconds");};Date.validateMinute=function(n){return Date._validate(n,0,59,"minutes");};Date.validateHour=function(n){return Date._validate(n,0,23,"hours");};Date.validateDay=function(n,year,month){return Date._validate(n,1,Date.getDaysInMonth(year,month),"days");};Date.validateMonth=function(n){return Date._validate(n,0,11,"months");};Date.validateYear=function(n){return Date._validate(n,1,9999,"seconds");};Date.prototype.set=function(config){var x=config;if(!x.millisecond&&x.millisecond!==0){x.millisecond=-1;}
if(!x.second&&x.second!==0){x.second=-1;}
if(!x.minute&&x.minute!==0){x.minute=-1;}
if(!x.hour&&x.hour!==0){x.hour=-1;}
if(!x.day&&x.day!==0){x.day=-1;}
if(!x.month&&x.month!==0){x.month=-1;}
if(!x.year&&x.year!==0){x.year=-1;}
if(x.millisecond!=-1&&Date.validateMillisecond(x.millisecond)){this.addMilliseconds(x.millisecond-this.getMilliseconds());}
if(x.second!=-1&&Date.validateSecond(x.second)){this.addSeconds(x.second-this.getSeconds());}
if(x.minute!=-1&&Date.validateMinute(x.minute)){this.addMinutes(x.minute-this.getMinutes());}
if(x.hour!=-1&&Date.validateHour(x.hour)){this.addHours(x.hour-this.getHours());}
if(x.month!==-1&&Date.validateMonth(x.month)){this.addMonths(x.month-this.getMonth());}
if(x.year!=-1&&Date.validateYear(x.year)){this.addYears(x.year-this.getFullYear());}
if(x.day!=-1&&Date.validateDay(x.day,this.getFullYear(),this.getMonth())){this.addDays(x.day-this.getDate());}
if(x.timezone){this.setTimezone(x.timezone);}
if(x.timezoneOffset){this.setTimezoneOffset(x.timezoneOffset);}
return this;};Date.prototype.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this;};Date.prototype.isLeapYear=function(){var y=this.getFullYear();return(((y%4===0)&&(y%100!==0))||(y%400===0));};Date.prototype.isWeekday=function(){return!(this.is().sat()||this.is().sun());};Date.prototype.getDaysInMonth=function(){return Date.getDaysInMonth(this.getFullYear(),this.getMonth());};Date.prototype.moveToFirstDayOfMonth=function(){return this.set({day:1});};Date.prototype.moveToLastDayOfMonth=function(){return this.set({day:this.getDaysInMonth()});};Date.prototype.moveToDayOfWeek=function(day,orient){var diff=(day-this.getDay()+7*(orient||+1))%7;return this.addDays((diff===0)?diff+=7*(orient||+1):diff);};Date.prototype.moveToMonth=function(month,orient){var diff=(month-this.getMonth()+12*(orient||+1))%12;return this.addMonths((diff===0)?diff+=12*(orient||+1):diff);};Date.prototype.getDayOfYear=function(){return Math.floor((this-new Date(this.getFullYear(),0,1))/86400000);};Date.prototype.getWeekOfYear=function(firstDayOfWeek){var y=this.getFullYear(),m=this.getMonth(),d=this.getDate();var dow=firstDayOfWeek||Date.CultureInfo.firstDayOfWeek;var offset=7+1-new Date(y,0,1).getDay();if(offset==8){offset=1;}
var daynum=((Date.UTC(y,m,d,0,0,0)-Date.UTC(y,0,1,0,0,0))/86400000)+1;var w=Math.floor((daynum-offset+7)/7);if(w===dow){y--;var prevOffset=7+1-new Date(y,0,1).getDay();if(prevOffset==2||prevOffset==8){w=53;}else{w=52;}}
return w;};Date.prototype.isDST=function(){console.log('isDST');return this.toString().match(/(E|C|M|P)(S|D)T/)[2]=="D";};Date.prototype.getTimezone=function(){return Date.getTimezoneAbbreviation(this.getUTCOffset,this.isDST());};Date.prototype.setTimezoneOffset=function(s){var here=this.getTimezoneOffset(),there=Number(s)*-6/10;this.addMinutes(there-here);return this;};Date.prototype.setTimezone=function(s){return this.setTimezoneOffset(Date.getTimezoneOffset(s));};Date.prototype.getUTCOffset=function(){var n=this.getTimezoneOffset()*-10/6,r;if(n<0){r=(n-10000).toString();return r[0]+r.substr(2);}else{r=(n+10000).toString();return"+"+r.substr(1);}};Date.prototype.getDayName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedDayNames[this.getDay()]:Date.CultureInfo.dayNames[this.getDay()];};Date.prototype.getMonthName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedMonthNames[this.getMonth()]:Date.CultureInfo.monthNames[this.getMonth()];};Date.prototype._toString=Date.prototype.toString;Date.prototype.toString=function(format){var self=this;var p=function p(s){return(s.toString().length==1)?"0"+s:s;};return format?format.replace(/dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?/g,function(format){switch(format){case"hh":return p(self.getHours()<13?self.getHours():(self.getHours()-12));case"h":return self.getHours()<13?self.getHours():(self.getHours()-12);case"HH":return p(self.getHours());case"H":return self.getHours();case"mm":return p(self.getMinutes());case"m":return self.getMinutes();case"ss":return p(self.getSeconds());case"s":return self.getSeconds();case"yyyy":return self.getFullYear();case"yy":return self.getFullYear().toString().substring(2,4);case"dddd":return self.getDayName();case"ddd":return self.getDayName(true);case"dd":return p(self.getDate());case"d":return self.getDate().toString();case"MMMM":return self.getMonthName();case"MMM":return self.getMonthName(true);case"MM":return p((self.getMonth()+1));case"M":return self.getMonth()+1;case"t":return self.getHours()<12?Date.CultureInfo.amDesignator.substring(0,1):Date.CultureInfo.pmDesignator.substring(0,1);case"tt":return self.getHours()<12?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator;case"zzz":case"zz":case"z":return"";}}):this._toString();};Date.now=function(){return new Date();};Date.today=function(){return Date.now().clearTime();};Date.prototype._orient=+1;Date.prototype.next=function(){this._orient=+1;return this;};Date.prototype.last=Date.prototype.prev=Date.prototype.previous=function(){this._orient=-1;return this;};Date.prototype._is=false;Date.prototype.is=function(){this._is=true;return this;};Number.prototype._dateElement="day";Number.prototype.fromNow=function(){var c={};c[this._dateElement]=this;return Date.now().add(c);};Number.prototype.ago=function(){var c={};c[this._dateElement]=this*-1;return Date.now().add(c);};(function(){var $D=Date.prototype,$N=Number.prototype;var dx=("sunday monday tuesday wednesday thursday friday saturday").split(/\s/),mx=("january february march april may june july august september october november december").split(/\s/),px=("Millisecond Second Minute Hour Day Week Month Year").split(/\s/),de;var df=function(n){return function(){if(this._is){this._is=false;return this.getDay()==n;}
return this.moveToDayOfWeek(n,this._orient);};};for(var i=0;i<dx.length;i++){$D[dx[i]]=$D[dx[i].substring(0,3)]=df(i);}
var mf=function(n){return function(){if(this._is){this._is=false;return this.getMonth()===n;}
return this.moveToMonth(n,this._orient);};};for(var j=0;j<mx.length;j++){$D[mx[j]]=$D[mx[j].substring(0,3)]=mf(j);}
var ef=function(j){return function(){if(j.substring(j.length-1)!="s"){j+="s";}
return this["add"+j](this._orient);};};var nf=function(n){return function(){this._dateElement=n;return this;};};for(var k=0;k<px.length;k++){de=px[k].toLowerCase();$D[de]=$D[de+"s"]=ef(px[k]);$N[de]=$N[de+"s"]=nf(de);}}());Date.prototype.toJSONString=function(){return this.toString("yyyy-MM-ddThh:mm:ssZ");};Date.prototype.toShortDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortDatePattern);};Date.prototype.toLongDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.longDatePattern);};Date.prototype.toShortTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortTimePattern);};Date.prototype.toLongTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.longTimePattern);};Date.prototype.getOrdinal=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th";}};(function(){Date.Parsing={Exception:function(s){this.message="Parse error at '"+s.substring(0,10)+" ...'";}};var $P=Date.Parsing;var _=$P.Operators={rtoken:function(r){return function(s){var mx=s.match(r);if(mx){return([mx[0],s.substring(mx[0].length)]);}else{throw new $P.Exception(s);}};},token:function(s){return function(s){return _.rtoken(new RegExp("^\s*"+s+"\s*"))(s);};},stoken:function(s){return _.rtoken(new RegExp("^"+s));},until:function(p){return function(s){var qx=[],rx=null;while(s.length){try{rx=p.call(this,s);}catch(e){qx.push(rx[0]);s=rx[1];continue;}
break;}
return[qx,s];};},many:function(p){return function(s){var rx=[],r=null;while(s.length){try{r=p.call(this,s);}catch(e){return[rx,s];}
rx.push(r[0]);s=r[1];}
return[rx,s];};},optional:function(p){return function(s){var r=null;try{r=p.call(this,s);}catch(e){return[null,s];}
return[r[0],r[1]];};},not:function(p){return function(s){try{p.call(this,s);}catch(e){return[null,s];}
throw new $P.Exception(s);};},ignore:function(p){return p?function(s){var r=null;r=p.call(this,s);return[null,r[1]];}:null;},product:function(){var px=arguments[0],qx=Array.prototype.slice.call(arguments,1),rx=[];for(var i=0;i<px.length;i++){rx.push(_.each(px[i],qx));}
return rx;},cache:function(rule){var cache={},r=null;return function(s){try{r=cache[s]=(cache[s]||rule.call(this,s));}catch(e){r=cache[s]=e;}
if(r instanceof $P.Exception){throw r;}else{return r;}};},any:function(){var px=arguments;return function(s){var r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){r=null;}
if(r){return r;}}
throw new $P.Exception(s);};},each:function(){var px=arguments;return function(s){var rx=[],r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){throw new $P.Exception(s);}
rx.push(r[0]);s=r[1];}
return[rx,s];};},all:function(){var px=arguments,_=_;return _.each(_.optional(px));},sequence:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;if(px.length==1){return px[0];}
return function(s){var r=null,q=null;var rx=[];for(var i=0;i<px.length;i++){try{r=px[i].call(this,s);}catch(e){break;}
rx.push(r[0]);try{q=d.call(this,r[1]);}catch(ex){q=null;break;}
s=q[1];}
if(!r){throw new $P.Exception(s);}
if(q){throw new $P.Exception(q[1]);}
if(c){try{r=c.call(this,r[1]);}catch(ey){throw new $P.Exception(r[1]);}}
return[rx,(r?r[1]:s)];};},between:function(d1,p,d2){d2=d2||d1;var _fn=_.each(_.ignore(d1),p,_.ignore(d2));return function(s){var rx=_fn.call(this,s);return[[rx[0][0],r[0][2]],rx[1]];};},list:function(p,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return(p instanceof Array?_.each(_.product(p.slice(0,-1),_.ignore(d)),p.slice(-1),_.ignore(c)):_.each(_.many(_.each(p,_.ignore(d))),px,_.ignore(c)));},set:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return function(s){var r=null,p=null,q=null,rx=null,best=[[],s],last=false;for(var i=0;i<px.length;i++){q=null;p=null;r=null;last=(px.length==1);try{r=px[i].call(this,s);}catch(e){continue;}
rx=[[r[0]],r[1]];if(r[1].length>0&&!last){try{q=d.call(this,r[1]);}catch(ex){last=true;}}else{last=true;}
if(!last&&q[1].length===0){last=true;}
if(!last){var qx=[];for(var j=0;j<px.length;j++){if(i!=j){qx.push(px[j]);}}
p=_.set(qx,d).call(this,q[1]);if(p[0].length>0){rx[0]=rx[0].concat(p[0]);rx[1]=p[1];}}
if(rx[1].length<best[1].length){best=rx;}
if(best[1].length===0){break;}}
if(best[0].length===0){return best;}
if(c){try{q=c.call(this,best[1]);}catch(ey){throw new $P.Exception(best[1]);}
best[1]=q[1];}
return best;};},forward:function(gr,fname){return function(s){return gr[fname].call(this,s);};},replace:function(rule,repl){return function(s){var r=rule.call(this,s);return[repl,r[1]];};},process:function(rule,fn){return function(s){var r=rule.call(this,s);return[fn.call(this,r[0]),r[1]];};},min:function(min,rule){return function(s){var rx=rule.call(this,s);if(rx[0].length<min){throw new $P.Exception(s);}
return rx;};}};var _generator=function(op){return function(){var args=null,rx=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments);}else if(arguments[0]instanceof Array){args=arguments[0];}
if(args){for(var i=0,px=args.shift();i<px.length;i++){args.unshift(px[i]);rx.push(op.apply(null,args));args.shift();return rx;}}else{return op.apply(null,arguments);}};};var gx="optional not ignore cache".split(/\s/);for(var i=0;i<gx.length;i++){_[gx[i]]=_generator(_[gx[i]]);}
var _vector=function(op){return function(){if(arguments[0]instanceof Array){return op.apply(null,arguments[0]);}else{return op.apply(null,arguments);}};};var vx="each any all".split(/\s/);for(var j=0;j<vx.length;j++){_[vx[j]]=_vector(_[vx[j]]);}}());(function(){var flattenAndCompact=function(ax){var rx=[];for(var i=0;i<ax.length;i++){if(ax[i]instanceof Array){rx=rx.concat(flattenAndCompact(ax[i]));}else{if(ax[i]){rx.push(ax[i]);}}}
return rx;};Date.Grammar={};Date.Translator={hour:function(s){return function(){this.hour=Number(s);};},minute:function(s){return function(){this.minute=Number(s);};},second:function(s){return function(){this.second=Number(s);};},meridian:function(s){return function(){this.meridian=s.slice(0,1).toLowerCase();};},timezone:function(s){return function(){var n=s.replace(/[^\d\+\-]/g,"");if(n.length){this.timezoneOffset=Number(n);}else{this.timezone=s.toLowerCase();}};},day:function(x){var s=x[0];return function(){this.day=Number(s.match(/\d+/)[0]);};},month:function(s){return function(){this.month=((s.length==3)?Date.getMonthNumberFromName(s):(Number(s)-1));};},year:function(s){return function(){var n=Number(s);this.year=((s.length>2)?n:(n+(((n+2000)<Date.CultureInfo.twoDigitYearMax)?2000:1900)));};},rday:function(s){return function(){switch(s){case"yesterday":this.days=-1;break;case"tomorrow":this.days=1;break;case"today":this.days=0;break;case"now":this.days=0;this.now=true;break;}};},finishExact:function(x){x=(x instanceof Array)?x:[x];var now=new Date();this.year=now.getFullYear();this.month=now.getMonth();this.day=1;this.hour=0;this.minute=0;this.second=0;for(var i=0;i<x.length;i++){if(x[i]){x[i].call(this);}}
this.hour=(this.meridian=="p"&&this.hour<13)?this.hour+12:this.hour;if(this.day>Date.getDaysInMonth(this.year,this.month)){throw new RangeError(this.day+" is not a valid value for days.");}
var r=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second);if(this.timezone){r.set({timezone:this.timezone});}else if(this.timezoneOffset){r.set({timezoneOffset:this.timezoneOffset});}
return r;},finish:function(x){x=(x instanceof Array)?flattenAndCompact(x):[x];if(x.length===0){return null;}
for(var i=0;i<x.length;i++){if(typeof x[i]=="function"){x[i].call(this);}}
if(this.now){return new Date();}
var today=Date.today();var method=null;var expression=!!(this.days!=null||this.orient||this.operator);if(expression){var gap,mod,orient;orient=((this.orient=="past"||this.operator=="subtract")?-1:1);if(this.weekday){this.unit="day";gap=(Date.getDayNumberFromName(this.weekday)-today.getDay());mod=7;this.days=gap?((gap+(orient*mod))%mod):(orient*mod);}
if(this.month){this.unit="month";gap=(this.month-today.getMonth());mod=12;this.months=gap?((gap+(orient*mod))%mod):(orient*mod);this.month=null;}
if(!this.unit){this.unit="day";}
if(this[this.unit+"s"]==null||this.operator!=null){if(!this.value){this.value=1;}
if(this.unit=="week"){this.unit="day";this.value=this.value*7;}
this[this.unit+"s"]=this.value*orient;}
return today.add(this);}else{if(this.meridian&&this.hour){this.hour=(this.hour<13&&this.meridian=="p")?this.hour+12:this.hour;}
if(this.weekday&&!this.day){this.day=(today.addDays((Date.getDayNumberFromName(this.weekday)-today.getDay()))).getDate();}
if(this.month&&!this.day){this.day=1;}
return today.set(this);}}};var _=Date.Parsing.Operators,g=Date.Grammar,t=Date.Translator,_fn;g.datePartDelimiter=_.rtoken(/^([\s\-\.\,\/\x27]+)/);g.timePartDelimiter=_.stoken(":");g.whiteSpace=_.rtoken(/^\s*/);g.generalDelimiter=_.rtoken(/^(([\s\,]|at|on)+)/);var _C={};g.ctoken=function(keys){var fn=_C[keys];if(!fn){var c=Date.CultureInfo.regexPatterns;var kx=keys.split(/\s+/),px=[];for(var i=0;i<kx.length;i++){px.push(_.replace(_.rtoken(c[kx[i]]),kx[i]));}
fn=_C[keys]=_.any.apply(null,px);}
return fn;};g.ctoken2=function(key){return _.rtoken(Date.CultureInfo.regexPatterns[key]);};g.h=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),t.hour));g.hh=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/),t.hour));g.H=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),t.hour));g.HH=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/),t.hour));g.m=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.minute));g.mm=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.minute));g.s=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.second));g.ss=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.second));g.hms=_.cache(_.sequence([g.H,g.mm,g.ss],g.timePartDelimiter));g.t=_.cache(_.process(g.ctoken2("shortMeridian"),t.meridian));g.tt=_.cache(_.process(g.ctoken2("longMeridian"),t.meridian));g.z=_.cache(_.process(_.rtoken(/^(\+|\-)?\s*\d\d\d\d?/),t.timezone));g.zz=_.cache(_.process(_.rtoken(/^(\+|\-)\s*\d\d\d\d/),t.timezone));g.zzz=_.cache(_.process(g.ctoken2("timezone"),t.timezone));g.timeSuffix=_.each(_.ignore(g.whiteSpace),_.set([g.tt,g.zzz]));g.time=_.each(_.optional(_.ignore(_.stoken("T"))),g.hms,g.timeSuffix);g.d=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.dd=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.ddd=g.dddd=_.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"),function(s){return function(){this.weekday=s;};}));g.M=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/),t.month));g.MM=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/),t.month));g.MMM=g.MMMM=_.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),t.month));g.y=_.cache(_.process(_.rtoken(/^(\d\d?)/),t.year));g.yy=_.cache(_.process(_.rtoken(/^(\d\d)/),t.year));g.yyy=_.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/),t.year));g.yyyy=_.cache(_.process(_.rtoken(/^(\d\d\d\d)/),t.year));_fn=function(){return _.each(_.any.apply(null,arguments),_.not(g.ctoken2("timeContext")));};g.day=_fn(g.d,g.dd);g.month=_fn(g.M,g.MMM);g.year=_fn(g.yyyy,g.yy);g.orientation=_.process(g.ctoken("past future"),function(s){return function(){this.orient=s;};});g.operator=_.process(g.ctoken("add subtract"),function(s){return function(){this.operator=s;};});g.rday=_.process(g.ctoken("yesterday tomorrow today now"),t.rday);g.unit=_.process(g.ctoken("minute hour day week month year"),function(s){return function(){this.unit=s;};});g.value=_.process(_.rtoken(/^\d\d?(st|nd|rd|th)?/),function(s){return function(){this.value=s.replace(/\D/g,"");};});g.expression=_.set([g.rday,g.operator,g.value,g.unit,g.orientation,g.ddd,g.MMM]);_fn=function(){return _.set(arguments,g.datePartDelimiter);};g.mdy=_fn(g.ddd,g.month,g.day,g.year);g.ymd=_fn(g.ddd,g.year,g.month,g.day);g.dmy=_fn(g.ddd,g.day,g.month,g.year);g.date=function(s){return((g[Date.CultureInfo.dateElementOrder]||g.mdy).call(this,s));};g.format=_.process(_.many(_.any(_.process(_.rtoken(/^(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),function(fmt){if(g[fmt]){return g[fmt];}else{throw Date.Parsing.Exception(fmt);}}),_.process(_.rtoken(/^[^dMyhHmstz]+/),function(s){return _.ignore(_.stoken(s));}))),function(rules){return _.process(_.each.apply(null,rules),t.finishExact);});var _F={};var _get=function(f){return _F[f]=(_F[f]||g.format(f)[0]);};g.formats=function(fx){if(fx instanceof Array){var rx=[];for(var i=0;i<fx.length;i++){rx.push(_get(fx[i]));}
return _.any.apply(null,rx);}else{return _get(fx);}};g._formats=g.formats(["yyyy-MM-ddTHH:mm:ss","ddd, MMM dd, yyyy H:mm:ss tt","ddd MMM d yyyy HH:mm:ss zzz","d"]);g._start=_.process(_.set([g.date,g.time,g.expression],g.generalDelimiter,g.whiteSpace),t.finish);g.start=function(s){try{var r=g._formats.call({},s);if(r[1].length===0){return r;}}catch(e){}
return g._start.call({},s);};}());Date._parse=Date.parse;Date.parse=function(s){var r=null;if(!s){return null;}
try{r=Date.Grammar.start.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};Date.getParseFunction=function(fx){var fn=Date.Grammar.formats(fx);return function(s){var r=null;try{r=fn.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};};Date.parseExact=function(s,fx){return Date.getParseFunction(fx)(s);};Date.prototype.age=function(){var today=Date.today();today={year:today.getFullYear(),month:today.getMonth()+1,day:today.getDate()};var birthdate={year:this.getFullYear(),month:this.getMonth()+1,day:this.getDate()};var age=today['year']-birthdate['year'];if((birthdate['month']>today['month'])||(birthdate['month']==today['month']&&today['day']<birthdate['day'])){age--;};return(age);};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;}};if(!this.JSON){JSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toJSON=function(key){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapeable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapeable.lastIndex=0;return escapeable.test(string)?'"'+string.replace(escapeable,function(a){var c=meta[a];if(typeof c==='string'){return c;}
return'\\u'+('0000'+
(+(a.charCodeAt(0))).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value,rep);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value,rep);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
return{stringify:function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});},parse:function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+
(+(a.charCodeAt(0))).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');}};}();}
(function($){var isObject=function(x){return(typeof x==='object')&&!(x instanceof Array)&&(x!==null);};$.extend({getJSONCookie:function(cookieName){var cookieData=$.cookie(cookieName);return cookieData?JSON.parse(cookieData):{};},setJSONCookie:function(cookieName,data,options){var cookieData='';options=$.extend({expires:90,path:'/'},options);if(!isObject(data)){throw new Error('JSONCookie data must be an object');}
cookieData=JSON.stringify(data);return $.cookie(cookieName,cookieData,options);},removeJSONCookie:function(cookieName){return $.cookie(cookieName,null);},JSONCookie:function(cookieName,data,options){if(data){$.setJSONCookie(cookieName,data,options);}
return $.getJSONCookie(cookieName);}});})(jQuery);(function($){$.facebox=function(data,klass){if($('#facebox').is(':visible')){$('#facebox .content').empty();}else{$.facebox.loading();}
if(data.ajax)fillFaceboxFromAjax(data.ajax,klass)
else if(data.image)fillFaceboxFromImage(data.image,klass)
else if(data.div)fillFaceboxFromHref(data.div,klass)
else if($.isFunction(data))data.call($)
else $.facebox.reveal(data,klass)}
$.extend($.facebox,{hideOverlay:hideOverlay,showOverlay:showOverlay,settings:{opacity:0.50,overlay:true,loadingImage:'/images/facebox/loading.gif',closeImage:'/images/facebox/closelabel.gif',imageTypes:['png','jpg','jpeg','gif'],spinnerHtml:'<div id="facebox-spinner" class="spinner"><span style="display:none"></span></div>',faceboxHtml:'\
    <div id="facebox" style="display:none;"> \
      <div class="body"> \
        <a href="#" class="close"> \
          <span class="hide">close</span> \
        </a> \
        <div class="content"> \
        </div> \
      </div> \
    </div>'},loading:function(){init()
if($('#facebox .loading').length==1)return true
showOverlay()
$('#facebox .content').empty()
$('#facebox .body').children().hide().end();$('#facebox').css({top:getPageScroll()[1],left:$(window).width()/2-205}).show()
$(document).bind('keydown.facebox',function(e){if(e.keyCode==27)$.facebox.close()
return true})
$(document).trigger('loading.facebox')},reveal:function(data,klass){$(document).trigger('beforeReveal.facebox')
if(klass){$('#facebox').addClass(klass);}else{$('#facebox').attr('class','');};$('#facebox .content').append(data).append($.facebox.settings.spinnerHtml)
$('#facebox .loading').remove()
$('#facebox .body').children().fadeIn('normal')
$('#facebox').css('left',$(window).width()/2-($('#facebox .body').width()/2))
$(document).trigger('reveal.facebox').trigger('afterReveal.facebox')},close:function(){$(document).trigger('close.facebox')
return false}})
$.fn.facebox=function(settings){if($(this).length==0)return
init(settings)
function clickHandler(){$.facebox.loading(true)
var klass=this.rel.match(/facebox\[?\.(\w+)\]?/)
if(klass)klass=klass[1]
fillFaceboxFromHref(this.href,klass)
return false}
return this.bind('click.facebox',clickHandler)}
function init(settings){if($.facebox.settings.inited)return true
else $.facebox.settings.inited=true
$(document).trigger('init.facebox')
makeCompatible()
var imageTypes=$.facebox.settings.imageTypes.join('|')
$.facebox.settings.imageTypesRegexp=new RegExp('\.('+imageTypes+')$','i')
if(settings)$.extend($.facebox.settings,settings)
$('body').append($.facebox.settings.faceboxHtml)
var preload=[new Image(),new Image()]
preload[0].src=$.facebox.settings.closeImage
preload[1].src=$.facebox.settings.loadingImage
$('#facebox').find('.b:first, .bl').each(function(){preload.push(new Image())
preload.slice(-1).src=$(this).css('background-image').replace(/url\((.+)\)/,'$1')})
$('#facebox .close').click($.facebox.close)
$('#facebox .close_image').attr('src',$.facebox.settings.closeImage)}
function getPageScroll(){var xScroll,yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;xScroll=self.pageXOffset;}else if(document.documentElement&&document.documentElement.scrollTop){yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;}else if(document.body){yScroll=document.body.scrollTop;xScroll=document.body.scrollLeft;}
return new Array(xScroll,yScroll)}
function getPageHeight(){var windowHeight
if(self.innerHeight){windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowHeight=document.documentElement.clientHeight;}else if(document.body){windowHeight=document.body.clientHeight;}
return windowHeight}
function makeCompatible(){var $s=$.facebox.settings
$s.loadingImage=$s.loading_image||$s.loadingImage
$s.closeImage=$s.close_image||$s.closeImage
$s.imageTypes=$s.image_types||$s.imageTypes
$s.faceboxHtml=$s.facebox_html||$s.faceboxHtml}
function fillFaceboxFromHref(href,klass){if(href.match(/#/)){var url=window.location.href.split('#')[0]
var target=href.replace(url,'')
if(target=='#')return
$.facebox.reveal($(target).html(),klass)}else if(href.match($.facebox.settings.imageTypesRegexp)){fillFaceboxFromImage(href,klass)}else{fillFaceboxFromAjax(href,klass)}}
function fillFaceboxFromImage(href,klass){var image=new Image()
image.onload=function(){$.facebox.reveal('<div class="image"><img src="'+image.src+'" /></div>',klass)}
image.src=href}
function fillFaceboxFromAjax(href,klass){$.get(href,function(data){$.facebox.reveal(data,klass)})}
function skipOverlay(){return $.facebox.settings.overlay==false||$.facebox.settings.opacity===null}
function showOverlay(){if(skipOverlay())return
if($('#facebox_overlay').length==0)
$("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')
$('#facebox_overlay').hide().addClass("facebox_overlayBG").css('opacity',$.facebox.settings.opacity).click(function(){$(document).trigger('close.facebox')}).fadeIn(50)
return false}
function hideOverlay(){if(skipOverlay())return
$('#facebox_overlay').fadeOut(50,function(){$("#facebox_overlay").removeClass("facebox_overlayBG")
$("#facebox_overlay").addClass("facebox_hide")
$("#facebox_overlay").remove()})
return false}
$(document).bind('close.facebox',function(){$(document).unbind('keydown.facebox')
$('#facebox').fadeOut("fast",function(){$('#facebox .content').removeClass().addClass('content')
hideOverlay()
$('#facebox .loading').remove()})})})(jQuery);(function($){$.extend({escapeHTML:function(string){return $('<div/>').text(string).html();}});$.fn.extend({vark_now:function(complete,options){return $(this).each(function(){var vark_options=VARK.build_vark_ajax_options(this,complete,options);$(this).trigger('vark_ajax');VARK.vark_ajax(vark_options);});},varkify:function(complete,options){return $(this).each(function(){var vark_options=VARK.build_vark_ajax_options(this,complete,options);$(this)[vark_options.action](function(){$(this).trigger('vark_ajax');VARK.vark_ajax(vark_options);return false;});});}});})(jQuery);var LAST_JSON;var BH;(function($){VARK=function(){var ready_stack=[],is_ready=false;var behaviors={};$('a[rel*=facebox]').facebox();behaviors.set_timer_to_poll_for_greeting_widget=function(){if(RAILS_ENV!='test'&&RAILS_ENV!='development'){VARK.update_greeting();setInterval("VARK.update_greeting()",30000);};};behaviors.enable_buttons=function(){enable_all_inputs();$(document).bind("ajaxComplete",function(){enable_all_inputs();});};var SIGNIN_FORM_HTML;show_signin_form=function(){if(!SIGNIN_FORM_HTML){var form=$('#signin_form-wrapper');SIGNIN_FORM_HTML=form.html();form.remove();};$.facebox(SIGNIN_FORM_HTML);behaviors.signin_form();Mixpanel.log_funnel('MAIN-ASK SIGNUP v2',4,'click sign in or signup',{},{click:'sign-in'});}
behaviors.signin_link=function(){$('.signin_link').click(function(){show_signin_form();return false;});};behaviors.pound_signin_or_signup=function(){var body=$('body');if((window.location.hash!=""&&window.location.hash.substring(1,200)=='signin')||(body.hasClass('c_sessions')&&body.hasClass('a_new'))){VARK.ready(function(){show_signin_form();});}
if((window.location.hash!=""&&window.location.hash.substring(1,200)=='signup')){VARK.ready(function(){VARK.signup.open_signup_modal();});}};behaviors.signin_form=function(){$('input.session_email').trigger('focus');VARK.facebook.behaviors.connect_button($('#signin_form-facebook'));VARK.openid.behaviors.init();VARK.behaviors.form_shadow_text($('form#new_session'));};behaviors.form_shadow_text=function(form){$('label span.hide',form).each(function(){var label_value=$(this).text();var input=$(this).closest('li').find(':input');if(input[0].nodeName.toLowerCase()!='textarea'){$(input).watermark(label_value);}else{if(input.val()==''){input.addClass('shadow').val(label_value);}
input.focus(function(){if(input.val()==label_value){input.removeClass('shadow').val('');}});input.blur(function(){if(input.val()==''){input.addClass('shadow').val(label_value);}});}});$(form).bind('vark_ajax',function(){$('label span.hide',form).each(function(){var label_value=$(this).text();var input=$(this).closest('li').find(':input');if(input.val()==label_value){input.removeClass('shadow').val('');}})})};behaviors.close_popup=function(popup,target,callback){$('body').undelegate('click').delegate('click','*',function(event){var in_popup=false;var popup_elements=[target];$(this).parents().each(function(){if(popup_elements.indexOf(this)!=-1){in_popup=true;return false;}});if(!in_popup){$(popup).hide();$('body').undelegate('click');if(callback){callback();}};})};behaviors.close_tooltip=function(tooltip,callback){$('html').undelegate('click').delegate('click','*',function(event){var in_tooltip=false;var tooltip_element=tooltip['getTip']?tooltip.getTip()[0]:tooltip;$(this).parents().each(function(){if(this==tooltip_element){in_tooltip=true;return false;}});if(!in_tooltip){tooltip.hide();$('body').undelegate('click');if(callback){callback();}};})};behaviors.badge_friend_tools=function(context,ignore){$(".add-friend",context).click(function(){$(this).siblings("form.add-friend-form").vark_now(function(json){if(ignore){$(this).closest(".friend-box").fadeOut(function(){$(this).remove();if($(".friend-box").length==0){window.location.href="/network/people_you_may_know";}});}
else{$("."+json.dom_id).replaceWith(json.html);}});return false;});$(".block-user, .remove-friend",context).click(function(){$(this).siblings("form.block-friend-form").vark_now(function(json){if(json.success){$("."+json.dom_id).replaceWith(json.html);}});return false;});$("form.ignore-suggested-connection-form").varkify(function(json){if(json.success){$(this).closest(".friend-box").fadeOut(function(){$(this).remove();update_page_numbers();update_people_count();if($(".friend-box").length==0){window.location.href="/network/people_you_may_know";}});}});$(".unblock-user",context).click(function(){$(this).siblings("form.unblock-friend-form").vark_now(function(json){if(json.success){$("."+json.dom_id).replaceWith(json.html);}});return false;});};behaviors.badge_popup=function(){$('.badge.with_popup .name').each(function(){var badge=$(this).closest('.badge');var tooltip_element=badge.children('.extra');var tooltip_opts={tip:tooltip_element,position:'bottom left',relative:true,offset:[22,200],delay:250,events:{def:"click,click"},api:true,onShow:function(event){VARK.behaviors.close_tooltip(this);return false;}};if(badge.hasClass('always_on')){tooltip_opts['onBeforeHide']=function(){return false};};var api=$(this).tooltip(tooltip_opts);if(badge.hasClass('always_on')){api.show();}
var img=badge.find('.avatar');img.click(function(){$(this).next('.name').trigger("click");return false;});});$('.badge.with_popup .avatar, .badge.with_popup .name').hover(function(){$(this).closest('.badge').addClass('hot');},function(){$(this).closest('.badge').removeClass('hot');});};behaviors.tooltips=function(){$(".help.tooltip_trigger").each(function(){setup_tooltip(this);});};behaviors.expandable=function(){$('.expandable a.expandable-icon, .expandable a.expandable-toggle').click(function(){toggle_section($(this).parents('.expandable'));return false;})};behaviors.expand_anchor_section=function(){if(window.location.hash!=""){$('.expandable').removeClass('expanded');var name=window.location.hash.substring(1,200);var expandable=$('a[name='+name+']').parents('.expandable');show_section(expandable);}};behaviors.fill_question=function(city){$(".fill-question").click(function(){var question_content='';if($(this).html()=="awesome new bands"){question_content="I'm looking for some new music -- can anyone recommend an awesome new band?";}
if($(this).html()=="date ideas"){question_content="Can anyone recommend a great date activity in "+city+"?";}
if($(this).html()=="Ask Aardvark for more tips"){question_content="Can anyone recommend some tips for relieving stress when I'm busy at work?";}
if(window.location.href.indexOf('/ask')>0){$("#web_question_content").html(question_content);}
else{window.location.href='/ask?q='+question_content;}
return false;});};var update_greeting=function(){json_request({url:'/get_greeting',type:'GET',complete:function(json){if(json.success){$("div#nav-greeting-msg").fadeOut("slow",function(){$('div#nav-greeting-msg .nav-greeting-msg').html(json.html);$("div#nav-greeting-msg").fadeIn("slow");});VARK.behaviors.fill_question(json.city);}}});};var apply_behaviors=function(behaviors,silence){BH=behaviors;$(behaviors).each(function(){try{window["eval"](this.toString());}catch(e){if(silence){console.log('Error loading '+this,e.toString());}else{throw e;}}});};var toggle_section=function(expandable){$(expandable).toggleClass('expanded');};var show_section=function(expandable){$(expandable).addClass('expanded');};var spinner=function(id){if(id!=null){id=id+'-spinner';}else{id='spinner';}
return'<div id="'+id+'" class="spinner"><span></span></div>';};var enable_all_inputs=function(context){$(':button:disabled, :submit:disabled, :image:disabled',context).removeAttr('disabled');};var hash_to_associative_array=function(h){var arr=[];$.each(h,function(k,v){arr[arr.length]={name:k,value:v};});return arr;};var flash_timer=null;var show_flash=function(time_in_seconds){var time=5000;if(!(typeof(time_in_seconds)=='undefined')){time=time_in_seconds*1000;}
clearTimeout(flash_timer);jQuery('#flash_container').fadeIn();flash_timer=setTimeout(function(){jQuery('#flash_container').fadeOut();},time);$("body").bind("click",function(){clearTimeout(flash_timer);jQuery('#flash_container').fadeOut();$("body").unbind("click");});};var sticky_flash=function(){clearTimeout(flash_timer);jQuery('#flash_container').fadeIn();};var update_flash=function(json,options){if(json.flash&&(json.flash.errors||json.flash.notices)){var str='';if(json.flash.errors){str+='<ul class="errors">';$.each(json.flash.errors,function(key,value){str+='<li>'+value+'</li>';});str+='</ul>';}
if(json.flash.notices){str+='<ul class="notices">';$.each(json.flash.notices,function(key,value){str+='<li>'+value+'</li>';});str+='</ul>';}
if(str.length>0){$("#flash-ul").html(str);show_flash();}};};var locks={};var with_lock=function(routine,lock_key){if(locks[lock_key]){return false;}
locks[lock_key]=true;return routine(function(){delete locks[lock_key];});};var without_lock=function(routine){return routine(function(){});};var build_vark_ajax_options=function(element,complete,options){var vark_options={complete:complete};options=options||{};if(element.nodeName.toUpperCase()=="FORM"){vark_options.action='submit';vark_options.form=element;}else if(element.nodeName.toUpperCase()=="A"){vark_options.action='click';vark_options.url=$(element).attr('href');}else{throw("You must pass a <form> or an <a> tag");};if(options.spinner!=null){vark_options.spinner=options.spinner;}else if($(element).find('.spinner').length>0){vark_options.spinner=$(element).find('.spinner');};vark_options.element=element;return vark_options;};var vark_ajax=function(options){var spinner;var request_options={url:options.url,form:options.form,data:options.data,type:options.type}
if(options.with_lock==null){options.with_lock=true;}
if(options.spinner!=null){spinner=$(options.spinner);}else{if($('#facebox').is(':visible')){spinner=$('#facebox-spinner');}else{spinner=$('#application-spinner');}}
var spinner_span=spinner.children('span');var routine=function(unlock){spinner_span.show();var old_complete;if($.isFunction(options.complete)){old_complete=options.complete;}else{old_complete=function(){};}
request_options.complete=function(json){unlock();spinner_span.hide();if(json.status!=500){old_complete.apply(options.element||this,[json]);};};VARK.json_request(request_options);};if(options.with_lock){return with_lock(routine,options.with_lock);}else{return without_lock(routine);};};var json_request=function(options){var url=(options.form&&options.form.action)||options.url;var data=options.data||{};var type;if(options.form){var form_data=$(options.form).serializeArray();data=$.merge(form_data,hash_to_associative_array(data));type=$(options.form).attr('method');}else if(options.data){type='POST';}else{type='GET';}
if($.isArray(data)){data[data.length]={name:'format',value:'jsonh'};}else if(typeof data=='string'){data=data+"&format=jsonh";}else{data['format']='jsonh';}
var ajax_options={};ajax_options.url=url;ajax_options.data=data;ajax_options.type=options.type||type;ajax_options.dataType='json';ajax_options.complete=function(event,xhr){var json={};if(event.status==0){return false;}else if(event.responseText==' '){json.status='500';}else{try{json=window["eval"](["(",event.responseText,")"].join(''));LAST_JSON=json;}catch(error){json.status='500';}}
json.status=parseInt(json.status);json.success=(json.status>=200&&json.status<300);json.redirect=(json.status>=300&&json.status<400);json.invalid=(json.status==422);if(json.status==500){json.flash={'errors':['Oops, there was a problem!<br/>The Aardvark team has been notified.']};}
if(json.status==401){window.location.href='/#signin';}
if(json.redirect_to){window.location.href=json.redirect_to;};if($.isFunction(options.complete)){options.complete(json);}
if(json.behaviors){window["eval"](json.behaviors);}
update_flash(json);}
$.ajax(ajax_options);};setup_tooltip=function(element){var tip=$($(element).attr('rel'));if($(element).hasClass('left')){var position='bottom left';var offset=[20,100]
tip.addClass(position);}else{var position='bottom right';var offset=[20,-162];tip.addClass(position);}
$(element).tooltip({tip:tip,position:position,relative:true,offset:offset,delay:250,events:{def:"click,blur"},onBeforeShow:function(event){if(this.isShown()){this.hide();return false;};},onShow:function(event){VARK.behaviors.close_tooltip(this);return false;},api:true});};var ready=function(callback){if(is_ready){return callback();}
ready_stack.push(callback);};var apply_initial_behaviors=function(behaviors){apply_behaviors(behaviors);is_ready=true;var cb=null;while(cb=ready_stack.shift()){cb();}};var check_cookies_enabled=function(){var value=new Date();value=value.getTime().toString();$.cookie('_test',value);if($.cookie('_test')!=value){return false;}else{$.cookie('_test',null);return true;}};var update_page_numbers=function(){var ending_page_number=parseInt($('span.end_page').html());$('span.end_page').html(ending_page_number-1);var total_count=parseInt($("span.total_pages").html());$("span.total_pages").html(total_count-1);};var update_people_count=function(){var total_people_str=$.trim($("div.title").find("span").html());var end=total_people_str.indexOf('p');var total_count=parseInt($.trim(total_people_str.substr(0,end)));if((total_count-1)==1){$("div.title").find("span").html("1 person");}
else{$("div.title").find("span").html((total_count-1).toString()+" people");}};var poll_status=function(url,callback,on_timeout){var started_at=new Date();var f=function(url,callback){if((typeof(on_timeout)!='undefined')&&((new Date()-started_at)>120000)){console.debug("TIMEOUT");on_timeout();}else{VARK.json_request({url:url,type:'GET',spinner:false,complete:function(json){switch(json.status){case 202:setTimeout(function(){f(url,callback)},1000);break;case 201:callback.apply(window,[json]);break;default:VARK.update_flash({flash:{errors:['Oops! An error occured while syncing with Facebook. Please try again.']}});}}});}}
f(url,callback);};var poll_until_redirect=function(polling_url,location,on_timeout){var job_complete=function(json){window.location.href=location;}
VARK.poll_status(polling_url,job_complete,on_timeout);};var open_popup=function(href,instanceSettings){var defaultSettings={centerBrowser:0,centerScreen:0,height:500,left:0,location:0,menubar:0,resizable:0,scrollbars:0,status:0,width:500,windowName:null,windowURL:null,top:0,toolbar:0};var settings;settings=$.extend({},defaultSettings,instanceSettings||{});var windowFeatures='height='+settings.height+',width='+settings.width+',toolbar='+settings.toolbar+',scrollbars='+settings.scrollbars+',status='+settings.status+',resizable='+settings.resizable+',location='+settings.location+',menuBar='+settings.menubar;settings.windowName=settings.windowName;settings.windowURL=href;var centeredY,centeredX;if(settings.centerBrowser){if($.browser.msie){centeredY=(window.screenTop-120)+((((document.documentElement.clientHeight+120)/2)-(settings.height/2)));centeredX=window.screenLeft+((((document.body.offsetWidth+20)/2)-(settings.width/2)));}else{centeredY=window.screenY+(((window.outerHeight/2)-(settings.height/2)));centeredX=window.screenX+(((window.outerWidth/2)-(settings.width/2)));}
window.open(settings.windowURL,settings.windowName,windowFeatures+',left='+centeredX+',top='+centeredY).focus();}else if(settings.centerScreen){centeredY=(screen.height-settings.height)/2;centeredX=(screen.width-settings.width)/2;window.open(settings.windowURL,settings.windowName,windowFeatures+',left='+centeredX+',top='+centeredY).focus();}else{window.open(settings.windowURL,settings.windowName,windowFeatures+',left='+settings.left+',top='+settings.top).focus();}
return false;};return{behaviors:behaviors,apply_behaviors:apply_behaviors,apply_initial_behaviors:apply_initial_behaviors,hash_to_associative_array:hash_to_associative_array,show_flash:show_flash,sticky_flash:sticky_flash,update_flash:update_flash,json_request:json_request,build_vark_ajax_options:build_vark_ajax_options,vark_ajax:vark_ajax,spinner:spinner,with_lock:with_lock,without_lock:without_lock,toggle_section:toggle_section,update_greeting:update_greeting,ready:ready,check_cookies_enabled:check_cookies_enabled,poll_status:poll_status,poll_until_redirect:poll_until_redirect,open_popup:open_popup};}();})(jQuery);if(!Array.prototype.indexOf)
{Array.prototype.indexOf=function(elt)
{var len=this.length>>>0;var from=Number(arguments[1])||0;from=(from<0)?Math.ceil(from):Math.floor(from);if(from<0)
from+=len;for(;from<len;from++)
{if(from in this&&this[from]===elt)
return from;}
return-1;};}
(function($){Mixpanel=function(){log_funnel=function(funnel,step,goal,properties,super_properties){if(typeof mpmetrics=="undefined"){return;}
var props=prepare_properties(properties,super_properties);mpmetrics.track_funnel(funnel,step,goal,props);};log_mp_event=function(event,properties,super_properties){if(typeof mpmetrics=="undefined"){return;}
var props=prepare_properties(properties,super_properties);mpmetrics.track_event(event,props);};prepare_properties=function(properties,super_properties){properties=properties||{};properties.distinct_id=Mixpanel.mixpanel_id();if(super_properties){jQuery.setJSONCookie('mp_super_properties',jQuery.extend(jQuery.getJSONCookie('mp_super_properties'),super_properties));}
super_properties=jQuery.getJSONCookie('mp_super_properties');return jQuery.extend(super_properties,properties);};mixpanel_id=function(){if(!jQuery.cookie('mixpanel_id')){jQuery.cookie('mixpanel_id',Math.ceil(10000000000*Math.random()),{expires:365,path:'/'})}
return jQuery.cookie('mixpanel_id');}
return{log_funnel:log_funnel,log_mp_event:log_mp_event,mixpanel_id:mixpanel_id};}();})(jQuery);VARK.facebook=function(){var api_key=null;var ready=false;var ready_stack=[];var loading=false;var window_loading=true;var behaviors={};behaviors.connect_button=function(element){load();var from_signin_form=($(element).parents('.signin_form').length>0);$(element).click(function(){on_connect_button(from_signin_form);return false;});};behaviors.connect_popup=function(){if(window.location.hash.substring(1,200)=='connect_with_offline_access'){ready_to_sync(false);}};behaviors.request_offline_button=function(element){load();$(element).click(function(){var tell_server=function(){var session=FB.Facebook.apiClient.get_session();VARK.json_request({data:{uid:session.uid,session_key:session.session_key},url:"/facebook_user_syncs/offline_access",type:'POST',complete:function(json){$(element).parent().hide();}});};if(offline_access_enabled()){tell_server();}
else{FB.Connect.showPermissionDialog('offline_access',function(granted){if(granted=='offline_access'){tell_server();}});}
return false;});};behaviors.log_out=function(){var signout_link=$('.sign_out');if(signout_link.text().toLowerCase()!="sign out"){return false;}
signout_link.click(function(){on_ready(function(){if(FB.Connect.get_loggedInUser()!=null){FB.Connect.logoutAndRedirect('/signout');}
else{window.location.href='/signout';}});return false;});};behaviors.render_serverfbml=function(element_class){on_ready(function(){FB.Connect.requireSession(function(){FB.XFBML.Host.parseDomElement($('.'+element_class)[0]);});});};var on_connect_button=function(signin){ready_to_sync(signin);};var ready_to_sync=function(signin){on_ready(function(){sync(function(json){VARK.json_request({url:json.location,type:'GET',complete:function(json){$.facebox(json.html);}});},signin);});};var start_sync=function(offline_access,callback,signin){var session=FB.Facebook.apiClient.get_session();var job={uid:session.uid,session_key:session.session_key,offline_access:offline_access};var from_signin_form=signin?1:0;VARK.json_request({data:{job:job,signin:from_signin_form},url:"/facebook_user_syncs/submit",complete:function(json){switch(json.status){case 202:$.facebox(json.html);$('#facebox-spinner span').show();VARK.poll_status(json.location,callback);break;case 302:$.facebox(json.html);break;case 303:window.location.href=json.location;break;default:VARK.update_flash({flash:{errors:['Oops! An error occured while syncing with Facebook. Please try again.']}});}}});};var offline_access_enabled=function(){var session=FB.Facebook.apiClient.get_session();return(session&&session.expires==0);};var on_offline_access=function(granted,callback){start_sync(granted,callback);};var on_connect=function(callback,signin){if(offline_access_enabled()){start_sync('1',callback,signin);}else{FB.Connect.showPermissionDialog('offline_access',function(granted){on_offline_access(granted?'1':'0',callback);});}};var sync=function(callback,signin){FB.Connect.requireSession(function(){on_connect(callback,signin);});};var start_loading=function(){$(window).unbind("load",start_loading);api_key=$('head meta[name=fb_api_key]').attr("content");$.getScript("http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US",function(){FB.Bootstrap.requireFeatures(["Connect"],function(){FB.Facebook.init(api_key,"/xd_receiver.htm");ready=true;var cb=null;while(cb=ready_stack.shift()){cb();}});});};var on_ready=function(callback){if(ready){return callback();}
ready_stack.push(callback);load();};var load=function(){if(!loading){loading=true;if(window_loading){$(window).bind("load",start_loading);}else{start_loading();}}};var post_feed=function(fb_id,invite_url,new_user,callback){$("#facebox .body").hide();var stream_text=new_user?'just signed up to answer questions on Aardvark! Join my network: '+invite_url:'I love Aardvark! Join my network so we can help each other out... '+invite_url;var prompt_text="What's on your mind?";var attachments={'name':'Aardvark','href':invite_url,'description':'Aardvark discovers the perfect person in your Facebook network to answer any question in minutes.','media':[{'type':'image','src':'http://vark.com/images/img_vark.jpg','href':invite_url}]};FB.Connect.requireSession(function(){FB.Connect.streamPublish(stream_text,attachments,null,fb_id,prompt_text,callback);});return false;};var redirect_to_fb_picker=function(){window.location.href="/invites/facebook";};var init=function(){$('body').append('<div id="FB_HiddenContainer" style="position: absolute; left: -10000px; top: -10000px; width: 0px; height: 0px;">&nbsp;</div>');$(window).bind("load",function(){window_loading=false;});};init();return{sync:function(){var self=this;var args=arguments;on_ready(function(){sync.apply(self,args);});},post_feed:function(){var self=this;var args=arguments;on_ready(function(){post_feed.apply(self,args);});},behaviors:behaviors,redirect_to_fb_picker:redirect_to_fb_picker,on_ready:on_ready,start_loading:start_loading};}();VARK.signup=function(){var signup_flow=false;var behaviors={};behaviors.link=function(){$('a.signup').click(function(){open_signup_modal();return false;})};behaviors.collect_topics=function(){VARK.json_request({url:'/collect_topics',type:'GET',complete:function(json){if(json.success){$.facebox(json.html);}}});};behaviors.scratch_form=function(){$('form#new_signup_validator').submit(function(){if(!VARK.check_cookies_enabled()){VARK.update_flash({flash:{'errors':['Please enable cookies in your browser in order to use Aardvark']}});return false;};$(this).vark_now(function(json){switch(json.status){case 201:if(VARK.openid.job_key){$.facebox(VARK.openid.please_wait_html);$('#facebox-spinner span').show();var after_sync_complete=function(json){VARK.signup.signup_flow=true;if(json.invitable_friends_on_aardvark_count>0){VARK.openid.show_contacts_on_aardvark(json.external_user_id);}else{window.location.href='/ask';};};var on_timeout=function(){window.location.href='/ask';};$(document).bind('facebox.close',on_timeout);VARK.poll_status('/portable_contacts_syncs/status?job_key='+VARK.openid.job_key,after_sync_complete,on_timeout);}else if(json.location){window.location.href=json.location;}else{$.facebox(json.html);}
break;default:$(this).replaceWith(json.html);}});return false;});$('form#new_signup_validator #signup_validator_user_attributes_birthdate').blur(function(){var date=Date.parse($(this).val());if(date){$(this).val(date.toString('MM/dd/yyyy'));}});$('form#new_signup_validator #signup_validator_user_attributes_location').autocomplete('/locations.jsonh',{matchContains:true,minChars:2,formatItem:function(row){return row.full_name;},dataType:'json',delay:200,matchSubset:false,parse:function(data){var locations=data.locations;var parsed=[];for(var i=0;i<locations.length;i++){var row=locations[i];if(row){parsed[parsed.length]={data:row,value:row.full_name,result:row.full_name};}}
return parsed;}});$('form#new_signup_validator #signup_validator_user_attributes_location').result(function(event,major,formatted){$('#signup_validator_user_attributes_city_location_id').val(major.id);VARK.json_request({url:'/locations/'+major.id+'/neighborhoods',type:'GET',complete:function(json){if(json.success){update_neighborhood_select(json.neighborhoods);}}});});};behaviors.choose=function(){$('a.scratch_signup').varkify(function(json){if(json.success){$.facebox(json.html);Mixpanel.log_funnel('MAIN-ASK SIGNUP v2',4,'click sign in or signup',{},{'click':'signup'});}});};behaviors.facebook_confirm=function(){$('#facebox a.next').click(function(){VARK.json_request({url:this.href,type:'GET',complete:function(json){$.facebox(json.html);}});return false;});};behaviors.after_create=function(){$('form#after_create_user').varkify(function(json){if(json.success){$.facebox.close();}else{$.facebox(json.html);}});};var update_neighborhood_select=function(options){if(options.length<1){$('#signup_validator_user_attributes_neighborhood_location_id').html('');$('#signup_validator_user_attributes_location_input').hide();}else{var options_html=['<option value="">Select a neighborhood</option>'];for(var i=0;i<options.length;i++){options_html.push(['<option value="',options[i].location.id,'">',options[i].location.name,'</option>'].join(''));}
$('#signup_validator_user_attributes_neighborhood_location_id').html(options_html.join(''));$('#signup_validator_user_attributes_neighborhood_location_input').show();}};var open_signup_modal=function(data){VARK.vark_ajax({url:'/signup',data:data,type:'GET',complete:function(json){$.facebox(json.html);},with_lock:'load_signup_form'});};return{behaviors:behaviors,open_signup_modal:open_signup_modal,signup_flow:signup_flow};}();VARK.interests=function(){var behaviors={};var user_interests=[];behaviors.load_user_interests=function(){$('ul#user_interests li span').each(function(){var user_term=$.trim($(this).text());user_interests[user_interests.length]=user_term.toLowerCase();})};behaviors.topics_tree=function(){load_topics_tree();$('div.topic-box ul.1, div.topic-box ul.2').delegate('click','a',function(){if($(this).hasClass('selected')){return false;};$(this).closest("ul").find("a").removeClass("hover_on");if($(this).hasClass('haschild')){$(this).addClass("hover_on");};var menu2=$(this).parents("div.topic-box ul").next("div.topic-box ul");menu2.empty();var tree=$(this).next("ul");if(tree.length==0){$(this).removeClass("add").addClass("selected");add_interest($(this).text(),'profile_addmore');}
tree.children().children("ul").hide();menu2.append(tree.children().clone());add_styles(menu2);menu2.show();menu2.next("div.topic-box ul").empty().next("div.topic-box ul").empty();return false;});$('ul.3').delegate('click','a',function(){var input=$(this);input.removeClass("add").addClass("selected");add_interest(input.text(),'profile_addmore');return false;});};behaviors.suggested_interest_li=function(){$('#suggested_interest_list form').submit(function(){if($(this).hasClass('add_interest')){var keyword=$(this).closest('li').find('.user_term').text();add_interest_to_interface(keyword);}
$(this).vark_now(null,{spinner:false});$(this).closest('li').fadeOut('fast');if($("#suggested_interest_list").children("li").length==0){$("#suggested_topics-container").fadeOut('fast');}
return false;})};behaviors.muted_interest_li=function(){$('#muted_interest_list').delegate('click','input',function(){var input=this;$(input).closest('li').fadeOut();$(input.form).vark_now(null,{spinner:false});return false;});};behaviors.muted_interest_form=function(){$('form#mute_interest_form').varkify(function(json){if(json.success){$('#muted_interest_list').append(json.html);var field=$(this).find('#mute_interest_form-user_term');remove_interest(field.val(),true);field.val('');}});};behaviors.interest_li=function(){$('#user_interests').delegate('click','input',function(){var keyword=$(this).closest('.interest').find('.user_term').text();remove_interest(keyword);return false;});};behaviors.new_interest_form=function(){$('form#new_interest').submit(function(){var user_term=$('#interest_user_term').val();if(!user_term==''){if(!add_interest(user_term,'profile_addmore')){$('ul#user_interests .user_term').each(function(){if($(this).text().toLowerCase()==user_term.toLowerCase()){$(this).closest('.interest').hide().fadeIn();};})}
$('#interest_user_term').val('').trigger('focus');};return false;})};behaviors.user_setting_auto_add_interests=function(){$('#user_auto_add_interests').click(function(){$('#edit_user_text').html('');var form=$(this).closest('form')[0];$(form).vark_now(function(json){$('#edit_user_text').html(json.html);});});};var add_interest=function(user_term,added_context){if(user_term.match(/any (.*) question/)){user_term=user_term.replace(/any (.*) question/,"$1");}
if(add_interest_to_interface(user_term)){var data={'interest':{'user_term':user_term,'added_context':added_context}};VARK.vark_ajax({url:'/interests',type:'POST',data:data,with_lock:false,spinner:false});return true;}else{return false;}}
var add_interest_to_interface=function(user_term){user_term=$.trim(user_term);if(user_term.match(/any (.*) question/)){user_term=user_term.replace(/any (.*) question/,"$1");}
if(interest_is_active(user_term)){return false;};user_interests[user_interests.length]=user_term.toLowerCase();tmpl='<li class="interest" style="display:none">'+'<form class="delete_interest" title="Remove this topic" method="post" action="/interests/destroy_by_user_term">'+'<input type="image" src="/images/blank.png"/>'+'<input type="hidden" value="#{escaped_user_term}" name="user_term"/>'+'</form>'+'<span class="user_term">'+'#{user_term}'+'</span>'+'</li>'
$('#user_interests').append($.tmpl(tmpl,{'user_term':user_term,'escaped_user_term':$.escapeHTML(user_term)},{escape:false}));$('#user_interests li:last').fadeIn();$('.topic-menu').each(function(){add_styles($(this));});return true;};var remove_interest=function(keyword,skip_ajax){keyword=$.trim(keyword).toLowerCase();var k;if(k=interest_is_active(keyword)){user_interests.splice(k.index,1);$("#user_interests li.interest").each(function(){if($.trim($(this).text().toLowerCase())==keyword){$(this).fadeOut('fast');}});$('.topic-menu').each(function(){add_styles($(this));})
if(!skip_ajax){var data={'user_term':keyword};VARK.vark_ajax({url:'/interests/destroy_by_user_term',type:'POST',data:data,with_lock:false,spinner:false});}
return true;}else{return false}};var add_styles=function(menu){$.each(menu.children("li").children("a"),function(index,cur){if($(cur).next("ul").length==0){if(interest_is_active($(cur).text())){$(cur).removeClass('add').addClass("selected");}else{$(cur).removeClass('selected').addClass("add");};}
else{$(cur).addClass("haschild");}});};var load_topics_tree=function(){var menu=$("div.topic-box ul.1");var tree=$("#topics-tree");tree.children().children().children("ul").hide();menu.append(tree.children().children());$.each(menu.children("li").children("a"),function(index,cur){if($(cur).next("ul").length==0){$(cur).addClass("add");}else{$(cur).addClass("haschild");}});};var interest_is_active=function(value){var index=user_interests.indexOf($.trim(value).toLowerCase());if(index==-1){if(value.match(/any (.*) question/)){value=value.replace(/any (.*) question/,"$1");}
index=user_interests.indexOf($.trim(value).toLowerCase());}
if(index!=-1){return{index:index};}else{return false;}};var handle_secure_hash=function(){var content=$('meta[name=secure_hash]').attr('content');if(!content){return;}
var matches=content.split(':',2);if(!matches){return;}
switch(matches[0]){case'mute':if(!$('#muted_interest_list').is(':visible')){$('div.muted_topics_expandable').children('a.expandable-toggle:first').trigger('click');}
$.scrollTo('div.muted_topics_expandable',400);$('#mute_interest_form-user_term').prev('.watermark').trigger('click');$('#mute_interest_form-user_term').trigger('keydown').val(matches[1]);$('#mute_interest_form').trigger('submit');break;}};VARK.ready(handle_secure_hash);return{behaviors:behaviors,user_interests:user_interests,add_interest:add_interest};}();VARK.web_question=function(){var behaviors={};behaviors.ask_form=function(){behaviors.ask_form_submit();};behaviors.clear_question_tag=function(){$("#web_question_content").change(function(){$("#web_question_question_tag").val("");});};behaviors.aardvark_response=function(json){behaviors.close_aardvark_response_click(json);behaviors.edit_tag_link();behaviors.cancel_question_form();};behaviors.post_facebook_stay_on_page=function(post_id,exception){if(!!post_id&&post_id!='null')
VARK.update_flash({'flash':{'notices':['Thanks, posted!']}});$.facebox.hideOverlay();};behaviors.ask_form_submit=function(){$('form#new_web_question').varkify(function(json){if(json.open_signup_modal){VARK.signup.open_signup_modal({version:'alternate_signup'});}else{set_aardvark_response(json);}});};behaviors.auto_submit=function(){console.debug('behavior');VARK.ready(function(){$('form#new_web_question').trigger('submit');});};behaviors.cancel_question_form=function(){$("#cancel_question-form").varkify(function(json){if(json.success){if(json.html=="WAIT"){$("#cancel_question-form").trigger("submit");}else{$('#web_question_content').val('').focus();close_aardvark_response(json);}}
return false;},{spinner:$('#aardvark_response .spinner')});};behaviors.edit_tag_link=function(){$('#edit_topic-link').click(function(){behaviors.edit_tag_form();return false;});};behaviors.prompt_tag_form=function(){$('form#prompt_tag_form #web_question_question_tag').trigger('focus');$('form#prompt_tag_form').varkify(function(json){set_aardvark_response(json);});};behaviors.edit_tag_form=function(){$('#edit_topic-link').hide();$("form#edit_tag").show();$('#question_topic, .subject.bold').hide();$('#aardvark_response').find('.ok').hide();$('#aardvark_response').find('.cancel').hide();$('#web_tag_question_tag').select();$('form#edit_tag').varkify(function(json){switch(json.status){case 404:$('#aardvark_response .spinner span').show();setTimeout(function(){$('form#edit_tag').trigger("submit")},1000);break;case 200:$(".people_in_your_network").html(json.html);$(".subject-wrapper .bold").html(json.topic_user_term).show();$(".active .subject").html(json.topic_user_term);$('form#edit_tag').hide();$('#edit_topic-link').show();$('#question_topic').show();$('#aardvark_response').find('.ok').show();$('#aardvark_response').find('.cancel').show();enable_keyboard_shortcut(json);break;}},{spinner:$('#aardvark_response .spinner')});};behaviors.close_aardvark_response_click=function(json){$('#aardvark_response a.ok').click(function(){close_aardvark_response(json);return false;});if($('#aardvark_response a.ok').length>0){enable_keyboard_shortcut(json);};$('#web_question_content').focus(function(){close_aardvark_response(json);$('#web_question_content').css('opacity','1');});};enable_keyboard_shortcut=function(){$(window).keydown(function(event){if(event.keyCode==13||event.keyCode==27){if($('#aardvark_response a.ok').is(':visible')){close_aardvark_response();};};});};set_aardvark_response=function(json){if(typeof json.html=="undefined"){return false;};$('#ask-interests').hide();$('#web_question_content').css('opacity','0.5');$('#new_web_question .chat-bubble-action').slideUp('fast');$('#aardvark_response').hide().html(json.html).slideDown('fast');$('#ask_wrapper-bottom').hide();behaviors.prompt_tag_form();$('#web_question_question_tag').focus();behaviors.aardvark_response(json);};close_aardvark_response=function(json){$('#aardvark_response').slideUp('fast');$('#new_web_question .chat-bubble-action').slideDown('fast');$('#ask_wrapper-bottom').show();$('#ask-interests').slideDown();if(json.success){$("#web_question_content").attr("value","");}else{$('#web_question_content').css('opacity','1');}};var handle_secure_hash=function(){var content=$('meta[name=secure_hash]').attr('content');if(!content){return;}
var matches=content.split(':');if(!matches){return;}
switch(matches[0]){case'cancel':$('#cancel_question-form').trigger('submit');break;case'flag':$('#answer_channel_'+matches[1]+' a.flag-link').trigger('click');break;case'rate':$('#answer_channel_'+matches[1]+' div.train_view:visible a').trigger('click');$('#answer_channel_'+matches[1]+' div.train a.feedback-'+matches[2]).trigger('click');break;case'thank':$('#answer_channel_'+matches[1]+' div.thanks a').trigger('click');break;case'resubmit':$('#channel_list li.channel.active form.web_resubmit').trigger('submit');break;}};VARK.ready(handle_secure_hash);return{behaviors:behaviors}}();VARK.profile=function(){var cancel_url=$("#preview_photo").attr("src");var behaviors={};behaviors.toggle_hide_interest=function(){$("div.interests form input").click(function(){if($("#hide_interests_forms label :checked").length<=2&&$(this).attr("checked")==false){VARK.update_flash({flash:{'errors':['You should have atleast 3 topics']}});return false;}
else{$(this).closest('form').trigger('submit');}});$("div.interests form").varkify(function(json){if(json.success){return false;}
else{$("#"+json.dom_id).attr("checked","checked");}});$('a#done_editing').click(function(){$('#hide_interests_forms').slideUp(function(){var string="";var count_added=0;$("span.checkbox_content").each(function(intIndex){if($(this).prev("input").attr('checked')){if(count_added!=0){string=string+" &bull; ";}
string=string+"<span>"+$(this).html()+"</span>";count_added=count_added+1;if(count_added==3){return false;}}});$('span#topics_list').html(string);$('div#knows_about').show();return false;});return false;});$('a#show_editing').click(function(){$('div#knows_about').hide();$('#hide_interests_forms').slideDown();return false;});};behaviors.settings_form=function(){$("form").varkify(function(json){if(json.redirect){window.location.href=json.location;};});};behaviors.personal_details=function(){$("form#personal_details-form").varkify(function(json){$(this).replaceWith(json.html);});$('form#personal_details-form #user_birthdate').blur(function(){var date=Date.parse($(this).val());if(date){$(this).val(date.toString('MM/dd/yyyy'));}});};behaviors.settings=function(){$("input.click-submit").click(function(){$(this).closest("form").trigger("submit");});};behaviors.auto_complete_location=function(){$('form#personal_details-form #user_location').autocomplete('/locations.jsonh',{matchContains:true,minChars:2,formatItem:function(row){return row.full_name;},dataType:'json',delay:200,matchSubset:false,parse:function(data){var locations=data.locations;var parsed=[];for(var i=0;i<locations.length;i++){var row=locations[i];if(row){parsed[parsed.length]={data:row,value:row.full_name,result:row.full_name};}}
return parsed;}});$('form#personal_details-form #user_location').result(function(event,major,formatted){$('#user_city_location_id').val(major.id);VARK.json_request({url:'/locations/'+major.id+'/neighborhoods',type:'GET',complete:function(json){if(json.success){update_neighborhood_select(json.neighborhoods);}}});});};behaviors.show_photo=function(){$("#show_photo-check").click(function(){$("form#show_photo-form").trigger("submit");});$("form#show_photo-form").varkify();};behaviors.save_photo=function(){$("form#save_photo-form").varkify(function(json){if(json.success){$("div.expandable").removeClass("expanded");}});$("form#save_photo-form a#cancel-form").click(function(){$("div.expandable").removeClass("expanded");$("#preview_photo").attr("src",cancel_url)
return false;});};behaviors.use_facebook_photo=function(){$("#facebook_photo-form").varkify(function(json){mark_preview_facebook();show_preview(json.preview_photo_url);},{spinner:false});$("#facebook_photo-link").click(function(){hide_preview();$("#facebook_photo-form").trigger("submit");return false;});};behaviors.import_photo=function(){$("#import_photo-button").click(function(){hide_preview();$("form#import_photo").vark_now(function(json){unmark_preview_facebook();show_preview(json.preview_photo_url);},{spinner:false});return false;});};behaviors.photo_upload_form=function(error,preview_photo_url){if(error=="true"){parent.VARK.update_flash({"flash":{"errors":["Invalid File Format"]}});}
parent.VARK.profile.show_preview(preview_photo_url);var update_preview=function(){parent.VARK.profile.unmark_preview_facebook();parent.VARK.profile.hide_preview();$('#upload_photo_form').trigger("submit");};$("input#user_uploaded_data").change(update_preview);};behaviors.change_account=function(context){$("form.changing_account_form",context).varkify(function(json){if(json.success){$(json.edit).append(json.html);if(json.remove){$(json.remove).remove();};$(this).find("input:visible").val("");$(this).parents(".expanded").removeClass('expanded').prev().children("#empty_im").remove();}else{$(this).html(json.html);}});VARK.behaviors.form_shadow_text($('form#new_account'));};behaviors.accounts_twitter=function(){$("#twitter_settings").varkify();$("#user_tweet_about_answers").click(function(){$("#twitter_settings").trigger("submit");});};behaviors.tweet=function(){$("form#tweet_form").varkify();};var hide_preview=function(){$('#preview_photo_busy').show();};var show_preview=function(url){if(url!=""){$('#preview_photo').attr("src",url);$("#save_photo-form #user_photo_url").attr("value",url);$("#save_photo-form #user_save_photo").attr("value",true);}
$('#preview_photo_busy').hide();};var mark_preview_facebook=function(){var photo=$('#preview_photo');if(photo.parent().hasClass('avatar-container'))return;$('#save_photo-form')[0].user_image_source.value='facebook';photo.wrap("<div class='avatar-container' />");photo.after("<div class='facebook-avatar-icon' />");};var unmark_preview_facebook=function(){var photo=$('#preview_photo');if(!photo.parent().hasClass('avatar-container'))return;$('#save_photo-form')[0].user_image_source.value='user';var prev_elt=photo.parent().prev();photo.parent().remove();prev_elt.after(photo);};var update_neighborhood_select=function(options){if(options.length<1){$('#user_neighborhood_location_id').html('');$('#user_neighborhood_location_input').hide();}else{var options_html=['<option value="">Select a neighborhood</option>'];for(var i=0;i<options.length;i++){options_html.push(['<option value="',options[i].location.id,'">',options[i].location.name,'</option>'].join(''));}
$('#user_neighborhood_location_id').html(options_html.join(''));$('#user_neighborhood_location_input').show();}};return{behaviors:behaviors,hide_preview:hide_preview,show_preview:show_preview,unmark_preview_facebook:unmark_preview_facebook}}();VARK.widgets=function(){var joined_aardvark_timer=null;var behaviors={};behaviors.joined_aardvark=function(){joined_aardvark_timer=setInterval(unshift_joined_aardvark_list,6000);};var unshift_joined_aardvark_list=function(){var user=$('#joined_aardvark .joined_aardvark-users .joined_aardvark-user:first');if(user.length==0){clearInterval(joined_aardvark_timer);return;}
user.remove();user.prependTo('#joined_aardvark .joined-today_box');user.slideDown();};return{behaviors:behaviors};}();VARK.watch_live=function(){var watch_live=null,multiline=false,list_wrapper=null,list_wrapper_width=0,ul=null,ul_width=0,ul_left=0,paused=true,timer=null,conversations=[],conversation_elements=[],pending_conversations=[],backfill_conversations=[],backfill_pos=0,popup=null,chat_line_template=null,selected_conversation=null,default_profile_image=null,animate=true;var get_random_seconds_between=function(min,max){random=Math.random();random=random*(max-min);random=min+random;random=Math.floor(random);random=random*1000;return random;};var new_conversation=function(new_conversation){var dup=false
$(conversations).each(function(){if(this.question==new_conversation.question){dup=true;return false;}});if(!dup){new_conversation.profile_image=new_conversation.profile_image||default_profile_image;pending_conversations.push(new_conversation);}};var pause=function(){clearTimeout(timer);paused=true;};var unpause=function(){clearTimeout(timer);timer=setTimeout(pop_conversation,get_random_seconds_between(2,4));paused=false;};var maybe_animate=function(elem,css,speed,method,callback){if(animate){elem.animate(css,speed,method,callback);}else{elem.css(css);callback();}};var append_conversation=function(conversation){ul.append(['<li class="interest"><a href="#">',$.escapeHTML(conversation.subject),'</a></li> '].join(''));var new_li=ul.find('li:last');var new_width=new_li.outerWidth(true)+1;ul_width+=new_width;if(multiline&&ul_width+ul_left>list_wrapper_width){old_ul_width=ul_width+ul_left-new_width;new_height=new_li.outerHeight(true);new_li.remove();ul.css({height:new_height,left:0,width:old_ul_width});ul=$('<ul/>').append(new_li);ul_width=list_wrapper_width;ul_left=-ul_width;ul.css({position:'relative',left:ul_left,width:ul_width,height:new_height});ul_width+=new_width;list_wrapper.prepend(ul);var uls=list_wrapper.children('ul');if(uls.length>3){var last_ul=$(uls[uls.length-1]);last_ul.children('li.interest').each(function(){conversations.pop();conversation_elements.pop();});last_ul.remove();}}
maybe_animate(ul,{width:ul_width},'fast','linear',function(){var first_li=ul.find('li:first');var first_width=first_li.outerWidth(true);if(!multiline&&ul_width>(list_wrapper_width*2)+first_width){conversations.pop();conversation_elements.pop();ul_width-=first_width;first_li.remove();ul.css({width:ul_width});}});conversations.unshift(conversation);conversation_elements.unshift(new_li[0]);clearTimeout(timer);timer=setTimeout(pop_conversation,get_random_seconds_between(1,5));};var pop_conversation=function(){var conversation;if(pending_conversations.length==0){if(backfill_conversations.length==0){return;}
if(backfill_pos==backfill_conversations.length-1){backfill_pos=0;}else{backfill_pos+=1;}
conversation=backfill_conversations[backfill_pos];}else{conversation=pending_conversations.shift();}
append_conversation(conversation);};var on_click=function(){pause();var li=$(this);selected_conversation=conversations[$.inArray(this,conversation_elements)];selected_conversation.profile_image=selected_conversation.profile_image||default_profile_image;var pos=li.offset();popup.find('.chat_line').html($.tmpl(chat_line_template,selected_conversation));popup.css({top:pos.top-popup.outerHeight()-4,left:pos.left-popup.outerWidth()+(li.outerWidth()/2)+42});popup.show();VARK.behaviors.close_popup(popup[0],li[0],unpause);return false;};var ask_this=function(){$('#web_question_content').trigger('focus').val(selected_conversation.question).trigger('click');$('#web_question_question_tag').val(selected_conversation.subject);};var preload=function(new_conversations){animate=false;$(new_conversations).each(function(){this.profile_image=this.profile_image||default_profile_image;append_conversation(this);});animate=true;};var init=function(new_chat_line_template,new_conversations,new_backfill_conversations){watch_live=$('#watch_live');multiline=watch_live.hasClass('multiline');ul=watch_live.find('ul:first');list_wrapper=ul.parent();list_wrapper_width=list_wrapper.innerWidth();ul_width=list_wrapper_width;ul_left=-ul_width;ul.css({position:'relative',left:ul_left,width:ul_width});list_wrapper.delegate('click','li',on_click);popup=$('#watch_live-popup').remove().appendTo('body');default_profile_image=$(["<div>",new_chat_line_template,"</div>"].join('')).find('img.avatar').attr('src');chat_line_template=new_chat_line_template.replace(default_profile_image,'#{profile_image}');popup.css({position:'absolute'});if(new_conversations){preload(new_conversations);}
if(new_backfill_conversations){backfill_conversations=new_backfill_conversations;}
unpause();};return{get_random_seconds_between:get_random_seconds_between,new_conversation:new_conversation,ask_this:ask_this,pause:pause,unpause:unpause,init:init};}();VARK.waitlist=function(){var behaviors={};behaviors.waitlist_submit=function(){$("form#new_waitlister").varkify(function(json){if(json.success){if(json.open_signup_modal){VARK.signup.open_signup_modal();}}});};return{behaviors:behaviors};}();VARK.history=function(){var behaviors={};behaviors.update_plural_num_desired_answers=function(){$(".select_num_desired_answers").change(function(){if($("li.active").find(".select_num_desired_answers").val()>1){$("li.active").find("#desired_answers_text").html('answers')}
else{$("li.active").find("#desired_answers_text").html('answer')}});};behaviors.transcript_column=function(){$("textarea[class*=expand]").TextAreaExpander();VARK.web_question.behaviors.cancel_question_form();};behaviors.share_channel=function(){$('form#new_channel_privacy input').click(function(){$(this.form).vark_now(function(json){$('#share-wrapper').replaceWith(json.html);});})};behaviors.channel_li=function(){$('ul#channel_list').delegate('click','li.channel:not(.active)',function(){var channel_id=$(this).attr('data-channel_id');var url='/channels/'+channel_id;var shared_channel=(channel_id==undefined);if(shared_channel){var channel_code=$(this).attr('data-channel_code');url='/t/'+channel_code;}
$('ul#channel_list li.channel').removeClass('active');$(this).addClass('active');$('#transcript-column').html(VARK.spinner('transcript'));setTimeout(function(){$.scrollTo('body',400)},400);VARK.json_request({url:url,complete:function(json){$('#transcript-column').html(json.html);}});return false;});};behaviors.channel_list_pagination=function(){$('#channel_list-pagination a').varkify(function(json){if(json.success){$('#index_content').html(json.html);};},{spinner:$('#channel_list-pagination-spinner')});};behaviors.resubmit_conversation=function(){$('form.web_resubmit').varkify(function(json){$(this).slideUp('fast');})};behaviors.channel_passthrough=function(){$('form.web_passthrough').varkify(function(json){if(json.success){$(this).find('textarea').val('');$(this).closest('.follow_up').before(json.html);};});};behaviors.channel_thanks=function(){$('form.web_thanks').submit(function(){$(this).vark_now(function(json){if(json.success){$(this).closest('.follow_up').before(json.html);$(this).parents('.thanks').slideUp();};},{spinner:$(this).parents('.content').find('.spinner')});return false;});};behaviors.channel_flag=function(){var links=$('a.flag-link');links.map(function(){link=$(this);var form=link.next('form.web_flag');form.varkify(function(json){if(json.success){link.replaceWith(link.html());}},{spinner:$(this).parents('.content').find('.spinner')});link.click(function(){form.trigger('submit');return false;});});};behaviors.channel_train=function(){$('.train_view a').click(function(){var train_view=$(this).parent();train_view.prev('.train').show();train_view.hide();return false;});$('form.web_train').submit(function(){$(this).vark_now(function(json){if(json.success){var train=$(this).parent();train.next('.train_view').children('.train_choice').html(json.choice);train.next('.train_view').show();train.hide();}});return false;});};return{behaviors:behaviors};}();VARK.invites=function(){var behaviors={};behaviors.external_email_user_sync=function(service){$('#new_external_email_user_sync').varkify(function(json){if(json.status==201){if(json.location){$(this).find('.spinner span').show();window.location.href=json.location;}else{$('#invite-panel').html(json.html);};}else{$(this).replaceWith(json.html);behaviors.external_email_user_sync(service);}});};behaviors.email_panel=function(){$('form#create_many_email').varkify(function(json){if(json.success){$('#invite-panel').html(json.html);behaviors.email_panel();$(this).find('input.topics:first').trigger('blur');}else{$('#invite-panel').html(json.html);behaviors.email_panel();}});};behaviors.view_panel=function(){$('#view_form li.invite form.resend_invite-form').each(function(){var form=$(this);var link=form.prev();$(this).varkify(function(json){if(json.success){form.remove();link.remove();}});});};behaviors.external_users=function(){$('#external_user_form li.external_user.invitable').each(function(){var li=$(this);var link=li.children('a:first');var popup=link.next();link.tooltip({tip:popup,position:'bottom left',offset:[15,popup.outerWidth()-10],delay:250,events:{def:"click,click"},api:true,relative:true,onShow:function(event){VARK.behaviors.close_tooltip(this);return false;}});link.varkify(function(json){popup.find('.help-box')[0].innerHTML=json.html;});});};behaviors.external_user_form=function(class_name){var spinner_span=$('#application-spinner').children('span');var lis=$('.'+class_name);lis.each(function(index){var li=$(this);var link=li.children('a:first');var popup=link.next();var form=popup.find('form:first');VARK.behaviors.form_shadow_text(form);var complete=function(json){spinner_span.hide();if(json.status==201){popup.remove();link.replaceWith(link.html());li.removeClass('invitable');}else{form.replaceWith(json.html);form=popup.find('form:first');VARK.behaviors.form_shadow_text(form);form.varkify(complete);}};form.varkify(complete);});};behaviors.close_external_user_form=function(class_name){var lis=$('.'+class_name);lis.each(function(index){var li=$(this);var link=li.children('a:first');var popup=link.next();popup.remove();link.replaceWith(link.html());li.removeClass('invitable');});};behaviors.ignored_external_user_candidate_form=function(){$('form.ignored_external_user_candidate').submit(function(){$(this).vark_now();$(this).closest('li').children().fadeOut();return false;})};behaviors.splittable_email_invite_form=function(){$('#new_splittable_email_invite').varkify(function(json){$(this).replaceWith(json.html);});$('#new_splittable_email_invite textarea').focus(function(){$(this).closest('form').find('.buttons').slideDown('fast');});};behaviors.facebook_panel=function(){behaviors.external_users(true);};behaviors.external_email_panel=function(){behaviors.external_users();};behaviors.gmail_panel=function(){behaviors.external_email_panel();};behaviors.yahoo_panel=function(){behaviors.external_email_panel();};behaviors.msnlive_panel=function(){behaviors.external_email_panel();};behaviors.aol_panel=function(){behaviors.external_email_panel();};return{behaviors:behaviors};}();VARK.referral=function(){var behaviors={};behaviors.answer_submit=function(){$("form#refferal_question").varkify(function(json){if(json.success){if(json.open_signup_modal){VARK.signup.open_signup_modal({version:'referral_signup'});}else{this.reset();$(this).closest('li').slideUp('fast');$('ul.answer_list').prepend(json.html).slideDown('fast');}};});};return{behaviors:behaviors};}();VARK.external_email_users=function(){var behaviors={};behaviors.confirm=function(){$('form#confirm_form #select_all').click(function(){var master_check=this;$('form#confirm_form input[type=checkbox]').each(function(){this.checked=master_check.checked;});});$('form#confirm_form').submit(function(){var count=$('form#confirm_form .people input[type=checkbox]:checked').length;if(count>=20){if(confirm('Are you sure you want to invite these '+count+' people?')){submit_form(this);};}else{submit_form(this);};return false;});$('form#confirm_form .skip').click(function(){$.facebox.close();if(VARK.signup.signup_flow){window.location.href='/ask';return false;}})};var submit_form=function(form){$(form).vark_now(function(json){if(json.success){if(VARK.signup.signup_flow){window.location.href='/ask';}else{window.location.href=json.location;}}else{$('#external_email_confirm').replaceWith(json.html);}});}
return{behaviors:behaviors};}();VARK.connections=function(){var behaviors={};behaviors.pagination_spinner=function(){$('.pagination a').click(function(){show_pagination_spinner();});$('#letter').change(function(){show_pagination_spinner();});}
var show_pagination_spinner=function(){$('div.connections-pagination-spinner span').show();};return{behaviors:behaviors};}();VARK.groups=function(){var behaviors={};behaviors.edit_or_cancel_groups=function(){$("a.edit_groups").click(function(){$(this).hide();$(".join_or_leave_group").show();$("ul.old_groups_list").show();$("a.cancel-edit-groups").show();return false;});$("a.cancel-edit-groups").click(function(){$(this).hide();$(".join_or_leave_group").hide();$("ul.old_groups_list").hide();$("a.edit_groups").show();return false;});};behaviors.join_or_leave_group=function(){$("a.join_group, a.leave_group").click(function(){$(this).hide().next().vark_now(function(json){$("div#groups_col").html(json.html);});return false;});};return{behaviors:behaviors};}();VARK.openid=function(){var job_key=null;var behaviors={};var please_wait_html=null;behaviors.init=function(){setup_openid($('a.btn-google-login'),login_or_signup_callback);setup_openid($('a.btn-google-sync'),sync_callback);$('a.btn-google-apps-login').varkify(function(json){$.facebox(json.html);setup_openid($('form#what_g_apps_domain'),login_or_signup_callback);});$('a.btn-google-apps-sync').varkify(function(json){$.facebox(json.html);setup_openid($('form#what_g_apps_domain'),sync_callback);});};var login_or_signup_callback=function(status,message,user_id){if(status=='ok'){if(user_id){window.location.href='/session/success';}else{submit_contacts_sync();VARK.signup.open_signup_modal({version:'narrow'});};}else{VARK.update_flash({flash:{errors:[message]}});}};var sync_callback=function(status,message,user_id){if(status=='ok'){submit_contacts_sync({'redirect_to':'/invites/new_gmail'});}else{VARK.update_flash({flash:{errors:[message]}});};};var setup_openid=function(selector,after_complete){$(selector).each(function(){if(this.nodeName=='FORM'){initiate_openid_on_submit($(this),after_complete);}else{initiate_openid_on_click($(this),after_complete);}})};var initiate_openid_now=function(after_complete,domain_name){var callback=function(event,status,message,user_id){after_complete(status,message,user_id);$('body').unbind('openid_complete');};begin(callback,domain_name);};var initiate_openid_on_click=function(selector,after_complete){$(selector).click(function(){initiate_openid_now(after_complete);return false;})};var initiate_openid_on_submit=function(selector,after_complete){$(selector).submit(function(){var domain_name=$('input:text',this).val();initiate_openid_now(after_complete,domain_name);return false;})};var submit_contacts_sync=function(options){if(typeof(options)=='undefined'){options={};}
VARK.vark_ajax({url:'/portable_contacts_syncs/submit',complete:function(json){if(json.success){VARK.openid.job_key=json.job_key;VARK.openid.please_wait_html=json.html;if(options['redirect_to']){$.facebox(VARK.openid.please_wait_html);$('#facebox-spinner span').show();var on_timeout=function(){VARK.update_flash({flash:{errors:['There was a problem syncing your contacts. Please try again.']}});};VARK.poll_until_redirect('/portable_contacts_syncs/status?job_key='+json.job_key,options['redirect_to'],on_timeout);}}else{VARK.update_flash({flash:{errors:['There was a problem syncing your contacts.']}});};}});};var show_contacts_on_aardvark=function(external_user_id){VARK.vark_ajax({url:'/external_email_users/'+external_user_id+'/confirm',type:'GET',data:{service:'gmail',version:'lightbox'},complete:function(json){if(json.success){$.facebox(json.html);}}});};var begin=function(callback,domain_name){$('body').bind('openid_complete',callback)
var url='/portable_contacts_syncs/authenticate'
if(domain_name){url=url+'?domain_name='+domain_name}
VARK.open_popup(url,{centerBrowser:1,height:500,width:450,windowName:'openid_popup'});};var complete=function(status,message,user_id,popup_window){console.debug('OpenID complete',status,message,user_id);popup_window.close();$('body').trigger('openid_complete',[status,message,user_id]);};return{behaviors:behaviors,complete:complete,job_key:job_key,please_wait_html:please_wait_html,show_contacts_on_aardvark:show_contacts_on_aardvark}}();(function(){if($('#flash-ul li:first').length>=1){VARK.show_flash(30);}
var matches=window.location.hash.match(/^#?badge-(\d+)$/)
if(matches){VARK.ready(function(){$('div.badge.user_'+matches[1]+':first div.name').trigger('click');});}
VARK.behaviors.enable_buttons();VARK.behaviors.pound_signin_or_signup();})();