var profileApp = function(options){
    var make_offer = function(date, panel, form){
        var i = date.data;
        var l = panel.getLayout();
        var f = form.form;
        l.setActiveItem(1);
        f.loadRecord(date);
        var detailsTemplate = new Ext.XTemplate('<tpl for="."><tpl for="usercategory"><div class="date_description"><div style="width:90px;margin-right:10px;" class="description_item"><img src="{[ values.thumbnail ? values.thumbnail : profileJson.thumbnail ]}" class="photo" height="80" width="80"></div><div style="padding-left:0px" class="description_item"><h3>{title}</h3></tpl><p>Date Starts: {offer_time_start}<br/>Price: {current_price_description}</p></tpl></div><div class="clear"></div></div></tpl>');
        var detailsElement = form.getEl().child('.date_description', true);
        detailsTemplate.overwrite(detailsElement, i);
        var defaultPrice = i.advertisedprice;
        if (i.saletypeid === 2) {
            defaultPrice = i.agreedprice >= i.minimumprice ? i.agreedprice : i.minimumprice;
            f.findField('offervalue').minValue = defaultPrice;
        }
        if (i.nohaggle) {
            f.findField('offervalue').minValue = defaultPrice;
        }
        f.findField('offervalue').setValue(defaultPrice);
    };
    var confirm_offer_sent = function(panel){
        pApp.flash('Success', 'Your message has been sent.', panel.getEl().child('.offer_confirmation'));
        panel.getLayout().setActiveItem(0);
    };
    var stores = {
        profile_details: new Ext.data.JsonStore({
            url: '/user/listAsJSON/profile_details',
            method: 'POST',
            data: profileJson,
            fields: ['bday', 'birthdate', 'country', 'city', 'state', 'location', 'gender', 'firstname', 'lastname', 'interests', 'movies', 'music', 'rating', 'userid', 'viewcount', 'zipcode', 'description', 'profilename', 'location', 'siteuse', 'url1', 'url2', 'url3']
        }),
        profile_details_2: new Ext.data.SimpleStore({
            fields: ['gender', 'profilename', 'firstname', 'lastname', 'interests', 'movies', 'music', 'bday', 'siteuse', 'location', 'url1', 'url2', 'url3'],
            data: [[profileJson.gender, profileJson.profilename, profileJson.firstname, profileJson.lastname, profileJson.interests, profileJson.movies, profileJson.music, profileJson.bday, profileJson.siteuse, profileJson.location, profileJson.url1, profileJson.url2, profileJson.url3]]
        }),
        profile_photo: new Ext.data.JsonStore({
            url: '/user/listAsJSON/profile_photo',
            method: 'POST',
            data: profileJson.photos ? profileJson.photos : [],
            fields: ['userid', 'photoid', 'mainphoto', 'small', 'full', 'medium', 'description']
        }),
        profile_video: new Ext.data.JsonStore({
            url: '/user/listAsJSON/profile_video',
            method: 'POST',
            data: profileJson.videos ? profileJson.videos : [],
            fields: ['userid', 'videoid', 'site', 'watchvar', 'youtube_thumb', 'youtube_embed', 'description']
        }),
        profile_charity: new Ext.data.JsonStore({
            url: '/user/listAsJSON/profile_charity',
            method: 'POST',
            data: profileJson.charities ? profileJson.charities : [],
            fields: ['charityid', 'charityName', 'thumbnail', 'charity']
        }),
        profile_friend: new Ext.data.JsonStore({
            url: '/user/listAsJSON/profile_friend',
            method: 'POST',
            data: profileJson.friends ? profileJson.friends : [],
            fields: ['userid', 'friendid', 'friend']
        }),
        profile_comment: new Ext.data.JsonStore({
            url: '/user/listAsJSON/profile_comment',
            method: 'POST',
            data: profileJson.comments ? profileJson.comments : [],
            fields: ['userid', 'posterid', 'poster', 'dateposted', 'commenttext', 'commentid']
        }),
        profile_videoresponse: new Ext.data.JsonStore({
            url: '/user/listAsJSON/profile_videoresponse',
            method: 'POST',
            data: profileJson.videoresponses ? profileJson.videoresponses : [],
            fields: ['userid', 'videoresponseid', 'thumbnail', 'source', 'dateposted', 'posterid']
        }),
        profile_biography: new Ext.data.SimpleStore({
            fields: ['description'],
            data: [[profileJson.description]]
        }),
        date_wanted: new Ext.data.JsonStore({
            url: '/user/listAsJSON/date_wanted',
            method: 'POST',
            data: profileJson.dateswanted ? profileJson.dateswanted : [],
            fields: ['filetype', 'processed', 'source', 'categoryid', 'userid', 'usercategoryid', 'title', 'price', 'price_description', 'reserveprice', 'saletypeid', 'thumbnail', 'title', 'description', 'locationstring', 'original', 'status', 'charityid1', 'charityid2', 'charityid3', 'charityamount1', 'charityamount2', 'charityamount3']
        }),
        date_wanted_availability: new Ext.data.JsonStore({
            url: '/user/listAsJSON/date_wanted_availability',
            method: 'POST',
            data: profileJson.dateswanted ? profileJson.dateswanted : [],
            fields: ['advertisedprice', 'category', 'category_description', 'current_price_description', 'dateposted', 'dateid', 'sellerid', 'offer_time_end', 'offer_time_start', 'offertimestart', 'offertimeend', 'paymenttypeid', 'statusid', 'thumbnail', 'usercategory', 'usertitle']
        }),
        date_availability: new Ext.data.JsonStore({
            url: '/user/listAsJSON/date_availability',
            method: 'POST',
            data: profileJson.availabledates ? profileJson.availabledates : [],
            fields: ['advertisedprice', 'category', 'category_description', 'current_price_description', 'dateposted', 'dateid', 'sellerid', 'offer_time_end', 'offer_time_start', 'offertimestart', 'offertimeend', 'paymenttypeid', 'statusid', 'thumbnail', 'usercategory', 'usertitle'],
            listeners: {}
        }),
        date_category: new Ext.data.JsonStore({
            url: '/user/listAsJSON/datecategory',
            method: 'POST',
            data: profileJson.datecategories ? profileJson.datecategories : [],
            fields: ['filetype', 'processed', 'source', 'categoryid', 'userid', 'usercategoryid', 'title', 'price', 'price_description', 'reserveprice', 'saletypeid', 'thumbnail', 'title', 'description', 'locationstring', 'original', 'status', 'charityid1', 'charityid2', 'charityid3', 'charityamount1', 'charityamount2', 'charityamount3']
        })
    };
    var toolbars = {
        date_category_bottom_toolbar: new Ext.Toolbar({})
    };
    var templates = {
        profile_details: new Ext.XTemplate('<tpl for="."><div class="profile_details"><table class="highlight">', '<tr><td class="label">Name:</td><td>{profilename}</td></tr>', '<tr><td class="label">Location:</td><td>{location}</td></tr>', '<tr><td class="label">Gender:</td><td>{[ values.gender=="G" ? "Group" : values.gender=="M" ? "Male" : values.gender=="F" ? "Female" : ""]}</td></tr>', '<tr><td class="label">Birthday:</td><td>{bday}</td></tr>', '<tr><td class="label">Interests:</td><td>{interests}</td></tr>', '<tr><td class="label">Music:</td><td>{music}</td></tr>', '<tr><td class="label">Movies:</td><td>{movies}</td></tr>', '<tr><td class="label">Websites:</td>', '<td>', '<a href="/reddoor?source=/user/profile/{userid}&target={url1}">{[ values.url1 ? values.url1 : "" ]}</a><br/>', '<a href="/reddoor?source=/user/profile/{userid}&target={url2}">{[ values.url2 ? values.url2 : "" ]}</a><br/>', '<a href="/reddoor?source=/user/profile/{userid}&target={url3}">{[ values.url3 ? values.url3 : "" ]}</a><br/>', '</td></tr>', '</table></div></tpl>'),
        profile_photo: new Ext.XTemplate('<tpl for="."><div class="profile_photo">', '<img class="photo" src="/static/images/photos/small/{small}" />', '</div></tpl><div class="clear"></div>'),
        profile_video: new Ext.XTemplate('<tpl for="."><div class="profile_video">', '<img src="{youtube_thumb}" class="photo" /><br/><div class="profile_video_description">{description}</div>', '</div></tpl><div class="clear"></div>'),
        profile_friend: new Ext.XTemplate('<tpl for="."><div class="profile_friend">', '<div class="profile_friend_item"><tpl for="friend"><img class="photo" height="{[ values.thumbnail ? "" : "80" ]}" width="{[ values.thumbnail ? "" : "80" ]}" src="{[ values.thumbnail ? values.thumbnail : "/static/images/site/default-photo.jpg"]}"  /><a href="/user/profile/{userid}">{profilename}</a></tpl></div>', '<div class="clear"></div>', '</div></tpl><div class="clear"></div>'),
        profile_comment: new Ext.XTemplate('<tpl for="."><div class="profile_comment {[ xindex%2==0 ? "odd" : "even" ]}">', '<div class="profile_comment_item poster-thumbnail"><tpl for="poster"><img class="photo" height="{[ values.thumbnail ? "" : "60" ]}" width="{[ values.thumbnail ? "" : "60" ]}" src="{[ values.thumbnail ? values.thumbnail : "/static/images/site/default-photo.jpg"]}"  /></tpl></div>', '<div class="profile_comment_item commenttext">{commenttext}</div>', '<div class="clear postedby">Posted by <a href="/user/profile/{posterid}"><tpl for="poster">{profilename}</tpl></a> on {dateposted}</div><div class="clear"></div>', '</div></tpl>'),
        profile_videoresponse: new Ext.XTemplate('<tpl for="."><div class="profile_videoresponse">', '<img src="{thumbnail}" height="60" width="80" class="photo" />', '</div></tpl>'),
        profile_videoresponse_show: new Ext.XTemplate('<tpl for=".">', '<object type="application/x-shockwave-flash" width="400" height="350" wmode="transparent" data="/static/objects/flvplayer.swf?file={source}&autoStart=true">', '<param name="movie" value="/static/objects/flvplayer.swf?file={source}&autoStart=true" />', '<param name="wmode" value="transparent" />', '</object></tpl>'),
        profile_biography: new Ext.XTemplate('<tpl for="."><div class="profile_biography"><p>{description}</p></div></tpl>'),
        profile_charity: new Ext.XTemplate('<tpl for="."><div class="profile_charity">', '<div class="charity_photo profile_charity_item"><a href="/charity/view/{charityid}"><tpl for="charity"><img src="{photo1}"></tpl></a></div>', '</div></tpl><div class="clear"></div>'),
        date_availability: new Ext.XTemplate('<tpl for="."><div class="date_availability {[ xindex%2==0 ? "odd" : "even" ]}">', '<div class="date_availability_item date_availability_details">', '<h3>{usertitle}</h3><p>Date starts on: {offer_time_start}</p><p>{current_price_description}</p>', '</div><div class="clear"></div>', '</div></tpl>'),
        date_wanted: new Ext.XTemplate('<tpl for="."><div class="date_wanted {[ xindex%2==0 ? "odd" : "even"]}">', '<div class="date_wanted_item date_wanted_photo"><img class="photo date_wanted_processed_{processed} date_wanted_filetype_{filetype}" onClick="pApp.dateWantedMedia(\{filetype:{filetype},usercategoryid:{usercategoryid},source:\'{source}\' \})" src="{[ values.thumbnail ? values.thumbnail : profileJson.thumbnail ]}" class="photo"/></div>', '<div class="date_wanted_item date_wanted_details"><h3>{title}</h3><h4>{price_description}</h4><p>{description}</p></div><div class="clear"></div>', '<div id="date_wanted_usermenu" style="margin-top:8px" class="right"><a onClick="pApp.checkWantedAvailability(\{usercategoryid:{usercategoryid}\})">Further Info</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a href="pApp.viewFeedback({usercategoryid})">Buyer\'s Feedback</a></div><div class="clear"></div>', '</div></tpl></div>'),
        date_category: new Ext.XTemplate('<tpl for="."><div class="date_category {[ xindex%2==0 ? "odd" : "even"]}">', '<div class="date_category_item date_category_photo"><img class="photo date_category_processed_{processed} date_category_filetype_{filetype}" onClick="pApp.dateOfferedMedia(\{filetype:{filetype},usercategoryid:{usercategoryid},source:\'{source}\' \})" src="{[ values.thumbnail ? values.thumbnail : profileJson.thumbnail ]}" class="photo" /></div>', '<div class="date_category_item date_category_details"><h3>{title}</h3><h4>{price_description}</h4><p>{description}</p><p>Location: {locationstring}</p></div><div class="clear"></div>', '<div style="margin-top:8px" class="right date_category_usermenu"><a onClick="pApp.checkAvailability(\{usercategoryid:{usercategoryid}\})">Request Date</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a onClick="pApp.checkAvailability(\{usercategoryid:{usercategoryid}\})">Further Info</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a href="pApp.viewFeedback({usercategoryid})">Buyer\'s Feedback</a></div><div class="clear"></div>', '</div></tpl></div>')
    };
    var views = {
        profile_details_view: new Ext.DataView({
            id: 'profile_details_view',
            tpl: templates.profile_details,
            store: stores.profile_details_2,
            itemSelector: 'div.profile_details__',
            emptyText: '<div class="emptyText">This member has not entered any details about themselves.</div>',
            selectedClass: 'selected-item',
            overClass: 'over-item',
            deferEmptyText: false
        }),
        profile_photo_view: new Ext.DataView({
            id: 'profile_photo_view',
            tpl: templates.profile_photo,
            store: stores.profile_photo,
            itemSelector: 'div.profile_photo',
            emptyText: '<div class="emptyText">This member does not have any photos.</div>',
            selectedClass: 'selected-item',
            overClass: 'over-item',
            singleSelect: true,
            deferEmptyText: false,
            listeners: {
                click: function(thisView, thisIndex, thisNode, eObject){
                    if (thisView.el.hasClass('editable')) {
                        return false;
                    }
                    var record = thisView.getRecord(thisNode);
                    var mainphoto = Ext.get('mainphoto');
                    mainphoto.dom.src = record.data.full;
                }
            }
        }),
        profile_comment_view: new Ext.DataView({
            id: 'profile_comment_view',
            tpl: templates.profile_comment,
            store: stores.profile_comment,
            itemSelector: 'div.profile_comment',
            emptyText: '<div class="emptyText">This member does not have any comments.</div>',
            selectedClass: 'selected-item',
            overClass: 'over-item',
            singleSelect: true,
            deferEmptyText: false
        }),
        profile_friend_view: new Ext.DataView({
            id: 'profile_friend_view',
            tpl: templates.profile_friend,
            store: stores.profile_friend,
            itemSelector: 'div.profile_friend',
            emptyText: '<div class="emptyText">This member does not have any friends posted.</div>',
            selectedClass: 'selected-item',
            overClass: 'over-item',
            singleSelect: true,
            deferEmptyText: false,
            listeners: {
                click: function(thisView, thisIndex, thisNode, eObject){
                    if (thisView.el.hasClass('editable')) {
                        return false;
                    }
                    var record = thisView.getRecord(thisNode);
                    window.location = '/user/profile/' + record.data.friendid;
                }
            }
        }),
        profile_videoresponse_view: new Ext.DataView({
            id: 'profile_videoresponse_view',
            tpl: templates.profile_videoresponse,
            store: stores.profile_videoresponse,
            itemSelector: 'div.profile_videoresponse',
            emptyText: '<div class="emptyText">This member does not have any video responses.</div>',
            selectedClass: 'selected-item',
            overClass: 'over-item',
            singleSelect: true,
            deferEmptyText: false,
            listeners: {
                click: function(thisView, thisIndex, thisNode, eObject){
                    if (thisView.el.hasClass('editable')) {
                        return false;
                    }
                    var record = thisView.getRecord(thisNode);
                    pApp.showComponent('profile_videoresponse_show');
                    var pvc = Ext.get('profile_videoresponse_container');
                    if (pvc.child('object')) {
                        pvc.child('object').remove();
                    }
                    pvc.insertFirst({
                        tag: 'object',
                        width: 400,
                        height: 350,
                        wmode: 'transparent',
                        data: '/static/objects/flvplayer.swf?file=' + record.data.source + '&autoStart=true',
                        children: [{
                            tag: 'param',
                            name: 'movie',
                            value: '/static/objects/flvplayer.swf?file=' + record.data.source + '&autoStart=true'
                        }, {
                            tag: 'param',
                            name: 'wmode',
                            value: 'transparent'
                        }, {
                            tag: 'embed',
                            wmode: 'transparent',
                            height: '350',
                            src: '/static/objects/flvplayer.swf?file=' + record.data.source + '&autoStart=true',
                            type: 'application/x-shockwave-flash',
                            width: '400'
                        }]
                    });
                }
            }
        }),
        profile_video_view: new Ext.DataView({
            id: 'profile_video_view',
            tpl: templates.profile_video,
            store: stores.profile_video,
            itemSelector: 'div.profile_video',
            selectedClass: 'selected-item',
            overClass: 'over-item',
            singleSelect: true,
            emptyText: '<div class="emptyText">This member does not have any videos.</div>',
            deferEmptyText: false,
            listeners: {
                click: function(thisView, thisIndex, thisNode, eObject){
                    if (thisView.el.hasClass('editable')) {
                        return false;
                    }
                    var record = thisView.getRecord(thisNode);
                    pApp.showComponent('profile_video_show');
                    var pvc = Ext.get('profile_video_container');
                    if (pvc.child('object')) {
                        pvc.child('object').remove();
                    }
                    pvc.insertFirst({
                        tag: 'object',
                        width: '425',
                        height: '355',
                        children: [{
                            tag: 'param',
                            name: 'movie',
                            value: 'http://www.youtube.com/v/' + record.data.watchvar + '&hl=en'
                        }, {
                            tag: 'param',
                            name: 'wmode',
                            value: 'transparent'
                        }, {
                            tag: 'embed',
                            wmode: 'transparent',
                            height: '355',
                            src: 'http://www.youtube.com/v/' + record.data.watchvar,
                            type: 'application/x-shockwave-flash',
                            width: '425'
                        }]
                    });
                }
            }
        }),
        profile_biography_view: new Ext.DataView({
            id: 'profile_biography_view',
            tpl: templates.profile_biography,
            store: stores.profile_biography,
            itemSelector: 'div.profile_biography',
            selectedClass: 'selected-item',
            emptyText: '<div class="emptyText">This member has not entered a biography.</div>',
            overClass: 'over-item',
            deferEmptyText: false
        }),
        profile_charity_view: new Ext.DataView({
            id: 'profile_charity_view',
            tpl: templates.profile_charity,
            store: stores.profile_charity,
            itemSelector: 'div.profile_charity',
            emptyText: '<div class="emptyText">This member does not have any favorite nonprofits.</div>',
            selectedClass: 'selected-item',
            overClass: 'over-item',
            singleSelect: true,
            deferEmptyText: false,
            listeners: {
                click: function(thisView, thisIndex, thisNode, eObject){
                    if (thisView.el.hasClass('editable')) {
                        return false;
                    }
                    var record = thisView.getRecord(thisNode);
                    window.location = '/charity/view/' + record.data.charityid;
                }
            }
        }),
        date_category_view: new Ext.DataView({
            id: 'date_category_view',
            tpl: templates.date_category,
            store: stores.date_category,
            itemSelector: 'div.date_category',
            emptyText: '<div class="emptyText">This member does not have any types of dates to buy or sell.</div>',
            selectedClass: 'selected-item',
            overClass: 'over-item',
            singleSelect: true,
            deferEmptyText: false
        }),
        date_availability_view: new Ext.DataView({
            id: 'date_availability_view',
            tpl: templates.date_availability,
            store: stores.date_availability,
            itemSelector: 'div.date_availability',
            emptyText: '<div class="emptyText">This member does not have dates to buy or sell.</div>',
            selectedClass: 'selected-item',
            overClass: 'over-item',
            singleSelect: true,
            deferEmptyText: false
        }),
        date_wanted_view: new Ext.DataView({
            id: 'date_wanted_view',
            tpl: templates.date_wanted,
            store: stores.date_wanted,
            itemSelector: 'div.date_wanted',
            emptyText: '<div class="emptyText">This member does not have any dates wanted.</div>',
            selectedClass: 'selected-item',
            overClass: 'over-item',
            singleSelect: true,
            deferEmptyText: false
        })
    };
    var forms = {
        date_availability: {
            id: 'offer_form',
            url: '/date/make_offer',
            title: 'Make an offer',
            xtype: 'form',
            frame: true,
            height: 330,
            labelAlign: 'top',
            labelSeparator: '',
            defaults: {
                msgTarget: 'side',
                width: 350
            },
            items: [{
                xtype: '',
                html: '<div style="padding:5px 0px;margin-bottom:10px;font-size:1.1em;" class="date_description" id="date_offer_description"></div>'
            }, {
                xtype: 'hidden',
                name: 'dateid'
            }, {
                xtype: 'numberfield',
                name: 'offervalue',
                fieldLabel: 'What is your offer or maximum bid?',
                allowBlank: false
            }, {
                name: 'message',
                xtype: 'textarea',
                fieldLabel: 'You may enter a short message for the seller.'
            }],
            buttons: [{
                text: 'Cancel',
                iconCls: 'btn-reset',
                handler: function(){
                    var p = Ext.getCmp('date_availability_panel');
                    var g = p.items.first();
                    var l = p.getLayout();
                    l.setActiveItem(0);
                }
            }, {
                text: 'Send Offer',
                iconCls: 'btn-apply',
                handler: function(){
                    var form = this.ownerCt.form;
                    form.submit({
                        waitMsg: 'Saving data...',
                        success: function(a, b){
                            confirm_offer_sent(Ext.getCmp('date_availability_panel'));
                        },
                        failure: function(a, b){
                        }
                    });
                }
            }]
        },
        profile_videoresponse_editor: new Ext.form.FormPanel({
            id: 'profile_videoresponse_editor',
            url: '/user/post_video_response',
            method: 'POST',
            frame: true,
            labelAlign: 'top',
            fileUpload: true,
            items: [{
                xtype: '',
                html: '<p>You may post a short video in response to this member. </p>'
            }, {
                xtype: 'hidden',
                name: 'userid',
                value: profileJson.userid
            }, {
                fieldLabel: 'Upload Video File (only mpg, avi, or wmv formats are viewable, max size 20 MB)',
                xtype: 'textfield',
                inputType: 'file',
                allowBlank: false,
                width: 375,
                name: 'videoupload'
            }, {
                width: 375,
                xtype: 'checkbox',
                inputValue: 1,
                name: 'agreement',
                hideLabel: true,
                boxLabel: 'I certify that I have the right to distribute this video, and that it abides by the standards of the Buyadate.org <a href="/terms">Terms of Use</a> and <a href="/privacy">Privacy Policy</a>.'
            }],
            buttons: [{
                iconCls: 'btn-reset',
                text: 'Cancel',
                handler: function(){
                    pApp.showComponent('profile_videoresponse_panel');
                }
            }, {
                iconCls: 'btn-apply',
                text: 'Post Response',
                handler: function(){
                    var values = this.ownerCt.form.getValues();
                    if (!this.ownerCt.form.findField("agreement").checked) {
                        alert('You must check the box ceritfying that you have the right to distribute this video.');
                        return false;
                    }
                    this.ownerCt.form.submit({
                        waitMsg: 'Uploading Video Response...This may take several minutes.',
                        success: function(a, b){
                            pApp.refreshView('profile_videoresponse_panel', 'profile_videoresponse_view');
                        },
                        failure: function(a, b){
                            if (b.result && b.result.errors) {
                                if (b.result.errors.message) {
                                    alert(b.result.errors.message);
                                    return false;
                                }
                                if (b.result.errors.forceLogin) {
                                    window.location = '/login?required=true&path=/user/profile/' + profileJson.userid;
                                    return false;
                                }
                            }
                        }
                    });
                }
            }]
        }),
        profile_comment_editor: new Ext.form.FormPanel({
            id: 'profile_comment_editor',
            url: '/user/post_comment',
            method: 'POST',
            frame: true,
            labelAlign: 'top',
            defaults: {
                msgTarget: 'side'
            },
            items: [{
                xtype: 'hidden',
                name: 'userid',
                value: profileJson.userid
            }, {
                xtype: 'textarea',
                width: 400,
                height: 150,
                fieldLabel: 'Post a Comment',
                name: 'commenttext'
            }],
            buttons: [{
                iconCls: 'btn-reset',
                text: 'Cancel',
                handler: function(){
                    pApp.showComponent('profile_comment_panel');
                }
            }, {
                iconCls: 'btn-apply',
                text: 'Post Comment',
                handler: function(){
                    this.ownerCt.form.submit({
                        waitMsg: 'Posting Comment...',
                        success: function(a, b){
                            pApp.refreshView('profile_comment_panel', 'profile_comment_view');
                        },
                        failure: function(a, b){
                            if (b.result.errors.forceLogin) {
                                window.location = '/login?required=true&path=/user/profile/' + profileJson.userid;
                                return false;
                            }
                        }
                    });
                }
            }]
        })
    };
    var grids = {
        date_availability: {
            title: 'Date Availability',
            id: 'date_availability_grid',
            xtype: 'grid',
            height: 330,
            stripeRows: true,
            frame: true,
            viewConfig: {
                forceFit: true,
                deferEmptyText: false,
                emptyText: 'This member does not have any availability.  You can <a href="/message/create/?recipient=' + profileJson.userid + '">ask this member a question</a>, or <a href="/message/create/?recipient=' + profileJson.userid + '">send them a message</a>.'
            },
            cm: new Ext.grid.ColumnModel([{
                header: "Start Date",
                dataIndex: "offer_time_start"
            }, {
                header: "Price",
                dataIndex: "current_price_description"
            }]),
            ds: stores.date_availability,
            sm: new Ext.grid.RowSelectionModel({
                singleSelect: true
            }),
            tbar: [{
                xtype: 'datefield',
                format: 'Y-m-d',
                width: 115,
                name: 'date_availability_search',
                id: 'date_availability_search',
                emptyText: 'Search by date'
            }, {
                xtype: 'button',
                iconCls: 'btn-reset',
                text: 'Clear',
                handler: function(){
                    Ext.getCmp('date_availability_search').clearValue();
                }
            }, {
                xtype: 'button',
                iconCls: 'btn-forward',
                text: 'Back',
                handler: function(){
                    pApp.showComponent('date_category_panel');
                }
            }],
            listeners: {
                rowdblclick: function(thisGrid, thisRow){
                    make_offer(thisGrid.getStore().getAt(thisRow), Ext.getCmp('date_availability_panel'), Ext.getCmp('offer_form'));
                }
            },
            bbar: [{
                iconCls: 'btn-forward',
                text: 'Request selected date.',
                handler: function(){
                    var p = Ext.getCmp('date_availability_panel');
                    var g = p.items.first();
                    var l = p.getLayout();
                    var f = Ext.getCmp('offer_form');
                    if (g.getSelectionModel().getSelections().length >= 1) {
                        var r = g.getSelectionModel().getSelections()[0];
                        make_offer(r, p, f);
                    }
                }
            }]
        }
    };
    var panels = {
        profile_details_panel: new Ext.Panel({
            bodyStyle: 'padding-top:10px;',
            tbar: new Ext.Toolbar({
                hidden: true
            }),
            id: 'profile_details_panel',
            layout: 'card',
            activeItem: 0,
            items: [views.profile_details_view]
        }),
        profile_photo_panel: new Ext.Panel({
            bodyStyle: 'padding-top:10px;',
            tbar: new Ext.Toolbar({
                hidden: true
            }),
            id: 'profile_photo_panel',
            layout: 'card',
            activeItem: 0,
            items: [views.profile_photo_view]
        }),
        profile_comment_panel: new Ext.Panel({
            bbar: new Ext.Toolbar({
                hidden: true
            }),
            bodyStyle: 'padding-top:10px;',
            tbar: new Ext.Toolbar({
                hidden: true
            }),
            id: 'profile_comment_panel',
            layout: 'card',
            activeItem: 0,
            items: [views.profile_comment_view]
        }),
        profile_friend_panel: new Ext.Panel({
            bodyStyle: 'padding-top:10px;',
            tbar: new Ext.Toolbar({
                hidden: true
            }),
            id: 'profile_friend_panel',
            layout: 'card',
            activeItem: 0,
            items: [views.profile_friend_view]
        }),
        profile_video_panel: new Ext.Panel({
            bodyStyle: 'padding-top:10px;',
            tbar: new Ext.Toolbar({
                hidden: true
            }),
            id: 'profile_video_panel',
            layout: 'card',
            activeItem: 0,
            items: [views.profile_video_view]
        }),
        profile_videoresponse_panel: new Ext.Panel({
            bodyStyle: 'padding-top:10px;',
            tbar: new Ext.Toolbar({
                hidden: true
            }),
            id: 'profile_videoresponse_panel',
            layout: 'card',
            activeItem: 0,
            items: [views.profile_videoresponse_view]
        }),
        profile_biography_panel: new Ext.Panel({
            bodyStyle: 'padding-top:10px;',
            tbar: new Ext.Toolbar({
                hidden: true
            }),
            id: 'profile_biography_panel',
            layout: 'card',
            activeItem: 0,
            items: [views.profile_biography_view]
        }),
        profile_charity_panel: new Ext.Panel({
            bodyStyle: 'padding-top:10px;',
            tbar: new Ext.Toolbar({
                hidden: true
            }),
            id: 'profile_charity_panel',
            layout: 'card',
            activeItem: 0,
            items: [views.profile_charity_view]
        }),
        date_wanted_panel: new Ext.Panel({
            bodyStyle: 'padding-top:10px;',
            tbar: new Ext.Toolbar({
                hidden: true
            }),
            id: 'date_wanted_panel',
            layout: 'card',
            activeItem: 0,
            items: [views.date_wanted_view]
        }),
        date_category_panel: new Ext.Panel({
            bbar: new Ext.Toolbar({
                hidden: true
            }),
            bodyStyle: 'padding-top:10px;',
            tbar: new Ext.Toolbar({
                hidden: true
            }),
            id: 'date_category_panel',
            layout: 'card',
            activeItem: 0,
            items: [views.date_category_view]
        }),
        date_wanted_availability_panel: new Ext.Panel({
            id: 'date_wanted_availability_panel',
            layout: 'card',
            activeItem: 0,
            bodyStyle: 'padding-top:10px;',
            items: [{
                title: 'Date Wanted Availability',
                id: 'date_wanted_availability_grid',
                xtype: 'grid',
                height: 330,
                stripeRows: true,
                frame: true,
                viewConfig: {
                    forceFit: true
                },
                cm: new Ext.grid.ColumnModel([{
                    header: "Start Date",
                    dataIndex: "offer_time_start"
                }, {
                    header: "Willing to pay",
                    dataIndex: "advertisedprice",
                    renderer: function(a){
                        return '$' + a;
                    }
                }]),
                ds: stores.date_wanted_availability,
                sm: new Ext.grid.RowSelectionModel({
                    singleSelect: true
                }),
                tbar: [{
                    xtype: 'datefield',
                    format: 'Y-m-d',
                    width: 115,
                    name: 'date_wanted_availability_search',
                    id: 'date_wanted_availability_search',
                    emptyText: 'Search by date'
                }, {
                    xtype: 'button',
                    iconCls: 'btn-reset',
                    text: 'Clear',
                    handler: function(){
                        Ext.getCmp('date_wanted_availability_search').setValue('');
                    }
                }, {
                    xtype: 'button',
                    iconCls: 'btn-forward',
                    text: 'Back',
                    handler: function(){
                        pApp.showComponent('date_wanted_panel');
                    }
                }],
                bbar: [{
                    iconCls: 'btn-forward',
                    text: 'Make an offer for selected date.',
                    handler: function(){
                        var p = Ext.getCmp('date_wanted_availability_panel');
                        var g = p.items.first();
                        var l = p.getLayout();
                        var f = Ext.getCmp('datewanted_offer_form').form;
                        if (g.getSelectionModel().getSelections().length >= 1) {
                            var r = g.getSelectionModel().getSelections()[0];
                            l.setActiveItem(1);
                            f.loadRecord(r);
                            Ext.get('date_wanted_offer_description').dom.innerHTML = 'You are about to make an offer on a date.  The price is ' + r.data.current_price_description;
                            if (r.data.saletypeid == 1) {
                                f.findField('offervalue').setValue(r.data.advertisedprice);
                            }
                        }
                    }
                }]
            }, {
                id: 'datewanted_offer_form',
                url: '/date/make_offer',
                title: 'Make an offer',
                xtype: 'form',
                frame: true,
                height: 330,
                labelAlign: 'top',
                labelSeparator: '',
                defaults: {
                    msgTarget: 'side',
                    width: 300
                },
                items: [{
                    xtype: '',
                    html: '<div style="padding:5px 0px;margin-bottom:10px;font-size:1.1em;" id="date_wanted_offer_description"></div>'
                }, {
                    xtype: 'numberfield',
                    name: 'offervalue',
                    fieldLabel: 'What price are you offering?',
                    allowBlank: false
                }, {
                    xtype: 'textarea',
                    fieldLabel: 'You may enter a short message for the seller.'
                }],
                buttons: [{
                    text: 'Cancel',
                    iconCls: 'btn-reset',
                    handler: function(){
                        var p = Ext.getCmp('date_wanted_availability_panel');
                        var g = p.items.first();
                        var l = p.getLayout();
                        l.setActiveItem(0);
                    }
                }, {
                    text: 'Send Offer',
                    iconCls: 'btn-apply',
                    handler: function(){
                        var form = this.ownerCt.form;
                        form.submit({
                            waitMsg: 'Saving data...',
                            success: function(a, b){
                                confirm_offer('date_wanted_confirmation');
                            },
                            failure: function(a, b){
                            }
                        });
                    }
                }]
            }]
        }),
        date_availability_panel: new Ext.Panel({
            id: 'date_availability_panel',
            layout: 'card',
            activeItem: 0,
            bodyStyle: 'padding-top:10px;',
            items: [grids.date_availability, forms.date_availability, {
                xtype: 'panel',
                ctCls: 'offer_confirmation',
                items: [{
                    xtype: ''
                }]
            }]
        })
    };
    var checkWantedAvailability = function(args){
        var panel = Ext.getCmp('date_wanted_availability_panel');
        var grid = panel.items.first();
        var query = stores.date_wanted.query('usercategoryid', args.usercategoryid);
        if (query.first().data.title) {
            grid.setTitle(query.first().data.title);
        }
        pApp.showComponent(panel.id);
        grid.getStore().load({
            params: {
                usercategoryid: args.usercategoryid
            }
        });
    };
    var checkAvailability = function(args){
        var panel = Ext.getCmp('date_availability_panel');
        var grid = panel.items.first();
        var query = stores.date_category.query('usercategoryid', args.usercategoryid);
        if (query.first().data.title) {
            grid.setTitle(query.first().data.title);
        }
        pApp.showComponent(panel.id);
        grid.getStore().load({
            params: {
                userid: profileJson.userid,
                usercategoryid: args.usercategoryid
            }
        });
    };
    var dateOfferedMedia = function(args){
        pApp.showComponent('date_category_media_show');
        var pvc = Ext.get('date_category_media_container');
		if(args.filetype == 1) {
		}
        if (args.filetype == 2) {
            if (pvc.child('object')) {
                pvc.child('object').remove();
            }
            pvc.insertFirst({
                tag: 'object',
                width: 400,
                height: 350,
                wmode: 'transparent',
                data: '/static/objects/flvplayer.swf?file=' + args.source + '&autoStart=true',
                children: [{
                    tag: 'param',
                    name: 'movie',
                    value: '/static/objects/flvplayer.swf?file=' + args.source + '&autoStart=true'
                }, {
                    tag: 'param',
                    name: 'wmode',
                    value: 'transparent'
                }, {
                    tag: 'embed',
                    wmode: 'transparent',
                    height: '400',
                    src: '/static/objects/flvplayer.swf?file=' + args.source + '&autoStart=true',
                    type: 'application/x-shockwave-flash',
                    width: '350'
                }]
            });
        }
    };
    var msgCt;
    function createBox(t, s){
        return ['<div class="msg">', '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>', '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>', '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>', '</div>'].join('');
    }
    var flash = function(title, format, frame){
        if (!msgCt) {
            msgCt = Ext.DomHelper.insertFirst(frame ? frame : document.body, {
                id: 'msg-div'
            }, true);
        }
        msgCt.alignTo(frame ? frame : document.body, 't-t');
        var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
        var m = Ext.DomHelper.append(msgCt, {
            html: createBox(title, s)
        }, true);
        m.slideIn('t').pause(2).ghost("t", {
            remove: true
        });
    };
    var dateWantedMedia = function(args){
        pApp.showComponent('date_wanted_media_show');
        var pvc = Ext.get('date_wanted_media_container');
        if (args.filetype == 2) {
            if (pvc.child('object')) {
                pvc.child('object').remove();
            }
            pvc.insertFirst({
                tag: 'object',
                width: 360,
                height: 315,
                wmode: 'transparent',
                data: '/static/objects/flvplayer.swf?file=' + args.source + '&autoStart=true',
                children: [{
                    tag: 'param',
                    name: 'movie',
                    value: '/static/objects/flvplayer.swf?file=' + args.source + '&autoStart=true'
                }, {
                    tag: 'param',
                    name: 'wmode',
                    value: 'transparent'
                }, {
                    tag: 'embed',
                    wmode: 'transparent',
                    height: '315',
                    src: '/static/objects/flvplayer.swf?file=' + args.source + '&autoStart=true',
                    type: 'application/x-shockwave-flash',
                    width: '360'
                }]
            });
        }
    };
    return {
        stores: stores,
        profile: profileJson,
        refreshView: function(panelid, viewid){
            this.showComponent(panelid);
            Ext.getCmp(viewid).store.load({
                params: {
                    userid: profileJson.userid
                }
            });
        },
        flash: flash,
        checkAvailability: checkAvailability,
        checkWantedAvailability: checkWantedAvailability,
        dateOfferedMedia: dateOfferedMedia,
        dateWantedMedia: dateWantedMedia,
        showComponent: function(component_id){
            var cEl = Ext.get(Ext.query('div#' + component_id + '.component')[0]);
            var cmp = Ext.getCmp(component_id);
            if (cmp && cmp.rendered) {
                cmp.show();
            }
            cEl.radioClass('active');
            if (cmp && !cmp.rendered) {
                cmp.render(component_id);
                cmp.show();
            }
            return cmp;
        },
        init: function(){
            Ext.QuickTips.init();
            var activeComponents = Ext.query('div.active.component');
            for (var i = 0; i < activeComponents.length; i++) {
                var component_id = activeComponents[i].id;
                var component = Ext.getCmp(component_id);
                if (component) {
                    component.render(component_id);
                }
            }
        }
    };
};

