/*
 * jQuery BBQ: Back Button & Query Library - v1.2.1 - 2/17/2010
 * http://benalman.com/projects/jquery-bbq-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,p){var i,m=Array.prototype.slice,r=decodeURIComponent,a=$.param,c,l,v,b=$.bbq=$.bbq||{},q,u,j,e=$.event.special,d="hashchange",A="querystring",D="fragment",y="elemUrlAttr",g="location",k="href",t="src",x=/^.*\?|#.*$/g,w=/^.*\#/,h,C={};function E(F){return typeof F==="string"}function B(G){var F=m.call(arguments,1);return function(){return G.apply(this,F.concat(m.call(arguments)))}}function n(F){return F.replace(/^[^#]*#?(.*)$/,"$1")}function o(F){return F.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/,"$1")}function f(H,M,F,I,G){var O,L,K,N,J;if(I!==i){K=F.match(H?/^([^#]*)\#?(.*)$/:/^([^#?]*)\??([^#]*)(#?.*)/);J=K[3]||"";if(G===2&&E(I)){L=I.replace(H?w:x,"")}else{N=l(K[2]);I=E(I)?l[H?D:A](I):I;L=G===2?I:G===1?$.extend({},I,N):$.extend({},N,I);L=a(L);if(H){L=L.replace(h,r)}}O=K[1]+(H?"#":L||!K[1]?"?":"")+L+J}else{O=M(F!==i?F:p[g][k])}return O}a[A]=B(f,0,o);a[D]=c=B(f,1,n);c.noEscape=function(G){G=G||"";var F=$.map(G.split(""),encodeURIComponent);h=new RegExp(F.join("|"),"g")};c.noEscape(",/");$.deparam=l=function(I,F){var H={},G={"true":!0,"false":!1,"null":null};$.each(I.replace(/\+/g," ").split("&"),function(L,Q){var K=Q.split("="),P=r(K[0]),J,O=H,M=0,R=P.split("]["),N=R.length-1;if(/\[/.test(R[0])&&/\]$/.test(R[N])){R[N]=R[N].replace(/\]$/,"");R=R.shift().split("[").concat(R);N=R.length-1}else{N=0}if(K.length===2){J=r(K[1]);if(F){J=J&&!isNaN(J)?+J:J==="undefined"?i:G[J]!==i?G[J]:J}if(N){for(;M<=N;M++){P=R[M]===""?O.length:R[M];O=O[P]=M<N?O[P]||(R[M+1]&&isNaN(R[M+1])?{}:[]):J}}else{if($.isArray(H[P])){H[P].push(J)}else{if(H[P]!==i){H[P]=[H[P],J]}else{H[P]=J}}}}else{if(P){H[P]=F?i:""}}});return H};function z(H,F,G){if(F===i||typeof F==="boolean"){G=F;F=a[H?D:A]()}else{F=E(F)?F.replace(H?w:x,""):F}return l(F,G)}l[A]=B(z,0);l[D]=v=B(z,1);$[y]||($[y]=function(F){return $.extend(C,F)})({a:k,base:k,iframe:t,img:t,input:t,form:"action",link:k,script:t});j=$[y];function s(I,G,H,F){if(!E(H)&&typeof H!=="object"){F=H;H=G;G=i}return this.each(function(){var L=$(this),J=G||j()[(this.nodeName||"").toLowerCase()]||"",K=J&&L.attr(J)||"";L.attr(J,a[I](K,H,F))})}$.fn[A]=B(s,A);$.fn[D]=B(s,D);b.pushState=q=function(I,F){if(E(I)&&/^#/.test(I)&&F===i){F=2}var H=I!==i,G=c(p[g][k],H?I:{},H?F:2);p[g][k]=G+(/#/.test(G)?"":"#")};b.getState=u=function(F,G){return F===i||typeof F==="boolean"?v(F):v(G)[F]};b.removeState=function(F){var G={};if(F!==i){G=u();$.each($.isArray(F)?F:arguments,function(I,H){delete G[H]})}q(G,2)};e[d]=$.extend(e[d],{add:function(F){var H;function G(J){var I=J[D]=c();J.getState=function(K,L){return K===i||typeof K==="boolean"?l(I,K):l(I,L)[K]};H.apply(this,arguments)}if($.isFunction(F)){H=F;return G}else{H=F.handler;F.handler=G}}})})(jQuery,this);
/*
 * jQuery hashchange event - v1.2 - 2/11/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,i,b){var j,k=$.event.special,c="location",d="hashchange",l="href",f=$.browser,g=document.documentMode,h=f.msie&&(g===b||g<8),e="on"+d in i&&!h;function a(m){m=m||i[c][l];return m.replace(/^[^#]*#?(.*)$/,"$1")}$[d+"Delay"]=100;k[d]=$.extend(k[d],{setup:function(){if(e){return false}$(j.start)},teardown:function(){if(e){return false}$(j.stop)}});j=(function(){var m={},r,n,o,q;function p(){o=q=function(s){return s};if(h){n=$('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;q=function(){return a(n.document[c][l])};o=function(u,s){if(u!==s){var t=n.document;t.open().close();t[c].hash="#"+u}};o(a())}}m.start=function(){if(r){return}var t=a();o||p();(function s(){var v=a(),u=q(t);if(v!==t){o(t=v,u);$(i).trigger(d)}else{if(u!==t){i[c][l]=i[c][l].replace(/#.*/,"")+"#"+u}}r=setTimeout(s,$[d+"Delay"])})()};m.stop=function(){if(!n){r&&clearTimeout(r);r=0}};return m})()})(jQuery,this);/*	ColorBox v1.3.6 - a full featured, light-weight, customizable lightbox based on jQuery 1.3 */
(function(c){function r(b,d){d=d==="x"?m.width():m.height();return typeof b==="string"?Math.round(b.match(/%/)?d/100*parseInt(b,10):parseInt(b,10)):b}function M(b){b=c.isFunction(b)?b.call(i):b;return a.photo||b.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i)}function Y(){for(var b in a)if(c.isFunction(a[b])&&b.substring(0,2)!=="on")a[b]=a[b].call(i);a.rel=a.rel||i.rel;a.href=a.href||i.href;a.title=a.title||i.title}function Z(b){i=b;a=c.extend({},c(i).data(q));Y();if(a.rel&&a.rel!=="nofollow"){g= c(".cboxElement").filter(function(){return(c(this).data(q).rel||this.rel)===a.rel});j=g.index(i);if(j<0){g=g.add(i);j=g.length-1}}else{g=c(i);j=0}if(!B){C=B=n;N=i;N.blur();c(document).bind("keydown.cbox_close",function(d){if(d.keyCode===27){d.preventDefault();e.close()}}).bind("keydown.cbox_arrows",function(d){if(g.length>1)if(d.keyCode===37){d.preventDefault();D.click()}else if(d.keyCode===39){d.preventDefault();E.click()}});a.overlayClose&&s.css({cursor:"pointer"}).one("click",e.close);c.event.trigger(aa); a.onOpen&&a.onOpen.call(i);s.css({opacity:a.opacity}).show();a.w=r(a.initialWidth,"x");a.h=r(a.initialHeight,"y");e.position(0);O&&m.bind("resize.cboxie6 scroll.cboxie6",function(){s.css({width:m.width(),height:m.height(),top:m.scrollTop(),left:m.scrollLeft()})}).trigger("scroll.cboxie6")}P.add(D).add(E).add(t).add(Q).hide();R.html(a.close).show();e.slideshow();e.load()}var q="colorbox",F="hover",n=true,e,x=c.browser.msie&&!c.support.opacity,O=x&&c.browser.version<7,aa="cbox_open",H="cbox_load",S= "cbox_complete",T="resize.cbox_resize",s,k,u,p,U,V,W,X,g,m,l,I,J,K,Q,P,t,E,D,R,y,z,v,w,i,N,j,a,B,C,$={transition:"elastic",speed:350,width:false,height:false,innerWidth:false,innerHeight:false,initialWidth:"400",initialHeight:"400",maxWidth:false,maxHeight:false,scalePhotos:n,scrolling:n,inline:false,html:false,iframe:false,photo:false,href:false,title:false,rel:false,opacity:0.9,preloading:n,current:"image {current} of {total}",previous:"previous",next:"next",close:"close",open:false,overlayClose:n, slideshow:false,slideshowAuto:n,slideshowSpeed:2500,slideshowStart:"start slideshow",slideshowStop:"stop slideshow",onOpen:false,onLoad:false,onComplete:false,onCleanup:false,onClosed:false};e=c.fn.colorbox=function(b,d){var h=this;if(!h.length)if(h.selector===""){h=c("<a/>");b.open=n}else return this;h.each(function(){var f=c.extend({},c(this).data(q)?c(this).data(q):$,b);c(this).data(q,f).addClass("cboxElement");if(d)c(this).data(q).onComplete=d});b&&b.open&&Z(h);return this};e.init=function(){function b(d){return c('<div id="cbox'+ d+'"/>')}m=c(window);k=c('<div id="colorbox"/>');s=b("Overlay").hide();u=b("Wrapper");p=b("Content").append(l=b("LoadedContent").css({width:0,height:0}),J=b("LoadingOverlay"),K=b("LoadingGraphic"),Q=b("Title"),P=b("Current"),t=b("Slideshow"),E=b("Next"),D=b("Previous"),R=b("Close"));u.append(c("<div/>").append(b("TopLeft"),U=b("TopCenter"),b("TopRight")),c("<div/>").append(V=b("MiddleLeft"),p,W=b("MiddleRight")),c("<div/>").append(b("BottomLeft"),X=b("BottomCenter"),b("BottomRight"))).children().children().css({"float":"left"}); I=c("<div style='position:absolute; top:0; left:0; width:9999px; height:0;'/>");c("body").prepend(s,k.append(u,I));if(x){k.addClass("cboxIE");O&&s.css("position","absolute")}p.children().bind("mouseover mouseout",function(){c(this).toggleClass(F)}).addClass(F);y=U.height()+X.height()+p.outerHeight(n)-p.height();z=V.width()+W.width()+p.outerWidth(n)-p.width();v=l.outerHeight(n);w=l.outerWidth(n);k.css({"padding-bottom":y,"padding-right":z}).hide();E.click(e.next);D.click(e.prev);R.click(e.close);p.children().removeClass(F); c(".cboxElement").live("click",function(d){if(d.button!==0&&typeof d.button!=="undefined")return n;else{Z(this);return false}})};e.position=function(b,d){function h(A){U[0].style.width=X[0].style.width=p[0].style.width=A.style.width;K[0].style.height=J[0].style.height=p[0].style.height=V[0].style.height=W[0].style.height=A.style.height}var f=m.height();f=Math.max(f-a.h-v-y,0)/2+m.scrollTop();var o=Math.max(document.documentElement.clientWidth-a.w-w-z,0)/2+m.scrollLeft();b=k.width()===a.w+w&&k.height()=== a.h+v?0:b;u[0].style.width=u[0].style.height="9999px";k.dequeue().animate({width:a.w+w,height:a.h+v,top:f,left:o},{duration:b,complete:function(){h(this);C=false;u[0].style.width=a.w+w+z+"px";u[0].style.height=a.h+v+y+"px";d&&d()},step:function(){h(this)}})};e.resize=function(b){function d(){a.w=a.w||l.width();a.w=a.mw&&a.mw<a.w?a.mw:a.w;return a.w}function h(){a.h=a.h||l.height();a.h=a.mh&&a.mh<a.h?a.mh:a.h;return a.h}function f(G){e.position(G,function(){if(B){if(x){A&&l.fadeIn(100);k[0].style.removeAttribute("filter")}if(a.iframe)l.append("<iframe id='cboxIframe'"+ (a.scrolling?" ":"scrolling='no'")+" name='iframe_"+(new Date).getTime()+"' frameborder=0 src='"+a.href+"' "+(x?"allowtransparency='true'":"")+" />");l.show();Q.show().html(a.title);if(g.length>1){P.html(a.current.replace(/\{current\}/,j+1).replace(/\{total\}/,g.length)).show();E.html(a.next).show();D.html(a.previous).show();a.slideshow&&t.show()}J.hide();K.hide();c.event.trigger(S);a.onComplete&&a.onComplete.call(i);a.transition==="fade"&&k.fadeTo(L,1,function(){x&&k[0].style.removeAttribute("filter")}); m.bind(T,function(){e.position(0)})}})}if(B){var o,A,L=a.transition==="none"?0:a.speed;m.unbind(T);if(b){l.remove();l=c('<div id="cboxLoadedContent"/>').html(b);l.hide().appendTo(I).css({width:d(),overflow:a.scrolling?"auto":"hidden"}).css({height:h()}).prependTo(p);c("#cboxPhoto").css({cssFloat:"none"});O&&c("select:not(#colorbox select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one("cbox_cleanup",function(){this.style.visibility="inherit"});a.transition=== "fade"&&k.fadeTo(L,0,function(){f(0)})||f(L);if(a.preloading&&g.length>1){b=j>0?g[j-1]:g[g.length-1];o=j<g.length-1?g[j+1]:g[0];o=c(o).data(q).href||o.href;b=c(b).data(q).href||b.href;M(o)&&c("<img />").attr("src",o);M(b)&&c("<img />").attr("src",b)}}else setTimeout(function(){var G=l.wrapInner("<div style='overflow:auto'></div>").children();a.h=G.height();l.css({height:a.h});G.replaceWith(G.children());e.position(L)},1)}};e.load=function(){var b,d,h,f=e.resize;C=n;i=g[j];a=c.extend({},c(i).data(q)); Y();c.event.trigger(H);a.onLoad&&a.onLoad.call(i);a.h=a.height?r(a.height,"y")-v-y:a.innerHeight?r(a.innerHeight,"y"):false;a.w=a.width?r(a.width,"x")-w-z:a.innerWidth?r(a.innerWidth,"x"):false;a.mw=a.w;a.mh=a.h;if(a.maxWidth){a.mw=r(a.maxWidth,"x")-w-z;a.mw=a.w&&a.w<a.mw?a.w:a.mw}if(a.maxHeight){a.mh=r(a.maxHeight,"y")-v-y;a.mh=a.h&&a.h<a.mh?a.h:a.mh}b=a.href;J.show();K.show();if(a.inline){c('<div id="cboxInlineTemp" />').hide().insertBefore(c(b)[0]).bind(H+" cbox_cleanup",function(){c(this).replaceWith(l.children())}); f(c(b))}else if(a.iframe)f(" ");else if(a.html)f(a.html);else if(M(b)){d=new Image;d.onload=function(){var o;d.onload=null;d.id="cboxPhoto";c(d).css({margin:"auto",border:"none",display:"block",cssFloat:"left"});if(a.scalePhotos){h=function(){d.height-=d.height*o;d.width-=d.width*o};if(a.mw&&d.width>a.mw){o=(d.width-a.mw)/d.width;h()}if(a.mh&&d.height>a.mh){o=(d.height-a.mh)/d.height;h()}}if(a.h)d.style.marginTop=Math.max(a.h-d.height,0)/2+"px";f(d);g.length>1&&c(d).css({cursor:"pointer"}).click(e.next); if(x)d.style.msInterpolationMode="bicubic"};d.src=b}else c("<div />").appendTo(I).load(b,function(o,A){A==="success"?f(this):f(c("<p>Request unsuccessful.</p>"))})};e.next=function(){if(!C){j=j<g.length-1?j+1:0;e.load()}};e.prev=function(){if(!C){j=j>0?j-1:g.length-1;e.load()}};e.slideshow=function(){function b(){t.text(a.slideshowStop).bind(S,function(){h=setTimeout(e.next,a.slideshowSpeed)}).bind(H,function(){clearTimeout(h)}).one("click",function(){d();c(this).removeClass(F)});k.removeClass(f+ "off").addClass(f+"on")}var d,h,f="cboxSlideshow_";t.bind("cbox_closed",function(){t.unbind();clearTimeout(h);k.removeClass(f+"off "+f+"on")});d=function(){clearTimeout(h);t.text(a.slideshowStart).unbind(S+" "+H).one("click",function(){b();h=setTimeout(e.next,a.slideshowSpeed);c(this).removeClass(F)});k.removeClass(f+"on").addClass(f+"off")};if(a.slideshow&&g.length>1)a.slideshowAuto?b():d()};e.close=function(){c.event.trigger("cbox_cleanup");a.onCleanup&&a.onCleanup.call(i);B=false;c(document).unbind("keydown.cbox_close keydown.cbox_arrows"); m.unbind(T+" resize.cboxie6 scroll.cboxie6");s.css({cursor:"auto"}).fadeOut("fast");k.stop(n,false).fadeOut("fast",function(){c("#colorbox iframe").attr("src","about:blank");l.remove();k.css({opacity:1});try{N.focus()}catch(b){}c.event.trigger("cbox_closed");a.onClosed&&a.onClosed.call(i)})};e.element=function(){return c(i)};e.settings=$;c(e.init)})(jQuery);
(function($){var pu_log=function(msg){try{console.log(msg);}catch(err){}}
$.PeriodicalUpdater=function(url,options,callback){var settings=jQuery.extend(true,{url:url,cache:false,method:'GET',data:'',minTimeout:1000,maxTimeout:8000,multiplier:2,maxCalls:0,autoStop:0},options);var timerInterval=settings.minTimeout;var maxCalls=settings.maxCalls;var autoStop=settings.autoStop;var calls=0;var noChange=0;var boostPeriod=function(){if(settings.multiplier>1){timerInterval=timerInterval*settings.multiplier;if(timerInterval>settings.maxTimeout){timerInterval=settings.maxTimeout;}}};var ajaxSettings=jQuery.extend(true,{},settings);if(settings.type&&!ajaxSettings.dataType)ajaxSettings.dataType=settings.type;if(settings.sendData)ajaxSettings.data=settings.sendData;ajaxSettings.type=settings.method;ajaxSettings.ifModified=true;function getdata(){var toSend=jQuery.extend(true,{},ajaxSettings);if(typeof(options.data)=='function'){toSend.data=options.data();if(toSend.data){if(typeof(toSend.data)=="number"){toSend.data=toSend.data.toString();}}}
if(maxCalls==0){$.ajax(toSend);}else if(maxCalls>0&&calls<maxCalls){$.ajax(toSend);calls++;}}
var remoteData=null;var prevData=null;ajaxSettings.success=function(data){pu_log("Successful run! (In 'success')");remoteData=data;timerInterval=settings.minTimeout;};ajaxSettings.complete=function(xhr,success){pu_log("Status of call: "+success+" (In 'complete')");if(maxCalls==-1)return;if(success=="success"||success=="notmodified"){var rawData=$.trim(xhr.responseText);if(rawData=='STOP_AJAX_CALLS'){maxCalls=-1;return;}
if(prevData==rawData){if(autoStop>0){noChange++;if(noChange==autoStop){maxCalls=-1;return;}}
boostPeriod();}else{noChange=0;timerInterval=settings.minTimeout;prevData=rawData;if(remoteData==null)remoteData=rawData;if(ajaxSettings.dataType=='json'){remoteData=JSON.parse(remoteData);}
if(settings.success){settings.success(remoteData);}
if(callback)callback(remoteData);}}
remoteData=null;setTimeout(getdata,timerInterval);}
ajaxSettings.error=function(xhr,textStatus){pu_log("Error message: "+textStatus+" (In 'error')");if(textStatus=="notmodified"){boostPeriod();}else{prevData=null;timerInterval=settings.minTimeout;}
if(settings.error){settings.error(xhr,textStatus);}};$(function(){getdata();});var handle={stop:function(){maxCalls=-1;return;}};return handle;};})(jQuery);/*global $ */
/*jslint browser: true */

var BITR = {};
BITR.namespace = function () {
    var a = arguments, o = null, i, j, d;
    for (i = 0 ; i < a.length; i = i + 1) {
        d = a[i].split(".");
        o = this;
        for (j = 0; j < d.length; j = j + 1) {
            o[d[j]] = o[d[j]] || {};
            o = o[d[j]];
        }
    }
    return o;
};

$.fn.processTweet = function () {  
    var url = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,
        at_link = /@([\w_]+)/gi;

    this.each(function () {  
        var el = $(this);
        el.html(  
            el.html().replace(url, '<a target="_blank" href="$1">$1</a>')
                .replace(at_link, '<a target="_blank" href="http://twitter.com/$1">@$1</a>')
        );  
    });  
    return $(this);  
}; 

$.fn.urlInputInit = function () {
    $('input.url', this).each(function () {
        if ($(this).val() === '') {
            $(this).val('http://');
        }
    });
    return $(this);
};

$.fn.urlInputFinalize = function () {
    $('input.url', this).each(function () {
        if ($(this).val() === 'http://') {
            $(this).val('');
        }
    });
    return $(this);
};

function set_placeholders() {
    /* http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html */
    $('[placeholder]').focus(function () {
        var input = $(this);
        if (input.val() === input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
        }
    }).blur(function () {
        var input = $(this);
        if (input.val() === '') {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
        }
    }).blur();
    $('[placeholder]').parents('form').submit(function () {
        $(this).find('[placeholder]').each(function () {
            var input = $(this);
            if (input.val() === input.attr('placeholder')) {
                input.val('');
            }
        });
    });
}

$(document).ready(set_placeholders);

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (str) {
        return !this.indexOf(str);
    };
}

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, "");
    };
}


BITR.namespace('forms');


BITR.forms.setupCountryRegion = function ($country, $region, initial) {

    function populate($select, options) {
        $.each(options, function (i, val) {
            $select.append($('<option value="' + val + '">' + val + '</option>'));
        });
    }

    function setup_region(v) {
        var options;

        if (v === 'US') {
            options = BITR.data.US_STATES;
        } else if (v === 'GB') {
            options = BITR.data.UK_COUNTRIES;
        } else if (v === 'CA') {
            options = BITR.data.CANADIAN_PROVINCES;
        } else if (v === 'AU') {
            options = BITR.data.AUSTRALIAN_STATES;
        }
        if (options) {
            $('option:not(:first)', $region).remove();
            populate($region, options);
            $region.show();
        } else {
            $region.val('');
            $region.hide();
        }
    }

    $country.change(function () {
        setup_region($(this).val());
    });

    setup_region($country.val());
    $region.val(initial);

};

BITR.forms.setupCountryCity = function ($country, $city, url) {

    function get_source_url(v) {
        if (v) {
            return url+"?country="+v;
        }
        return url
    }

    function setup_city(v) {
        var source_url = get_source_url(v);
        $city.autocomplete('option', 'source', source_url);
    }

    $country.change(function () {
        setup_city($(this).val());
    });
    
    setup_city($country.val());
};

$(document).ready(function () {
    $('.message a.close').live('click', function () {
        $(this).parent('div.message').hide();
        return false;
    });
});

BITR.namespace("data");

BITR.data.US_STATES = [
    'Alabama',
    'Alaska',
    'Arizona',
    'Arkansas',
    'California',
    'Colorado',
    'Connecticut',
    'Delaware',
    'District of Columbia',
    'Florida',
    'Georgia',
    'Hawaii',
    'Idaho',
    'Illinois',
    'Indiana',
    'Iowa',
    'Kansas',
    'Kentucky',
    'Louisiana',
    'Maine',
    'Maryland',
    'Massachusetts',
    'Michigan',
    'Minnesota',
    'Mississippi',
    'Missouri',
    'Montana',
    'Nebraska',
    'Nevada',
    'New Hampshire',
    'New Jersey',
    'New Mexico',
    'New York',
    'North Carolina',
    'North Dakota',
    'Ohio',
    'Oklahoma',
    'Oregon',
    'Pennsylvania',
    'Rhode Island',
    'South Carolina',
    'South Dakota',
    'Tennessee',
    'Texas',
    'Utah',
    'Vermont',
    'Virginia',
    'Washington',
    'West Virginia',
    'Wisconsin',
    'Wyoming'
];

BITR.data.CANADIAN_PROVINCES = [
    'Alberta',
    'British Columbia',
    'Manitoba',
    'Newfoundland',
    'New Brunswick',
    'Northwest Territories',
    'Nova Scotia',
    'Nunavut',
    'Ontario',
    'Quebec',
    'Saskatchewan',
    'Yukon'
];

BITR.data.UK_COUNTRIES = [
    'England',
    'Northern Ireland',
    'Scotland',
    'Wales'
];

BITR.data.AUSTRALIAN_STATES = [
    'ACT',
    'New South Wales',
    'Northern Territory',
    'Queensland',
    'South Australia',
    'Victoria',
    'Tasmania',
    'Western Australia'
];

BITR.namespace('login');

BITR.login.make_loginbox_  = function(selector) {

    $(selector).colorbox({
        inline: true,
        href: '#login_box',
        height: 390
    });

};

BITR.login.make_loginbox = function(selector, next) {
    BITR.login.make_loginbox_(selector);

    $(selector).click(function() {
        if (next !== undefined) {
            $('#login_box_next').val(next);
        } else {
            $('#login_box_next').val('');
        }
    });
};


BITR.login.make_loginbox_action = function(selector, next, action) {
    BITR.login.make_loginbox(selector, next);

    $(selector).click(function() {
        $('#login_box_action').val(action);
    });
};

BITR.namespace("event.edit");

BITR.event.edit.make_form_submit_handler = function(domain, check_url, event_id, form_selector, hashtags_selector, hashtag_dialog_selector) {
    if (!hashtags_selector) {
      hashtags_selector = "#id_hashtags"
    }
    if (!form_selector) {
      form_selector = "#event_form"
    }
    if (!hashtag_dialog_selector) {
      hashtag_dialog_selector = "#hashtag_dialog"
    }
    return (function() {
        data = {
            hashtags: $(hashtags_selector).val()
        };
        if (event_id) {
            data.event_id = event_id;
        }
        $.getJSON(check_url , data, function(data, textStatus) {
            if (data == 'ok') {
                $(form_selector).urlInputFinalize().submit();
            } else {
                var msg ="";
                $.each(data, function(ind, item) {
                    var url = domain + item[1];
                    msg += "The hashtag #" + item[0] +
                    ' belongs to another event (<a target="_blank" href="' +
                        url + '">' + url + '</a>).<br/>';
                });

                if (data.length == 1) {
                    msg += "<br/>Would you still like to use it?";
                } else {
                    msg += "<br/>Would you still like to use them?";
                }
                $(hashtag_dialog_selector + ' p').replaceWith('<p>'+msg+'</p>');
                $(hashtag_dialog_selector).dialog('open');
            }

        });
    });

};


// Have dynamic "add another" and "delete" buttons with formsets.
BITR.event.edit.dynamic_content_formset = function(t) {
    var prefix = t['prefix']
    var shadow = t['shadow']
    var fieldset=$('fieldset.'+prefix)
    $("div.items div.item", fieldset).formset({
        extraClasses: ['item'],
        prefix : prefix,
        added: function(row) {
        
            //Reset date fields
            $(".date_field", row).attr('class', 'date_field');
            $(".date_field", row).datepicker({ dateFormat: 'dd/mm/yy' });

            // Shadows the value of the same-classed field in the previous formset
            if (shadow){
                for (i in shadow) {
                    fields = $('fieldset.'+prefix + ' ' + shadow[i])
                    if (fields.length > 1) {
                        last = fields[fields.length-2].value;
                        $(shadow[i], row).attr('value', last);
                    }
                }
            }    
            
            //Reset placeholders
            set_placeholders();
        }
    });
};

/*global $, BITR, window */
/*jslint browser: true, onevar: false */

BITR.namespace("event");

BITR.event.processTweets = function () {
    $('.tweet span.text').processTweet();
};

BITR.event.Stream = function (event_slug) {

    var stream = this,
        count_new_url = "/EVENT_SLUG/e/_count_new/".replace('EVENT_SLUG', event_slug),
        get_tweet_url = "/EVENT_SLUG/e/_get_tweets/".replace("EVENT_SLUG", event_slug);

    this.count = parseInt($('#tweet_count').html(), 10);

    this.updater = undefined;

    this.get_latest_id = function () {
        var id = $('div#tweets div.tweet').attr('id');
        if (id) { 
            return id.replace('tweet_', ''); 
        }
        return 0;
    };

    this.get_oldest_id = function () {
        var last = $('div#tweets div.tweet:last');
        if (last) {
            return last.attr('id').replace('tweet_', '');
        }
        return -1;
    };

    this.reset_updater = function () {
        if (this.updater !== undefined) {
            this.updater.stop();
        }

        this.updater = $.PeriodicalUpdater(count_new_url, {
            method: 'get',
            data: {since_id: this.get_latest_id()},
            minTimeout: 10000,
            maxTimeout: 30000,
            multiplier: 1.2,
            maxCalls: 0,
            autoStop: 0
        }, function (data) {
            var response = parseInt(data, 10);
            if (response > 0) {
                if (response === 1) {
                    $('#new_tweets')[0].innerHTML = "1 new tweet";
                } else {
                    $('#new_tweets')[0].innerHTML = response + " new tweets";
                }
                $('#new_tweets').css('display', 'block');

                $('#tweet_count').html(stream.count + response);
            }
        });
    };

    this.populate_tweet = function (newTweet, tweetData) {
        newTweet.attr('id', 'tweet_' + tweetData.status_id_str);
        $('img', newTweet).attr('src', tweetData.profile_image_url);
        $('span.when', newTweet)[0].innerHTML = tweetData.created_since + ' ago via ' + tweetData.source;
        var author = $('a.author', newTweet);
        author.attr("href", 'http://twitter.com/' + tweetData.from_user);
        author[0].innerHTML = tweetData.from_user;
        $('span.text', newTweet)[0].innerHTML = tweetData.text;
        $('span.text', newTweet).processTweet();
    };

    this.highlight_tweet = function (tweet) {
        var bgDiv = $('div.content', tweet);
        bgDiv.css("background-color", '#F7F6E6');
        
        setTimeout(function () {
            bgDiv.animate({backgroundColor: '#FFF'}, 1000);
        }, 5000);

    };

    /** init **/

    this.start = function () {
        $('#new_tweets').click(function () {

            $.getJSON(get_tweet_url, {
                since_id: stream.get_latest_id()
            }, function (data, textStatus) {
                // tweets are ordered by status_id descending,
                // need to reverse so that they end up correct after doing
                // insertAfter
                $.each(data.reverse(), function (idx, tweet) { 
                    var newTweet = $('div.tweets div.tweet:first').clone(true);
                    stream.populate_tweet(newTweet, tweet);
                    stream.highlight_tweet(newTweet);


                    newTweet.insertAfter('#new_tweets');
                });

                $('#new_tweets').css('display', 'none');

                stream.count = parseInt($('#tweet_count').html(), 10);
                stream.reset_updater();

            });

        });

        $('#more_tweets').click(function () {
            $.getJSON(get_tweet_url, {
                before_id: stream.get_oldest_id()
            }, function (data, textStatus) {
                $.each(data, function (idx, tweet) {
                    var newTweet = $('div#tweets div.tweet:first').clone(true);
                    stream.populate_tweet(newTweet, tweet);
                    newTweet.insertBefore('#more_div');
                });

            });

            return false;
        });

        this.reset_updater();
    };

};

BITR.event.people = function(view) {
    // Use ajax and fetch more people and insert into display gallery or list.
    var table = document.getElementById('people_table');
    var limit = 6
    var per_row = 6
    var offset = table.rows.length * table.rows[0].cells.length;
    if (view == "list") {
        
        limit = 24;
        per_row = 2;
    }
    
    var data = {offset: offset, limit: limit, per_row: per_row}
    $.post(".", data, function(data, textStatus, xhr) {
        for (var i = 0; i < data.length; i++) {
           var row = table.insertRow(table.rows.length);
           for(var j = 0; j < data[i].length; j++) {
               var result = data[i][j];
               var cell = row.insertCell(row.cells.length);
               if (view == "list") {
                   $(cell).addClass("people_list");
                   cell.innerHTML="<strong class='name'>"+result.name+
                   "</strong>, <a class='author' href='http://twitter.com/"+
                   result.screen_name+"'>@"+result.screen_name+"</a> <span class='count'>"+result.count+" tweet"+(result.count!=1?"s":"")+
                   "</span>";
               }
               else {
                   $(cell).addClass("people_gallery");
                   cell.innerHTML="<a href='http://twitter.com/"+ result.screen_name+"'>\
                   <img src='" + result.profile_image_url + "' width='55' height='55'/>\
                   </a><br><strong class='name'>"+ result.name +"</strong><br>\
                   <a class='author' href='http://twitter.com/"+ result.screen_name+"'>@"+result.screen_name+"</a>\
                   <br><span class='count'>"+result.count+" tweet"+(result.count!=1?"s":"")+"</span><br>";
               }
               var attend_img = "attend-img-none";
               if (result.attendee) attend_img = "attend-img-small";
               
               cell.innerHTML +='\
               <div class="attending_user">\
                 <div class="'+attend_img+'"></div>\
               </div>'
               if (view != 'list'){
                 cell.innerHTML = "<div>"+cell.innerHTML+"</div>"
               }
           }
      }
    }, "json")
    return false;
}

BITR.event.AutoStream = function (event_slug) {
    var stream = this,
        url = "/EVENT_SLUG/e/_get_tweets/";

    this.url = url.replace('EVENT_SLUG', event_slug);
    this.updater = undefined;

    this.reset_updater = function () {
        if (stream.updater !== undefined) {
            stream.updater.stop();
        }

        stream.updater = $.PeriodicalUpdater(this.url, {
            method: 'get',
            data: {since_id: stream.get_latest_id()},
            minTimeout: 2000,
            maxTimeout: 10000,
            multiplier: 1.1,
            maxCalls: 0,
            streamStop: 0
        }, function (data) {
            data = $.parseJSON(data);

            $.each(data.reverse(), function (idx, tweet) { 
                var newTweet = $('#tweet_template').clone(true),
                    countSpan = $('#tweet_count span')[0];

                stream.populate_tweet(newTweet, tweet);
                $('#tweets div.tweet:first').before(newTweet);

                newTweet.css("display", "block");

                stream.highlight_tweet(newTweet);

                if ($('#tweets div.tweet').size() > 20) {
                    $('#tweets div.tweet:last').remove();
                }

                countSpan.innerHTML = parseInt(countSpan.innerHTML, 10) + 1;

            });

            if (data.length > 0) {
                stream.reset_updater();
            }

        });
    };

    this.start = function () {
        this.reset_updater();
    };

};

BITR.event.AutoStream.prototype = new BITR.event.Stream();
BITR.event.AutoStream.constructor = BITR.event.AutoStream;

BITR.event.Retweets = function (event_slug) {
    var retweets = this;

    retweets.url = "/EVENT_SLUG/e/_get_retweets/"
        .replace("EVENT_SLUG", event_slug);
    retweets.skip = 20;

    retweets.init = function () {
        $('#more_div').click(retweets.load_more);
    };

    retweets.load_more = function () {
        $.getJSON(retweets.url, {
            skip: retweets.skip
        }, function (data, textStatus) {
            $.each(data, function (idx, tweet) {
                var newTweet = $('div.tweets div.tweet:first').clone(true);
                retweets.populate(newTweet, tweet);
                newTweet.insertBefore('#more_div');
            });
            retweets.skip += data.length;
        });
        return false;
    };

    retweets.populate = function (newTweet, data) {
        var count = $('span.count', newTweet)[0];
        if (data.count === 1) {
            count.innerHTML = "1 RT";
        } else {
            count.innerHTML = data.count + " RTS";
        }

        $('img', newTweet).attr("src", data.profile_image_url);

        var author = $('a.author', newTweet);
        author.attr("href", 'http://twitter.com/' + data.screen_name);
        author[0].innerHTML = "@" + data.screen_name;
        $('span.text', newTweet)[0].innerHTML = data.text;
        $('span.text', newTweet).processTweet();

    };

};

BITR.event.People = function (event_slug) {
    BITR.event.Retweets.call(this, event_slug);
    var people = this;

    people.url = "/EVENT_SLUG/e/_get_people/"
        .replace("EVENT_SLUG", event_slug);

    people.populate = function (newTweet, data) {
        var count = $('span.count', newTweet)[0];
        if (data.count === 1) {
            count.innerHTML = "1 tweet";
        } else {
            count.innerHTML = data.count + " tweets";
        }

        $('img', newTweet).attr("src", data.profile_image_url);

        var author = $('a.author', newTweet);
        author.attr("href", 'http://twitter.com/' + data.screen_name);
        author[0].innerHTML = "@" + data.screen_name;

        $('strong.name', newTweet)[0].innerHTML = data.name;

    };

};
BITR.event.People.prototype = new BITR.event.Retweets();
BITR.event.People.constructor = BITR.event.People;

BITR.event.post_attend = function(event_slug, attend, callback) {
    var url = "/EVENT_SLUG/e/attend/".replace('EVENT_SLUG', event_slug);
    var data = {};
    if (attend) {
        data.attend = 1;
    } else {
        data.unattend = 1;
    }
    $.post(url, data, callback);
}

BITR.event.attend_event = function(slug) {
  return function() {
    BITR.event.post_attend(slug, true, function (data, textStatus) {
        if (data === "attended") {
            $("div.attend-status-attend").css("display", "none");
            $("div.attend-status-unattend").css("display", "block")
            var count = $("#attendee-count")[0]
            if (count) {
                count.innerHTML = (parseInt(count.innerHTML, 10) + 1) + "";
            }
            $(".user-attend-img").removeClass("attend-img-none");
            $(".user-attend-img").addClass("attend-img-small");
            $(".people_option").removeClass("people_hidden");
            $(".people_option").removeClass("people_hidden");
            $(".people_table").removeClass("people_hidden");
            $(".user-attend").removeClass("people_none");
        }
    });
    return false;
  }
}

BITR.event.unattend_event = function(slug) {
    return function() {
      BITR.event.post_attend(slug, false, function (data, textStatus) {
          if (data === "unattended") {
              $("div.attend-status-attend").css("display", "block");
              $("div.attend-status-unattend").css("display", "none");
              var count = $("#attendee-count")[0]
              if (count) {
                  count.innerHTML = (parseInt(count.innerHTML, 10) - 1) + "";
              }
              $(".user-attend-img").removeClass("attend-img-small");
              $(".user-attend-img").addClass("attend-img-none");
          }
      });
      return false;
    }
}

BITR.event.attend_twitter = function() {
    $("form.connect-button")[0].submit();
}

BITR.event.post_save = function (event_slug, add, callback) {
    var url = "/EVENT_SLUG/e/save/".replace('EVENT_SLUG', event_slug);
    var data = {};
    if (add) {
        data.add = 1;
    } else {
        data.remove = 1;
    }
    $.post(url, data, callback);
};

BITR.event.Save = function (event_slug, el, saved) {
    var btn = this;

    btn.$ = el;

    btn.set_status = function (saved) {
        var txt;
        btn.saved = saved;
        if (saved) {
            $(btn.$)[0].innerHTML = "Saved";
			$(btn.$)[0].className = "save-event-btn with-remove";
        } else {
            $(btn.$)[0].innerHTML = "Save";
			$(btn.$)[0].className = "save-event-btn";
        }
    };
    btn.set_status(saved);

    btn.on_response = function (data, textStatus) {
        if (data === "added") {
            btn.set_status(true);
        } else if (data === "removed") {
            btn.set_status(false);
        } else if (data === "login") {
            window.location = "/login/";
        }
    };

    btn.click = function () {
        BITR.event.post_save(event_slug, !btn.saved, btn.on_response);
        return false;
    };


    btn.$.click(btn.click);

};

BITR.event.Votes = function (event_slug) {

    var vote_url = "/SLUG/e/vote/".replace('SLUG', event_slug);

    /* matches Vote.CATEGORY_XXX */
    var categories = ['V', 'N', 'C', 'W'];

    function bind($elem, category, action, success) {
        $elem.click(function () {
            if ($elem.hasClass('clicked')) {
                return false;
            }
            $.ajax({
                type: 'POST',
                url: vote_url,
                data: {
                    category: category,
                    action: action
                },
                success: success
            });
            return false;
        });
    }

    function set_value($elem, value) {
        if (value > 0) {
            $elem.html('+' + value);
        } else {
            $elem.html(value);
        }
    }

    function update_total() {
        var total = 0;
        $.each(categories, function (idx, cat) {
            total += parseInt($('#votes_' + cat).html(), 10);
        });
        set_value($('#votes_total'), total);
    }

    $.each(categories, function (idx, cat) {
        var $votes = $('#votes_' + cat),
            score = parseInt($votes.html(), 10),
            $up = $('#upvote_' + cat),
            $down = $('#downvote_' + cat);

        function do_bind($target, $other, action, val) {
            bind($target, cat, action, function (data) {
                if (data !== 'ok') {
                    return;
                }
                if ($other.hasClass('clicked')) {
                    $other.removeClass('clicked');
                    score += val;
                }
                $target.addClass('clicked');
                score += val;
                set_value($votes, score);
                update_total();
            });
        }
        do_bind($up, $down, 'upvote', 1);
        do_bind($down, $up, 'downvote', -1);
    });

};



BITR.event.table_save_button = function () {
    var $el = $(this);
    var slug = $el.parents('tr').attr('id').replace('event_slug-', '');
    BITR.event.post_save(slug, !$el.hasClass("checkmark"), function (data, textStatus) {
        if (data === "added") {
            $el.addClass("checkmark").removeClass("green-s").html("").attr("title", "Remove from saved").attr("style", "height:20px !important;padding-top:7px;");
        } else if (data === "removed") {
            $el.removeClass("checkmark").addClass("green-s").html("save").attr("title", "Save event").attr("style", "height:20px !important;padding-top:7px;");
        }
    });
    return false;

};

BITR.event.hotspot_save_button = function () {
    var $el = $(this);
    var slug = $el.parents('li').attr('id').replace('event_slug-', '');
    BITR.event.post_save(slug, $el.hasClass("gray-heart"), function (data, textStatus) {
        if (data === "added") {
            $el.addClass("green-heart").removeClass("gray-heart").attr("title", "Remove from saved");
        } else if (data === "removed") {
            $el.removeClass("green-heart").addClass("gray-heart").attr("title", "Save event");
        }
    });
    return false;

};


BITR.namespace('twitter');

BITR.twitter.TweetDialog = function (elem, error, title, cancel, close) {
    var dialog = this;
    var $elem = $(elem);
    var $error_elem = $(error);
    title = title ? title : "Tweet this";
    cancel = cancel ? cancel : "Cancel";
    close = close ? close : function () {};
    dialog.reply_to_id = undefined;

    $error_elem.dialog({
        autoOpen: false,
        draggable: false,
        resizable: false,
        title: "Error",
        buttons: {
            "Ok": function () {
                $(this).dialog('close');
            }
        },
        modal: true
    });
 
    var buttons = {
        "Tweet": function () {
            $.ajax({
                type: 'POST',
                url: "/twitter/tweet/",
                data: {
                    text: $('.tweet_input', $elem).val().trim(),
                    reply_to_id: dialog.reply_to_id
                },
                success: function (data, textStatus, xhr) {
                    if (data === 'ok') {
                        $elem.dialog('close');
                    } else {
                        dialog.error();
                    }
                },
                error: function (xhr) {
                    dialog.error();
                }
            });

        },
    }
    buttons[cancel] = function () {
        $elem.dialog('close');
    }
    
    $elem.dialog({
        autoOpen: false,
        draggable: false,
        resizable: false,
        width: 400,
        title: title,
        buttons: buttons,
        modal: true,
        close: function() {
            close ();
        }
        
    });
            
    function update_chars_remaining() {
        var c = 140 - $('.tweet_input', $elem).val().trim().length,
            $remaining = $('.chars_remaining', $elem);

        $remaining.html(c);
        if (c < 0) {
            $remaining.addClass('negative');
        } else {
            $remaining.removeClass('negative');
        }
    }

    $('.tweet_input', $elem).keydown(update_chars_remaining).change(update_chars_remaining)
        .keyup(update_chars_remaining);

    dialog.show = function (text, reply_to_id) {
        dialog.reply_to_id = reply_to_id;

        $('.tweet_input', $elem).val(text);
        update_chars_remaining();
        $elem.dialog('open');
    };

    dialog.error = function () {
        $error_elem.dialog('open');
    };

};


BITR.event.init_action_dialogs = function () {
    
    var $tweet_dialog = new BITR.twitter.TweetDialog($('#tweet_dialog'), $('#tweet_error'));
    function on_reply() {
        var $tweet = $(this).parents('div.tweet');
        var text = '@' + $('.author', $tweet).html().trim() + ' ';
        var reply_to_id = $tweet.attr('id').replace('tweet_', '');
        $tweet_dialog.show(text, reply_to_id);

        return false;

    }

    function on_retweet() {
        var $tweet = $(this).parents('div.tweet');
        var text = 'RT @' + $('.author', $tweet).html().trim() +
            ': ' + $('.text', $tweet).attr('tweettext').trim();
        var reply_to_id = $tweet.attr('id').replace('tweet_', '');
        $tweet_dialog.show(text, reply_to_id);

        return false;
    }
    
    function on_attend() {
        var slug = $('.event_slug', $tweet).html().trim()
        var url = document.URL.match("http://[^/]+/")+slug+"/e/people/";
        var $tweet_dialog = new BITR.twitter.TweetDialog($('#tweet_dialog'), $('#tweet_error')
          , "Would you like to tweet that you are attending?", "No Thanks", function() {
            if (window.location != url) window.location = url
          });
        var $tweet = $('.attend_status');
        var name = $('.event_name').html().trim()
        var hash = $('.event_hash').html().trim()
        var text = 'I am attending ' + name + " #" + hash + ". You can see this event on Be In The Room. " + url;
        $tweet_dialog.show(text);
    }
    
    
    
    $('div.tweet a.action_reply').click(on_reply);
    $('div.tweet a.action_retweet').click(on_retweet);
    $('a.attend-event').click(on_attend);
    
};




BITR.namespace("my_saved");
BITR.my_saved.init = function () {
    $('#events a.save_btn').click(BITR.event.table_save_button);
};

BITR.namespace('facebook');
BITR.facebook.submit_post = function(form, session) {
    $form = $(form);

    $form.appendTo($("#fb-root"));

    function add_data(k, v) {
        var el = document.createElement("input");
        el.type = "hidden"
        el.name = k;
        el.value = v;
        $form.append(el);
    };

    $.each(session, function(k, v) {
        add_data('fbs_'+k, v);
    });

    // call api to get user info
    FB.api('/me',  {fields: 'id,first_name,last_name,picture'}, function(response) {
        add_data('first_name', response.first_name);
        add_data('last_name', response.last_name);
        add_data('picture', response.picture);
        form.submit();

    });

};

$(document).ready(function() {

    $('.facebook-connect-button').click(function() {
        FB.getLoginStatus(process_status);
        return false;
    });

    function process_status(response) {
        if (!response.session) {
            FB.login(do_submit);
        } else {
            do_submit(response);
        }
    }

    function do_submit(response) {
        var form = document.createElement("form");
        form.action = "/social/facebook/login/";
        form.method = "POST";
        BITR.facebook.submit_post(form, response.session);
    }


    $('.facebook-disconnect-button').click(function() {
        FB.getLoginStatus(do_disconnect);
        return false;
    });

    function do_disconnect(response) {
        if (response.session) {
            disconnect_revoke(response);
        } else {
            FB.login(disconnect_revoke);
        }
    }

    function disconnect_revoke(response) {
        if (response.session) {
            var form = document.createElement("form");
            $form = $(form).attr('action', "/social/facebook/disconnect/")
                .attr('method', 'POST');
            var e = document.createElement("input");
            $(e).attr('name', 'uid').attr('value', response.session.uid).appendTo($form);
            $form.appendTo('body').submit();
        }
    }

});

BITR.facebook.init_change = function() {
    $('#change_facebook').click(function() {
        FB.getLoginStatus(do_change);
        return false;
    });

    function do_change(response) {
        if (response.session) {
            // revoke authorization then move to step 2
            FB.api({
                method: 'auth.revokeAuthorization'
            }, do_login);
        } else {
            // user is not logged in or has not authorized
            // this account, call login
            do_login(response);
        }
    }

    function do_login(response) {
        if (response.session) {
            alert('fatal error, still logged in');
        } else {
            FB.login(on_login);
        }
    }

    function on_login(response) {
        if (response.session) {
            var form = document.createElement("form");
            form.action = "/social/facebook/login/";
            form.method = "POST";
            BITR.facebook.submit_post(form, response.session);
        } else {
            // TODO: cancelled
        }

    }

};


BITR.namespace("search");

BITR.search.hints = function() {
    var hint_text = 'hashtags, name, city, country or topics';

    $('#search').blur(function() {
        if ($('#search').val() == '') {
            $('#search').addClass('hint');
            $('#search').val(hint_text);
        }
    });

    $('#search').focus(function () {
        $('#search').removeClass('hint');
        if ($('#search').val() == hint_text) {
            $('#search').val('');
        }
    });

    if ($('#search').val() != hint_text) {
        if ($('#search').val() == '') {
            $('#search').addClass('hint');
            $('#search').val(hint_text);
        } else {
            $('#search').removeClass('hint');
        }
    }

};

$(document).ready(BITR.search.hints);

BITR.search.paginator_init = function() {
    $('#page_selector').change(function() {
        window.location = $.param.querystring(window.location.href, {p: $(this).val() });

    });

    $('#id_results_per_page').change(function(){
        window.location = $.param.querystring(window.location.href, {results_per_page: $(this).val() });
    });
}

BITR.search.init = function(show, pnum) {
    var show_filters = show;

    BITR.search.paginator_init();

    $('#id_start_date').datepicker({ dateFormat: 'dd/mm/yy' });

    $('#toggle_filters').click(function() {
        update_filter_viz(!show_filters);

        return false;
    });

    function update_filter_viz(show) {
        show_filters = show;

        var txt = '';
        if (show_filters) {
            $('#filters').show();
            txt = 'Hide filters';
        } else {
            $('#filters').hide();
            txt = 'Filter Search Results';
        }
        $('#toggle_filters').text(txt);
    }
    update_filter_viz(show_filters);

};

BITR.namespace("fields");
BITR.fields.init = function() {
    $.each($(".autocomplete"), function(index, value) {
        var source = $.parseJSON(value.getAttribute('data-source'))
        $('#'+value.id).autocomplete({source: source });
    })
}

$(document).ready(BITR.fields.init);


