Ext.apply(Ext.form.VTypes, {
    password : function(val, field) {
        if (field.initialPassField) {
            var pwd = Ext.getCmp(field.initialPassField);
            val2 = pwd.getValue();
            if ((val != "") && (val2 != ""))
                return (val == val2);
        }
        return true;
    },

    passwordText : 'Passwords do not match'
});
Ext.ns('Ext.ux.form');
Ext.ux.form.FileUploadField = Ext.extend(Ext.form.TextField,  {
    buttonText: 'Browse...',
    buttonOnly: false,
    buttonOffset: 3,
    readOnly: true,
    autoSize: Ext.emptyFn,
    initComponent: function(){
        Ext.ux.form.FileUploadField.superclass.initComponent.call(this);
        this.addEvents(
            'fileselected'
            );
    },
    onRender : function(ct, position){
        Ext.ux.form.FileUploadField.superclass.onRender.call(this, ct, position);
        this.wrap = this.el.wrap({
            cls:'x-form-field-wrap x-form-file-wrap'
        });
        this.el.addClass('x-form-file-text');
        this.el.dom.removeAttribute('name');
        this.createFileInput();
        var btnCfg = Ext.applyIf(this.buttonCfg || {}, {
            text: this.buttonText
        });
        this.button = new Ext.Button(Ext.apply(btnCfg, {
            renderTo: this.wrap,
            cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '')
        }));
        if(this.buttonOnly){
            this.el.hide();
            this.wrap.setWidth(this.button.getEl().getWidth());
        }
        this.bindListeners();
        this.resizeEl = this.positionEl = this.wrap;
    },
    bindListeners: function(){
        this.fileInput.on({
            scope: this,
            mouseenter: function() {
                this.button.addClass(['x-btn-over','x-btn-focus'])
            },
            mouseleave: function(){
                this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
            },
            mousedown: function(){
                this.button.addClass('x-btn-click')
            },
            mouseup: function(){
                this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
            },
            change: function(){
                var v = this.fileInput.dom.value;
                this.setValue(v);
                this.fireEvent('fileselected', this, v);
            }
        });
    },
    createFileInput : function() {
        this.fileInput = this.wrap.createChild({
            id: this.getFileInputId(),
            name: this.name||this.getId(),
            cls: 'x-form-file',
            tag: 'input',
            type: 'file',
            size: 1
        });
    },
    reset : function(){
        this.fileInput.remove();
        this.createFileInput();
        this.bindListeners();
        Ext.ux.form.FileUploadField.superclass.reset.call(this);
    },
    getFileInputId: function(){
        return this.id + '-file';
    },
    onResize : function(w, h){
        Ext.ux.form.FileUploadField.superclass.onResize.call(this, w, h);
        this.wrap.setWidth(w);
        if(!this.buttonOnly){
            var neww = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset;
            this.el.setWidth(neww);
        }
    },
    onDestroy: function(){
        Ext.ux.form.FileUploadField.superclass.onDestroy.call(this);
        Ext.destroy(this.fileInput, this.button, this.wrap);
    },
    onDisable: function(){
        Ext.ux.form.FileUploadField.superclass.onDisable.call(this);
        this.doDisable(true);
    },
    onEnable: function(){
        Ext.ux.form.FileUploadField.superclass.onEnable.call(this);
        this.doDisable(false);

    },
    doDisable: function(disabled){
        this.fileInput.dom.disabled = disabled;
        this.button.setDisabled(disabled);
    },
    preFocus : Ext.emptyFn,
    alignErrorIcon : function(){
        this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
    }
});
Ext.reg('fileuploadfield', Ext.ux.form.FileUploadField);
Ext.form.FileUploadField = Ext.ux.form.FileUploadField;
Ext.ux.form.SearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent : function(){
        Ext.ux.form.SearchField.superclass.initComponent.call(this);
        this.on('specialkey', function(f, e){
            if(e.getKey() == e.ENTER){
                this.onTrigger2Click();
            }
        }, this);
    },
    validationEvent:false,
    validateOnBlur:false,
    trigger1Class:'x-form-clear-trigger',
    trigger2Class:'x-form-search-trigger',
    hideTrigger1:true,
    width:180,
    hasSearch : false,
    paramName : 'p',
    emptyText: 'Enter some terms to search',
    onTrigger1Click : function() {
        if (this.hasSearch){
            this.el.dom.value = '';
            var o = {
                start: 0
            };
            this.store.baseParams = this.store.baseParams || {};
            this.store.baseParams[this.paramName] = '';
            this.store.reload({
                params:o
            });
            this.triggers[0].hide();
            this.hasSearch = false;
            this.store.removeAll(false);
            Ext.get(this.dataview).setVisible(false);
        }
    },
    onTrigger2Click : function() {
        var v = this.getRawValue();
        if(v.length < 1){
            this.onTrigger1Click();
            return;
        }
        var o = {
            start: 0
        };
        this.store.baseParams = this.store.baseParams || {};
        this.store.baseParams[this.paramName] = v;
        this.store.reload({
            params:o
        });
        this.hasSearch = true;
        this.triggers[0].show();
        Ext.get(this.dataview).setVisible(true);
    }
});
Ext.reg('searchfield', Ext.ux.form.SearchField);
Ext.ns('Ext.ux')
Ext.ux.Carousel = Ext.extend(Ext.util.Observable, {
    interval: 3,
    transitionDuration: 1,
    transitionType: 'carousel',
    transitionEasing: 'easeOut',
    itemSelector: 'img',
    activeSlide: 0,
    autoPlay: false,
    showPlayButton: false,
    pauseOnNavigate: false,
    wrap: false,
    freezeOnHover: false,
    navigationOnHover: false,
    hideNavigation: false,
    width: null,
    height: null,

    constructor: function(elId, config) {
        config = config || {};
        Ext.apply(this, config);

        Ext.ux.Carousel.superclass.constructor.call(this, config);

        this.addEvents(
            'beforeprev',
            'prev',
            'beforenext',
            'next',
            'change',
            'play',
            'pause',
            'freeze',
            'unfreeze'
            );

        this.el = Ext.get(elId);
        this.slides = this.els = [];

        if(this.autoPlay || this.showPlayButton) {
            this.wrap = true;
        }

        if(this.autoPlay && typeof config.showPlayButton === 'undefined') {
            this.showPlayButton = true;
        }

        this.initMarkup();
        this.initEvents();

        if(this.carouselSize > 0) {
            this.refresh();
        }
    },

    initMarkup: function() {
        var dh = Ext.DomHelper;

        this.carouselSize = 0;
        var items = this.el.select(this.itemSelector);
        this.els.container = dh.append(this.el, {
            cls: 'ux-carousel-container'
        }, true);
        this.els.slidesWrap = dh.append(this.els.container, {
            cls: 'ux-carousel-slides-wrap'
        }, true);

        this.els.navigation = dh.append(this.els.container, {
            cls: 'ux-carousel-nav'
        }, true).hide();
        this.els.caption = dh.append(this.els.navigation, {
            tag: 'h4',
            cls: 'ux-carousel-caption'
        }, true);
        this.els.navNext = dh.append(this.els.navigation, {
            tag: 'a',
            href: '#',
            cls: 'ux-carousel-nav-next'
        }, true);
        if(this.showPlayButton) {
            this.els.navPlay = dh.append(this.els.navigation, {
                tag: 'a',
                href: '#',
                cls: 'ux-carousel-nav-play'
            }, true)
        }
        this.els.navPrev = dh.append(this.els.navigation, {
            tag: 'a',
            href: '#',
            cls: 'ux-carousel-nav-prev'
        }, true);

        // set the dimensions of the container
        this.slideWidth = this.width || this.el.getWidth(true);
        this.slideHeight = this.height || this.el.getHeight(true);
        this.els.container.setStyle({
            width: this.slideWidth + 'px',
            height: this.slideHeight + 'px'
        });

        this.els.caption.setWidth((this.slideWidth - (this.els.navNext.getWidth()*2) - (this.showPlayButton ? this.els.navPlay.getWidth() : 0) - 20) + 'px')

        items.appendTo(this.els.slidesWrap).each(function(item) {
            item = item.wrap({
                cls: 'ux-carousel-slide'
            });
            this.slides.push(item);
            item.setWidth(this.slideWidth + 'px').setHeight(this.slideHeight + 'px');
        }, this);
        this.carouselSize = this.slides.length;
        if(this.navigationOnHover) {
            this.els.navigation.setStyle('top', (-1*this.els.navigation.getHeight()) + 'px');
        }
        this.el.clip();
    },

    initEvents: function() {
        this.els.navPrev.on('click', function(ev) {
            ev.preventDefault();
            var target = ev.getTarget();
            target.blur();
            if(Ext.fly(target).hasClass('ux-carousel-nav-disabled')) return;
            this.prev();
        }, this);

        this.els.navNext.on('click', function(ev) {
            ev.preventDefault();
            var target = ev.getTarget();
            target.blur();
            if(Ext.fly(target).hasClass('ux-carousel-nav-disabled')) return;
            this.next();
        }, this);

        if(this.showPlayButton) {
            this.els.navPlay.on('click', function(ev){
                ev.preventDefault();
                ev.getTarget().blur();
                if(this.playing) {
                    this.pause();
                }
                else {
                    this.play();
                }
            }, this);
        }

        if(this.freezeOnHover) {
            this.els.container.on('mouseenter', function(){
                if(this.playing) {
                    this.fireEvent('freeze', this.slides[this.activeSlide]);
                    Ext.TaskMgr.stop(this.playTask);
                }
            }, this);
            this.els.container.on('mouseleave', function(){
                if(this.playing) {
                    this.fireEvent('unfreeze', this.slides[this.activeSlide]);
                    Ext.TaskMgr.start(this.playTask);
                }
            }, this, {
                buffer: (this.interval/2)*1000
            });
        }

        if(this.navigationOnHover) {
            this.els.container.on('mouseenter', function(){
                if(!this.navigationShown) {
                    this.navigationShown = true;
                    this.els.navigation.stopFx(false).shift({
                        y: this.els.container.getY(),
                        duration: this.transitionDuration
                    })
                }
            }, this);

            this.els.container.on('mouseleave', function(){
                if(this.navigationShown) {
                    this.navigationShown = false;
                    this.els.navigation.stopFx(false).shift({
                        y: this.els.navigation.getHeight() - this.els.container.getY(),
                        duration: this.transitionDuration
                    })
                }
            }, this);
        }

        if(this.interval && this.autoPlay) {
            this.play();
        }
    },

    prev: function() {
        if (this.fireEvent('beforeprev') === false) {
            return;
        }
        if(this.pauseOnNavigate) {
            this.pause();
        }
        this.setSlide(this.activeSlide - 1);

        this.fireEvent('prev', this.activeSlide);
        return this;
    },

    next: function() {
        if(this.fireEvent('beforenext') === false) {
            return;
        }
        if(this.pauseOnNavigate) {
            this.pause();
        }
        this.setSlide(this.activeSlide + 1);

        this.fireEvent('next', this.activeSlide);
        return this;
    },

    play: function() {
        if(!this.playing) {
            this.playTask = this.playTask || {
                run: function() {
                    this.playing = true;
                    this.setSlide(this.activeSlide+1);
                },
                interval: this.interval*1000,
                scope: this
            };

            this.playTaskBuffer = this.playTaskBuffer || new Ext.util.DelayedTask(function() {
                Ext.TaskMgr.start(this.playTask);
            }, this);

            this.playTaskBuffer.delay(this.interval*1000);
            this.playing = true;
            if(this.showPlayButton) {
                this.els.navPlay.addClass('ux-carousel-playing');
            }
            this.fireEvent('play');
        }
        return this;
    },

    pause: function() {
        if(this.playing) {
            Ext.TaskMgr.stop(this.playTask);
            this.playTaskBuffer.cancel();
            this.playing = false;
            if(this.showPlayButton) {
                this.els.navPlay.removeClass('ux-carousel-playing');
            }
            this.fireEvent('pause');
        }
        return this;
    },

    clear: function() {
        this.els.slidesWrap.update('');
        this.slides = [];
        this.carouselSize = 0;
        this.pause();
        return this;
    },

    add: function(el, refresh) {
        var item = Ext.fly(el).appendTo(this.els.slidesWrap).wrap({
            cls: 'ux-carousel-slide'
        });
        item.setWidth(this.slideWidth + 'px').setHeight(this.slideHeight + 'px');
        this.slides.push(item);
        if(refresh) {
            this.refresh();
        }
        return this;
    },

    refresh: function() {
        this.carouselSize = this.slides.length;
        this.els.slidesWrap.setWidth((this.slideWidth * this.carouselSize) + 'px');
        if(this.carouselSize > 0) {
            if(!this.hideNavigation) this.els.navigation.show();
            this.activeSlide = 0;
            this.setSlide(0, true);
        }
        return this;
    },

    setSlide: function(index, initial) {
        if(!this.wrap && !this.slides[index]) {
            return;
        }
        else if(this.wrap) {
            if(index < 0) {
                index = this.carouselSize-1;
            }
            else if(index > this.carouselSize-1) {
                index = 0;
            }
        }
        if(!this.slides[index]) {
            return;
        }

        this.els.caption.update(this.slides[index].child(':first-child', true).title || '');
        var offset = index * this.slideWidth;
        if (!initial) {
            switch (this.transitionType) {
                case 'fade':
                    this.slides[index].setOpacity(0);
                    this.slides[this.activeSlide].stopFx(false).fadeOut({
                        duration: this.transitionDuration / 2,
                        callback: function(){
                            this.els.slidesWrap.setStyle('left', (-1 * offset) + 'px');
                            this.slides[this.activeSlide].setOpacity(1);
                            this.slides[index].fadeIn({
                                duration: this.transitionDuration / 2
                            });
                        },
                        scope: this
                    })
                    break;

                default:
                    var xNew = (-1 * offset) + this.els.container.getX();
                    this.els.slidesWrap.stopFx(false);
                    this.els.slidesWrap.shift({
                        duration: this.transitionDuration,
                        x: xNew,
                        easing: this.transitionEasing
                    });
                    break;
            }
        }
        else {
            this.els.slidesWrap.setStyle('left', '0');
        }

        this.activeSlide = index;
        this.updateNav();
        this.fireEvent('change', this.slides[index], index);
    },

    updateNav: function() {
        this.els.navPrev.removeClass('ux-carousel-nav-disabled');
        this.els.navNext.removeClass('ux-carousel-nav-disabled');
        if(!this.wrap) {
            if(this.activeSlide === 0) {
                this.els.navPrev.addClass('ux-carousel-nav-disabled');
            }
            if(this.activeSlide === this.carouselSize-1) {
                this.els.navNext.addClass('ux-carousel-nav-disabled');
            }
        }
    }
});
function embedCalendar(path, dt){
    return function() {
        var datePicker = new Ext.DatePicker({
            renderTo: 'calendar',
            xtype: 'panel',
            border: false,
            frame: false,
            width: 177,
            showToday: false,
            items: {
                xtype: 'datepicker'
            },
            listeners: {
                select: function(obj, date) {
                    dtStr = date.format("Y-m-d");
                    delim = '?';
                    if (path.indexOf('?') != -1) {
                        delim = '&';
                    }
                    location.href = path + delim + "start_date=" + dtStr;
                }
            }
        });
        if (dt) {
            dtObj = Date.parseDate(dt, "Y-m-d");
            datePicker.setValue(dtObj);
        }
    }
}
function handleChangeLocation(ctx) {
    return function() {
        Ext.get('chgloc').on('click', function(e){
            Ext.MessageBox.show({
                title: 'Change Location',
                msg: 'Enter your location in the text box below and click the <i>Change Location</i> button. (e.g., New York, NY or 10001)',
                cls: 'align-left',
                width: 400,
                buttons: {
                    ok:'Change Location',
                    cancel:'Cancel'
                },
                prompt: true,
                multiline: false,
                animEl: 'chgloc',
                icon: Ext.MessageBox.QUESTION,
                fn: function(buttonId, text) {
                    if (buttonId === 'ok') {
                        location.href = ctx + "/change_metro?cz=" + text;
                    }
                }
            });
            return false;
        });
    }
}
var loginWin;
function showLoginDlg() {
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';

    var form = new Ext.form.FormPanel({
        id: 'loginForm',
        waitMsgTarget: true,
        bodyStyle: 'padding:5px;',
        defaults: {
            anchor: '-40',
            allowBlank: false
        },
        keys: [{
            key: [10,13],
            fn: loginFormSubmit
        }],
        items: [{
            xtype: 'textfield',
            name: 'username',
            fieldLabel: 'Username'
        },{
            xtype: 'textfield',
            inputType: 'password',
            name: 'password',
            fieldLabel: 'Password'
        }]
    });

    if (!loginWin) {
        loginWin = new Ext.Window({
            title: 'Login',
            collapsible: false,
            maximizable: false,
            width: 350,
            height: 145,
            layout: 'fit',
            plain: true,
            bodyStyle: 'padding:5px;',
            buttonAlign: 'right',
            closeAction: 'hide',
            items: form,
            resizable: false,
            buttons: [{
                text: 'Login',
                listeners: {
                    click: loginFormSubmit
                }
            },{
                text: 'Cancel',
                listeners: {
                    click:  function() {
                        loginWin.hide();
                    }
                }
            }]
        });
    }
    loginWin.show();

    return false;
}
function loginFormSubmit() {
    var cmp = Ext.getCmp('loginForm');
    cmp.getForm().submit({
        url: '/ajax/login',
        waitMsg: 'Logging in',
        clientValidation: true,
        success: function(form, action) {
            if (action.result.success == true) {
                loginWin.hide();
                location.href = action.result.url;
            }
        },
        failure: function(form, action) {
            switch (action.failureType) {
                case Ext.form.Action.CLIENT_INVALID:
                    Ext.Msg.alert('Failure', 'Please enter a valid username and password.');
                    break;
                case Ext.form.Action.CONNECT_FAILURE:
                    Ext.Msg.alert('Failure', 'Server communication failed');
                    break;
                case Ext.form.Action.SERVER_INVALID:
                    if (action.result.validated == false) {
                        Ext.Msg.show({
                            title:'Validate E-mail Address?',
                            msg: 'Your e-mail address has not been validated. Would you like us to re-send the validation e-mail?',
                            buttons: Ext.Msg.YESNO,
                            fn: function(btn) {
                                if (btn == 'yes') {
                                    loginWin.hide();
                                    location.href = '/user/send_vkey';
                                }
                            },
                            icon: Ext.MessageBox.QUESTION
                        });
                    } else {
                        Ext.Msg.show({
                            title:'Invalid Username or Password',
                            msg: 'Please enter a valid username and password. If you forgot your password, we can change it. Would you like to change your password?',
                            buttons: Ext.Msg.YESNO,
                            fn: function(btn) {
                                if (btn == 'yes') {
                                    loginWin.hide();
                                    location.href = '/user/forgotpw';
                                }
                            },
                            icon: Ext.MessageBox.QUESTION
                        });
                    }
            }
        }
    });
}
var signupWin;
function showSignupDlg() {
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';

    var form = new Ext.form.FormPanel({
        id: 'registerForm',
        bodyStyle: 'padding:5px;',
        defaults: {
            anchor: '-40',
            allowBlank: false
        },
        keys: [{
            key: [10,13],
            fn: signupFormSubmit
        }],
        items: [{
            xtype: 'textfield',
            name: 'username',
            fieldLabel: 'Username'
        },{
            xtype: 'textfield',
            name: 'email',
            fieldLabel: 'Email'
        },{
            xtype: 'textfield',
            inputType: 'password',
            name: 'password1',
            id: 'password1',
            fieldLabel: 'Password'
        },{
            xtype: 'textfield',
            inputType: 'password',
            name: 'password2',
            id: 'password2',
            fieldLabel: 'Password (again)',
            vtype: 'password',
            initialPassField: 'password1'
        },{
            xtype: 'textfield',
            name: 'zip',
            fieldLabel: 'Zipcode'
        },{
            xtype: 'checkbox',
            name: 'tos',
            boxLabel: 'I agree to the Terms of Service'
        }]
    });

    if (!signupWin) {
        signupWin = new Ext.Window({
            title: 'Create Account',
            collapsible: false,
            maximizable: false,
            width: 425,
            height: 250,
            layout: 'fit',
            plain: true,
            bodyStyle: 'padding:5px;',
            buttonAlign: 'right',
            closeAction: 'hide',
            items: form,
            resizable: false,
            buttons: [{
                text: 'Signup',
                listeners: {
                    click:  signupFormSubmit
                }
            },{
                text: 'Cancel',
                listeners: {
                    click:  function() {
                        signupWin.hide();
                    }
                }
            }]
        });
    }
    signupWin.show();

    return false;
}
function signupFormSubmit() {
    var cmp = Ext.getCmp('registerForm');
    cmp.getForm().submit({
        url: '/ajax/signup',
        waitMsg: 'Creating account',
        clientValidation: true,
        success: function(form, action) {
            signupWin.hide();
            Ext.Msg.alert('Success', action.result.msg);
        },
        failure: function(form, action) {
            switch (action.failureType) {
                case Ext.form.Action.CLIENT_INVALID:
                    Ext.Msg.alert('Failure', 'Please fill all fields and try again.');
                    break;
                case Ext.form.Action.CONNECT_FAILURE:
                    Ext.Msg.alert('Failure', 'Server communication failed');
                    break;
                case Ext.form.Action.SERVER_INVALID:
                    Ext.Msg.alert('Failure', action.result.msg);
            }
        }
    });
}
var smsWin;
function showSMSDlg(itemType, itemId) {
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    var companyStore = new Ext.data.JsonStore({
        fields : ['name', 'value'],
        data   : [
        {
            name:'AT&T',
            value:'7'
        },
        {
            name:'Alltel',
            value:'1'
        },
        {
            name:'Boost Mobile',
            value:'2'
        },
        {
            name:'Cellular South',
            value:'3'
        },
        {
            name:'CellularOne',
            value:'4'
        },
        {
            name:'Centennial Wireless',
            value:'5'
        },
        {
            name:'Cincinnati Bell',
            value:'6'
        },
        {
            name:'Edge Wireless',
            value:'8'
        },
        {
            name:'Helio',
            value:'9'
        },
        {
            name:'Metro PCS',
            value:'10'
        },
        {
            name:'Nextel',
            value:'11'
        },
        {
            name:'nTelos',
            value:'12'
        },
        {
            name:'Qwest Wireless',
            value:'13'
        },
        {
            name:'SouthernLINC Wireless',
            value:'14'
        },
        {
            name:'Sprint PCS',
            value:'15'
        },
        {
            name:'SunCom',
            value:'16'
        },
        {
            name:'T-Mobile',
            value:'17'
        },
        {
            name:'U.S. Cellular',
            value:'18'
        },
        {
            name:'Unicel',
            value:'19'
        },
        {
            name:'Verizon Wireless',
            value:'20'
        },
        {
            name:'Virgin Mobile USA',
            value:'21'
        }
        ]
    });
    var form = new Ext.form.FormPanel({
        id: 'smsForm',
        bodyStyle: 'padding:5px;',
        defaults: {
            anchor: '-40',
            labelStyle: 'text-align:right;'
        },
        items: [{
            xtype: 'hidden',
            name: 'type',
            value: itemType
        },{
            xtype: 'hidden',
            name: 'id',
            value: itemId
        },{
            xtype: 'textfield',
            name: 'name',
            fieldLabel: 'Your Name',
            allowBlank: false
        },{
            xtype: 'textfield',
            name: 'email',
            fieldLabel: 'Email',
            allowBlank: false
        },{
            xtype: 'textfield',
            name: 'phone',
            fieldLabel: 'Phone Number'
        },{
            xtype: 'combo',
            width: '100px',
            mode: 'local',
            value: '',
            triggerAction: 'all',
            forceSelection: true,
            editable: false,
            typeAhead: true,
            name: 'company',
            hiddenName: 'company',
            displayField: 'name',
            valueField: 'value',
            fieldLabel: 'Mobile Company',
            store: companyStore
        }]
    });

    if (!smsWin) {
        smsWin = new Ext.Window({
            title: 'Send SMS',
            collapsible: false,
            maximizable: false,
            width: 425,
            height: 200,
            layout: 'fit',
            plain: true,
            bodyStyle: 'padding:5px;',
            buttonAlign: 'right',
            closeAction: 'hide',
            items: form,
            resizable: false,
            modal: true,
            buttons: [{
                text: 'Send',
                listeners: {
                    click:  function() {
                        var cmp = Ext.getCmp('smsForm');
                        cmp.getForm().submit({
                            url: '/ajax/send_sms',
                            waitMsg: 'Sending SMS',
                            clientValidation: true,
                            success: function(form, action) {
                                smsWin.hide();
                                Ext.MessageBox.alert('Success', action.result.msg);
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CLIENT_INVALID:
                                        Ext.Msg.alert('Failure', 'Please fill all fields and try again.');
                                        break;
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('Failure', 'Server communication failed');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('Failure', action.result.msg);
                                }
                            }
                        });
                    }
                }
            },{
                text: 'Cancel',
                listeners: {
                    click:  function() {
                        smsWin.hide();
                    }
                }
            }]
        });
    }
    smsWin.show();

    return false;
}
function handleSearch(path,apath,root){
    return function() {
        Ext.QuickTips.init();

        var ds = new Ext.data.JsonStore({
            proxy: new Ext.data.HttpProxy({
                url: apath
            }),
            root: root,
            fields: [
            {
                name: 'id',
                mapping: 'id'
            },
            {
                name: 'path',
                mapping: 'path'
            },
            {
                name: 'title',
                mapping: 'title'
            },
            {
                name: 'venue',
                mapping: 'venue'
            },
            {
                name: 'city',
                mapping: 'city'
            },
            {
                name: 'state',
                mapping: 'state'
            }
            ]
        });
        var resultTpl = new Ext.XTemplate(
            '<tpl for="."><div class="search-item">',
            '<b>{title}</b><br />',
            '{venue} in {city} {state}',
            '</div></tpl>',
            {
                compiled: true
            }
            );

        var p = new Ext.Panel({
            renderTo: 'search-box',
            layout: {
                type:'hbox',
                padding:'5',
                pack:'center',
                align:'middle'
            },
            autoWidth: true,
            bodyStyle: 'background-color:#E9F3FE;',
            height: 30,
            plain: true,
            frame: false,
            border: false,
            defaults:{
                margins:'0 5 0 0'
            },
            keys: [{
                key: [10,13],
                fn: function() {
                    var val = Ext.get("search").getValue();
                    if ((val) && (val != "")) {
                        location.href = path + '?' + Ext.urlEncode({
                            p:val
                        });
                    }
                }
            }],
            items:[{
                xtype:'displayfield',
                value:'Search: '
            },{
                id:'search',
                xtype: 'combo',
                mode: 'remote',
                store: ds,
                displayField:'title',
                typeAhead: false,
                loadingText: 'Searching...',
                width: 500,
                hideTrigger:true,
                tpl: resultTpl,
                itemSelector: 'div.search-item',
                listeners: {
                    'beforeselect': function(combo, record, index ) {
                        combo.collapse();
                        if (index == 0) {
                            var val = Ext.get("search").getValue();
                            if ((val) && (val != "")) {
                                location.href = path + '?' + Ext.urlEncode({
                                    p:val
                                });
                            }
                        } else {
                            location.href = record.data.path + "/" + root + "/" + record.data.id + ".html";
                        }
                        
                        return false;
                    }
                }
            },{
                xtype:'button',
                width: 75,
                text: 'Search',
                iconCls: 'search-btn',
                listeners: {
                    click:  function() {
                        var val = Ext.get("search").getValue();
                        if ((val) && (val != "")) {
                            location.href = path + '?' + Ext.urlEncode({
                                p:val
                            });
                        }
                    }
                }
            }]
        });
    };
}
