/*
 * OverlayPlayground.  Liscensed to chicagomovers.org
 */
(function($) {
$.fn.overlayPlayground = function(o){
    var defaults = {
        background: '#000',
        opacity: .75,
        zIndex: 1000,
        fixed: true,
        playgroundFixed: false,
        html: '',
        overlay: true,
        open: true,
        destroyOnClose: false
    }
    if (o == 'close') o = {open: false};
    if (o == 'open') o = {open: true};
    o = $.extend(defaults, o);
    var ie6 = (typeof document.body.style.maxWidth == "undefined") ? true : false;
    return this.each(function(){
        if(o.open) {
            if($(this).find('.overlayPlaygroundOverlay,.overlayPlaygroundPlayground').length > 0) {
                $(this).find('.overlayPlaygroundOverlay,.overlayPlaygroundPlayground').show();
            }
            else {
                $(this).height($(this).height());
                if(o.overlay) {
                    $('<div class="overlayPlaygroundOverlay">&nbsp;</div>').css({
                        opacity: o.opacity,
                        filter: 'alpha(opacity='+(o.opacity * 100)+')',
                        background: o.background,
                        zIndex: o.zIndex,
                        padding: 0,
                        margin: 0,
                        height: $(this).height() + 'px',
                        width: '100%',
                        left: 0,
                        top: 0,
                        position: (ie6 || !o.fixed) ? 'absolute' : 'fixed'
                    }).appendTo(this);
                }
                $('<div class="overlayPlaygroundPlayground"></div>').css({
                    zIndex: o.zIndex + 10,
                    padding: 0,
                    margin: 0,
                    height: '100%',
                    width: '100%',
                    left: 0,
                    top: 0,
                    position: (ie6 || !o.playgroundFixed) ? 'absolute' : 'fixed'
                }).html(o.html).appendTo(this);
            }
        }
        else {
            if(!o.destroyOnClose)
                $(this).find('.overlayPlaygroundOverlay,.overlayPlaygroundPlayground').hide();
            else
                $(this).find('.overlayPlaygroundOverlay,.overlayPlaygroundPlayground').remove();
        }
    });
}
})(jQuery);

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

function state_picker(moving_state, moving_city) {
    var current_state = $('#'+ moving_state).attr('value');
    /**
     * Load all zip codes once HTML is ready.
     */
    $.post('/static/inc/transactions/', {
        allzips: "yes"
    }, function(data) {
        data = data.split(',');
        $('input[name=zip]').autocomplete(data);
    });
    if(current_state != '') {
        /**
             * Initial AJAX call if state is already selected
             */
        $.post('/static/inc/transactions/', {
            state:current_state
        }, function(data) {
            data = data.split(',');
            $('input[name=' + moving_city + ']').autocomplete(data, {
                cacheLength:1
            });
        });
    /*$.post('/inc/transactions/', {state:current_state, zips: "yes"}, function(data) {
                data = data.split(',');
                $('input[name=zip]').autocomplete(data);
            });*/
    }
    $('#' + moving_state).change(function() {
        var state = $(this).attr('value');
        if(state == 'DC' || state == 'District of Columbia') {
            $('input[name=' + moving_city + ']').val('Washington');
        }
        current_state = state;
        /**
             * AJAX call to fill list of city names according to state
             * called when value of state dropdown changes
             */
        $.post('/static/inc/transactions/', {
            state: state
        }, function(data) {
            data = data.split(',');
            $('input[name=' + moving_city + ']').autocomplete(data, {
                cacheLength:1
            });
        });
    /*$.post('/inc/transactions/', {state: state, zips: "yes"}, function(data) {
                data = data.split(',');
                $('input[name=zip]').autocomplete(data);
            });*/
    });
}
Date.dayNames=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];Date.abbrDayNames=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];Date.monthNames=["January","February","March","April","May","June","July","August","September","October","November","December"];Date.abbrMonthNames=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];Date.firstDayOfWeek=1;Date.format="dd/mm/yyyy";Date.fullYearStart="20";(function(){function b(c,d){if(!Date.prototype[c]){Date.prototype[c]=d}}b("isLeapYear",function(){var c=this.getFullYear();return(c%4==0&&c%100!=0)||c%400==0});b("isWeekend",function(){return this.getDay()==0||this.getDay()==6});b("isWeekDay",function(){return !this.isWeekend()});b("getDaysInMonth",function(){return[31,(this.isLeapYear()?29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()]});b("getDayName",function(c){return c?Date.abbrDayNames[this.getDay()]:Date.dayNames[this.getDay()]});b("getMonthName",function(c){return c?Date.abbrMonthNames[this.getMonth()]:Date.monthNames[this.getMonth()]});b("getDayOfYear",function(){var c=new Date("1/1/"+this.getFullYear());return Math.floor((this.getTime()-c.getTime())/86400000)});b("getWeekOfYear",function(){return Math.ceil(this.getDayOfYear()/7)});b("setDayOfYear",function(c){this.setMonth(0);this.setDate(c);return this});b("addYears",function(c){this.setFullYear(this.getFullYear()+c);return this});b("addMonths",function(d){var c=this.getDate();this.setMonth(this.getMonth()+d);if(c>this.getDate()){this.addDays(-this.getDate())}return this});b("addDays",function(c){this.setTime(this.getTime()+(c*86400000));return this});b("addHours",function(c){this.setHours(this.getHours()+c);return this});b("addMinutes",function(c){this.setMinutes(this.getMinutes()+c);return this});b("addSeconds",function(c){this.setSeconds(this.getSeconds()+c);return this});b("zeroTime",function(){this.setMilliseconds(0);this.setSeconds(0);this.setMinutes(0);this.setHours(0);return this});b("asString",function(d){var c=d||Date.format;return c.split("yyyy").join(this.getFullYear()).split("yy").join((this.getFullYear()+"").substring(2)).split("mmmm").join(this.getMonthName(false)).split("mmm").join(this.getMonthName(true)).split("mm").join(a(this.getMonth()+1)).split("dd").join(a(this.getDate())).split("hh").join(a(this.getHours())).split("min").join(a(this.getMinutes())).split("ss").join(a(this.getSeconds()))});Date.fromString=function(o,n){var j=n||Date.format;var m=new Date("01/01/1977");var k=0;var c=j.indexOf("mmmm");if(c>-1){for(var g=0;g<Date.monthNames.length;g++){var e=o.substr(c,Date.monthNames[g].length);if(Date.monthNames[g]==e){k=Date.monthNames[g].length-4;break}}m.setMonth(g)}else{c=j.indexOf("mmm");if(c>-1){var e=o.substr(c,3);for(var g=0;g<Date.abbrMonthNames.length;g++){if(Date.abbrMonthNames[g]==e){break}}m.setMonth(g)}else{m.setMonth(Number(o.substr(j.indexOf("mm"),2))-1)}}var l=j.indexOf("yyyy");if(l>-1){if(c<l){l+=k}m.setFullYear(Number(o.substr(l,4)))}else{if(c<l){l+=k}m.setFullYear(Number(Date.fullYearStart+o.substr(j.indexOf("yy"),2)))}var h=j.indexOf("dd");if(c<h){h+=k}m.setDate(Number(o.substr(h,2)));if(isNaN(m.getTime())){return false}return m};var a=function(c){var d="0"+c;return d.substring(d.length-2)}})();(function(d){d.fn.extend({renderCalendar:function(q){var B=function(i){return document.createElement(i)};q=d.extend({},d.fn.datePicker.defaults,q);if(q.showHeader!=d.dpConst.SHOW_HEADER_NONE){var n=d(B("tr"));for(var v=Date.firstDayOfWeek;v<Date.firstDayOfWeek+7;v++){var h=v%7;var u=Date.dayNames[h];n.append(jQuery(B("th")).attr({scope:"col",abbr:u,title:u,"class":(h==0||h==6?"weekend":"weekday")}).html(q.showHeader==d.dpConst.SHOW_HEADER_SHORT?u.substr(0,1):u))}}var e=d(B("table")).attr({cellspacing:2,className:"jCalendar"}).append((q.showHeader!=d.dpConst.SHOW_HEADER_NONE?d(B("thead")).append(n):B("thead")));var f=d(B("tbody"));var y=(new Date()).zeroTime();var A=q.month==undefined?y.getMonth():q.month;var o=q.year||y.getFullYear();var l=new Date(o,A,1);var k=Date.firstDayOfWeek-l.getDay()+1;if(k>1){k-=7}var p=Math.ceil(((-1*k+1)+l.getDaysInMonth())/7);l.addDays(k-1);var z=function(){if(q.hoverClass){d(this).addClass(q.hoverClass)}};var g=function(){if(q.hoverClass){d(this).removeClass(q.hoverClass)}};var m=0;while(m++<p){var t=jQuery(B("tr"));for(var v=0;v<7;v++){var j=l.getMonth()==A;var x=d(B("td")).text(l.getDate()+"").attr("className",(j?"current-month ":"other-month ")+(l.isWeekend()?"weekend ":"weekday ")+(j&&l.getTime()==y.getTime()?"today ":"")).hover(z,g);if(q.renderCallback){q.renderCallback(x,l,A,o)}t.append(x);l.addDays(1)}f.append(t)}e.append(f);return this.each(function(){d(this).empty().append(e)})},datePicker:function(e){if(!d.event._dpCache){d.event._dpCache=[]}e=d.extend({},d.fn.datePicker.defaults,e);return this.each(function(){var g=d(this);var i=true;if(!this._dpId){this._dpId=d.event.guid++;d.event._dpCache[this._dpId]=new a(this);i=false}if(e.inline){e.createButton=false;e.displayClose=false;e.closeOnSelect=false;g.empty()}var f=d.event._dpCache[this._dpId];f.init(e);if(!i&&e.createButton){f.button=d('<a href="#" class="dp-choose-date" title="'+d.dpText.TEXT_CHOOSE_DATE+'">'+d.dpText.TEXT_CHOOSE_DATE+"</a>").bind("click",function(){g.dpDisplay(this);this.blur();return false});g.after(f.button)}if(!i&&g.is(":text")){g.bind("dateSelected",function(k,j,l){this.value=j.asString()}).bind("change",function(){if(this.value!=""){var j=Date.fromString(this.value);if(j){f.setSelected(j,true,true)}}});if(e.clickInput){g.bind("click",function(){g.dpDisplay()})}var h=Date.fromString(this.value);if(this.value!=""&&h){f.setSelected(h,true,true)}}g.addClass("dp-applied")})},dpSetDisabled:function(e){return b.call(this,"setDisabled",e)},dpSetStartDate:function(e){return b.call(this,"setStartDate",e)},dpSetEndDate:function(e){return b.call(this,"setEndDate",e)},dpGetSelected:function(){var e=c(this[0]);if(e){return e.getSelected()}return null},dpSetSelected:function(g,f,e){if(f==undefined){f=true}if(e==undefined){e=true}return b.call(this,"setSelected",Date.fromString(g),f,e,true)},dpSetDisplayedMonth:function(e,f){return b.call(this,"setDisplayedMonth",Number(e),Number(f),true)},dpDisplay:function(f){return b.call(this,"display",f)},dpSetRenderCallback:function(e){return b.call(this,"setRenderCallback",e)},dpSetPosition:function(e,f){return b.call(this,"setPosition",e,f)},dpSetOffset:function(e,f){return b.call(this,"setOffset",e,f)},dpClose:function(){return b.call(this,"_closeCalendar",false,this[0])},_dpDestroy:function(){}});var b=function(h,g,e,j,i){return this.each(function(){var f=c(this);if(f){f[h](g,e,j,i)}})};function a(e){this.ele=e;this.displayedMonth=null;this.displayedYear=null;this.startDate=null;this.endDate=null;this.showYearNavigation=null;this.closeOnSelect=null;this.displayClose=null;this.selectMultiple=null;this.verticalPosition=null;this.horizontalPosition=null;this.verticalOffset=null;this.horizontalOffset=null;this.button=null;this.renderCallback=[];this.selectedDates={};this.inline=null;this.context="#dp-popup"}d.extend(a.prototype,{init:function(e){this.setStartDate(e.startDate);this.setEndDate(e.endDate);this.setDisplayedMonth(Number(e.month),Number(e.year));this.setRenderCallback(e.renderCallback);this.showYearNavigation=e.showYearNavigation;this.closeOnSelect=e.closeOnSelect;this.displayClose=e.displayClose;this.selectMultiple=e.selectMultiple;this.verticalPosition=e.verticalPosition;this.horizontalPosition=e.horizontalPosition;this.hoverClass=e.hoverClass;this.setOffset(e.verticalOffset,e.horizontalOffset);this.inline=e.inline;if(this.inline){this.context=this.ele;this.display()}},setStartDate:function(e){if(e){this.startDate=Date.fromString(e)}if(!this.startDate){this.startDate=(new Date()).zeroTime()}this.setDisplayedMonth(this.displayedMonth,this.displayedYear)},setEndDate:function(e){if(e){this.endDate=Date.fromString(e)}if(!this.endDate){this.endDate=(new Date("12/31/2999"))}if(this.endDate.getTime()<this.startDate.getTime()){this.endDate=this.startDate}this.setDisplayedMonth(this.displayedMonth,this.displayedYear)},setPosition:function(e,f){this.verticalPosition=e;this.horizontalPosition=f},setOffset:function(e,f){this.verticalOffset=parseInt(e)||0;this.horizontalOffset=parseInt(f)||0},setDisabled:function(e){$e=d(this.ele);$e[e?"addClass":"removeClass"]("dp-disabled");if(this.button){$but=d(this.button);$but[e?"addClass":"removeClass"]("dp-disabled");$but.attr("title",e?"":d.dpText.TEXT_CHOOSE_DATE)}if($e.is(":text")){$e.attr("disabled",e?"disabled":"")}},setDisplayedMonth:function(f,n,j){if(this.startDate==undefined||this.endDate==undefined){return}var i=new Date(this.startDate.getTime());i.setDate(1);var l=new Date(this.endDate.getTime());l.setDate(1);var h;if((!f&&!n)||(isNaN(f)&&isNaN(n))){h=new Date().zeroTime();h.setDate(1)}else{if(isNaN(f)){h=new Date(n,this.displayedMonth,1)}else{if(isNaN(n)){h=new Date(this.displayedYear,f,1)}else{h=new Date(n,f,1)}}}if(h.getTime()<i.getTime()){h=i}else{if(h.getTime()>l.getTime()){h=l}}var g=this.displayedMonth;var k=this.displayedYear;this.displayedMonth=h.getMonth();this.displayedYear=h.getFullYear();if(j&&(this.displayedMonth!=g||this.displayedYear!=k)){this._rerenderCalendar();d(this.ele).trigger("dpMonthChanged",[this.displayedMonth,this.displayedYear])}},setSelected:function(k,e,f,h){if(e==this.isSelected(k)){return}if(this.selectMultiple==false){this.selectedDates={};d("td.selected",this.context).removeClass("selected")}if(f&&this.displayedMonth!=k.getMonth()){this.setDisplayedMonth(k.getMonth(),k.getFullYear(),true)}this.selectedDates[k.toString()]=e;var i="td.";i+=k.getMonth()==this.displayedMonth?"current-month":"other-month";i+=':contains("'+k.getDate()+'")';var j;d(i,this.ele).each(function(){if(d(this).text()==k.getDate()){j=d(this);j[e?"addClass":"removeClass"]("selected")}});if(h){var g=this.isSelected(k);$e=d(this.ele);$e.trigger("dateSelected",[k,j,g]);$e.trigger("change")}},isSelected:function(e){return this.selectedDates[e.toString()]},getSelected:function(){var e=[];for(s in this.selectedDates){if(this.selectedDates[s]==true){e.push(Date.parse(s))}}return e},display:function(e){if(d(this.ele).is(".dp-disabled")){return}e=e||this.ele;var l=this;var h=d(e);var k=h.offset();var m;var n;var g;var i;if(l.inline){m=d(this.ele);n={id:"calendar-"+this.ele._dpId,className:"dp-popup dp-popup-inline"};i={}}else{m=d("body");n={id:"dp-popup",className:"dp-popup"};i={top:k.top+l.verticalOffset,left:k.left+l.horizontalOffset};var j=function(q){var o=q.target;var p=d("#dp-popup")[0];while(true){if(o==p){return true}else{if(o==document){l._closeCalendar();return false}else{o=d(o).parent()[0]}}}};this._checkMouse=j;this._closeCalendar(true)}m.append(d("<div></div>").attr(n).css(i).append(d("<h2></h2>"),d('<div class="dp-nav-prev"></div>').append(d('<a class="dp-nav-prev-year" href="#" title="'+d.dpText.TEXT_PREV_YEAR+'">&lt;&lt;</a>').bind("click",function(){return l._displayNewMonth.call(l,this,0,-1)}),d('<a class="dp-nav-prev-month" href="#" title="'+d.dpText.TEXT_PREV_MONTH+'">&lt;</a>').bind("click",function(){return l._displayNewMonth.call(l,this,-1,0)})),d('<div class="dp-nav-next"></div>').append(d('<a class="dp-nav-next-year" href="#" title="'+d.dpText.TEXT_NEXT_YEAR+'">&gt;&gt;</a>').bind("click",function(){return l._displayNewMonth.call(l,this,0,1)}),d('<a class="dp-nav-next-month" href="#" title="'+d.dpText.TEXT_NEXT_MONTH+'">&gt;</a>').bind("click",function(){return l._displayNewMonth.call(l,this,1,0)})),d("<div></div>").attr("className","dp-calendar")).bgIframe());var f=this.inline?d(".dp-popup",this.context):d("#dp-popup");if(this.showYearNavigation==false){d(".dp-nav-prev-year, .dp-nav-next-year",l.context).css("display","none")}if(this.displayClose){f.append(d('<a href="#" id="dp-close">'+d.dpText.TEXT_CLOSE+"</a>").bind("click",function(){l._closeCalendar();return false}))}l._renderCalendar();d(this.ele).trigger("dpDisplayed",f);if(!l.inline){if(this.verticalPosition==d.dpConst.POS_BOTTOM){f.css("top",k.top+h.height()-f.height()+l.verticalOffset)}if(this.horizontalPosition==d.dpConst.POS_RIGHT){f.css("left",k.left+h.width()-f.width()+l.horizontalOffset)}d(document).bind("mousedown",this._checkMouse)}},setRenderCallback:function(e){if(e==null){return}if(e&&typeof(e)=="function"){e=[e]}this.renderCallback=this.renderCallback.concat(e)},cellRender:function(k,e,h,g){var l=this.dpController;var j=new Date(e.getTime());k.bind("click",function(){var i=d(this);if(!i.is(".disabled")){l.setSelected(j,!i.is(".selected")||!l.selectMultiple,false,true);if(l.closeOnSelect){l._closeCalendar()}}});if(l.isSelected(j)){k.addClass("selected")}for(var f=0;f<l.renderCallback.length;f++){l.renderCallback[f].apply(this,arguments)}},_displayNewMonth:function(f,e,g){if(!d(f).is(".disabled")){this.setDisplayedMonth(this.displayedMonth+e,this.displayedYear+g,true)}f.blur();return false},_rerenderCalendar:function(){this._clearCalendar();this._renderCalendar()},_renderCalendar:function(){d("h2",this.context).html(Date.monthNames[this.displayedMonth]+" "+this.displayedYear);d(".dp-calendar",this.context).renderCalendar({month:this.displayedMonth,year:this.displayedYear,renderCallback:this.cellRender,dpController:this,hoverClass:this.hoverClass});if(this.displayedYear==this.startDate.getFullYear()&&this.displayedMonth==this.startDate.getMonth()){d(".dp-nav-prev-year",this.context).addClass("disabled");d(".dp-nav-prev-month",this.context).addClass("disabled");d(".dp-calendar td.other-month",this.context).each(function(){var h=d(this);if(Number(h.text())>20){h.addClass("disabled")}});var g=this.startDate.getDate();d(".dp-calendar td.current-month",this.context).each(function(){var h=d(this);if(Number(h.text())<g){h.addClass("disabled")}})}else{d(".dp-nav-prev-year",this.context).removeClass("disabled");d(".dp-nav-prev-month",this.context).removeClass("disabled");var g=this.startDate.getDate();if(g>20){var f=new Date(this.startDate.getTime());f.addMonths(1);if(this.displayedYear==f.getFullYear()&&this.displayedMonth==f.getMonth()){d("dp-calendar td.other-month",this.context).each(function(){var h=d(this);if(Number(h.text())<g){h.addClass("disabled")}})}}}if(this.displayedYear==this.endDate.getFullYear()&&this.displayedMonth==this.endDate.getMonth()){d(".dp-nav-next-year",this.context).addClass("disabled");d(".dp-nav-next-month",this.context).addClass("disabled");d(".dp-calendar td.other-month",this.context).each(function(){var h=d(this);if(Number(h.text())<14){h.addClass("disabled")}});var g=this.endDate.getDate();d(".dp-calendar td.current-month",this.context).each(function(){var h=d(this);if(Number(h.text())>g){h.addClass("disabled")}})}else{d(".dp-nav-next-year",this.context).removeClass("disabled");d(".dp-nav-next-month",this.context).removeClass("disabled");var g=this.endDate.getDate();if(g<13){var e=new Date(this.endDate.getTime());e.addMonths(-1);if(this.displayedYear==e.getFullYear()&&this.displayedMonth==e.getMonth()){d(".dp-calendar td.other-month",this.context).each(function(){var h=d(this);if(Number(h.text())>g){h.addClass("disabled")}})}}}},_closeCalendar:function(e,f){if(!f||f==this.ele){d(document).unbind("mousedown",this._checkMouse);this._clearCalendar();d("#dp-popup a").unbind();d("#dp-popup").empty().remove();if(!e){d(this.ele).trigger("dpClosed",[this.getSelected()])}}},_clearCalendar:function(){d(".dp-calendar td",this.context).unbind();d(".dp-calendar",this.context).empty()}});d.dpConst={SHOW_HEADER_NONE:0,SHOW_HEADER_SHORT:1,SHOW_HEADER_LONG:2,POS_TOP:0,POS_BOTTOM:1,POS_LEFT:0,POS_RIGHT:1};d.dpText={TEXT_PREV_YEAR:"Previous year",TEXT_PREV_MONTH:"Previous month",TEXT_NEXT_YEAR:"Next year",TEXT_NEXT_MONTH:"Next month",TEXT_CLOSE:"Close",TEXT_CHOOSE_DATE:"Choose date"};d.dpVersion="$Id: jquery.datePicker.js 15 2008-12-17 04:40:18Z kelvin.luck $";d.fn.datePicker.defaults={month:undefined,year:undefined,showHeader:d.dpConst.SHOW_HEADER_SHORT,startDate:undefined,endDate:undefined,inline:false,renderCallback:null,createButton:true,showYearNavigation:true,closeOnSelect:true,displayClose:false,selectMultiple:false,clickInput:false,verticalPosition:d.dpConst.POS_TOP,horizontalPosition:d.dpConst.POS_LEFT,verticalOffset:0,horizontalOffset:0,hoverClass:"dp-hover"};function c(e){if(e._dpId){return d.event._dpCache[e._dpId]}return false}if(d.fn.bgIframe==undefined){d.fn.bgIframe=function(){return this}}d(window).bind("unload",function(){var f=d.event._dpCache||[];for(var e in f){d(f[e].ele)._dpDestroy()}})})(jQuery);
$(document).ready(function() {
    if($('#topform').length > 0) {
        state_picker('movingtostate','movingtocity');
        //state_picker('movingfromstate','movingfromcity');
    }
    var focusId, lastFocusId;
    $('#phone input').keypress(function(e) {
        var s = String.fromCharCode(e.which);
        if(e.which != 8 && !s.match(/\d/)) {
            return false;
        }
        return true;
    });

    $('#topform input, #topform select').focus(function() {
        lastFocusId = focusId;
        focusId = this.id;
    });

    $(document.body).keydown(function(e) {
        if(focusId == 'topform-submit') {//IE doesn't allow keydown event on input[type=image], so this is the alternative
            if(e.which == 8) {//8 = backspace
                if(lastFocusId == 'fourdiget') {// if the last focus was indeed on the fourdiget field
                    $('#fourdiget').focus();//focus on the previous field
                    var val = $('#fourdiget').val();
                    $('#fourdiget').val(val.charAt(0) + val.charAt(1) + val.charAt(2));//now delete last character as user expects
                }
                return false;//prevent going back in history
            }
        }
        return true;
    });
    
    if($('#topform').length > 0) {
        /**
         * Begin Calendar Functionality
         * The "Calendar Button" is inserted with an inline script in the main body of the home page,
         * and has an id="date-pick".  The image is /static/images/calendar.png.  The following code is triggered
         * from a click event on the calendar button, which was previously inserted.
         */
        // initialise the "Select date" link
        $('#date-pick').datePicker(
        // associate the link with a date picker
        {
            createButton:false,
            startDate: '01/' + this_month + '/' + this_year,// dd/mm/yyyy
            endDate: '31/12/' + next_year // dd/mm/yyyy
        }
        ).bind(
            // when the link is clicked display the date picker
            'click',
            function()
            {
                updateSelects($(this).dpGetSelected()[0]);
                $(this).dpDisplay();
                return false;
            }
            ).bind(
            // when a date is selected update the SELECTs
            'dateSelected',
            function(e, selectedDate, $td, state)
            {
                updateSelects(selectedDate);
            }
            ).bind(
            'dpClosed',
            function(e, selected)
            {
                updateSelects(selected[0]);
            }
            );

        var updateSelects = function (selectedDate)
        {
            selectedDate = new Date(selectedDate);
            var selectedMonth = (selectedDate.getMonth()+1);
            if(selectedMonth < 10) selectedMonth = '0' + selectedMonth;
            var selectedDay = selectedDate.getDate();
            if(selectedDay < 10) selectedDay = '0' + selectedDay;
            $('#moveday option[value=' + selectedDay + ']').attr('selected', 'selected');
            $('#movemonth option[value=' + selectedMonth + ']').attr('selected', 'selected');
            $('#moveyear option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
        }
        // listen for when the selects are changed and update the picker
        $('#moveday, #movemonth, #moveyear')
        .bind(
            'change',
            function()
            {
                /*var d = new Date(
                        $('#moveday').val(),
                        $('#movemonth').val(),
                        $('#moveyear').val()
                    );*/
                var dString = $('#moveday').val() + '/' + $('#movemonth').val() +  '/' + $('#moveyear').val();
                $('#date-pick').dpSetSelected(dString);
            }
            );

        // default the position of the selects to today
        if(default_date) {
            var today = new Date();
            updateSelects(today.getTime());
        }

        // and update the datePicker to reflect it...
        $('#moveday').trigger('change');
    }
});

$(document).ready(function() {
    var closeDefault = true;
    $('.readmore').click(function(){
        $(document.body).overlayPlayground({
            opacity: .6
        });
        $(document.body).addClass('modal');
        if($('#window').length == 0) {
            $('<div id="window"><div></div><a id="close-window" href="#">[x close]</a></div>').appendTo('.overlayPlaygroundPlayground');
            $('#close-window').click(function() {
                $(document.body).overlayPlayground('close');
                $(document.body).removeClass('modal');
                return false;
            });
            $('#window').click(function() {
                closeDefault = false;
            });
            $('.overlayPlaygroundPlayground').click(function() {
                if(closeDefault) {
                    $(document.body).overlayPlayground('close');
                    $(document.body).removeClass('modal');
                }
                closeDefault = true;
            });
        }
        var windowContent = $($(this).attr('href')).html();
        $('#window > div').html(windowContent);
        window.location.hash = '#';
        return false;
    })
})
