Ext.namespace('PBS.catalog');

PBS.catalog.SearchFilter = new function() {
};

PBS.catalog.SearchFilter.restore_configuration = function() {
    //var config = Ext.urlDecode(Ext.state.Manager.get('catalog_state'));
    // First try to restore state from the cookie.
    //if(!this.compare_configuration(config)) {
        // If that doesn't work, try it from the URL hash.
        config = Ext.urlDecode(document.location.hash.substring(1));
        this.compare_configuration(config);
    //}
};

PBS.catalog.SearchFilter.compare_configuration = function(old) {
    if(typeof(old.p) == 'undefined') {
        return false;
    }

    var reload_courses = false;
    var reload_orgs = false;

    var force_int_list = function(list) {
        for(var i=0; i<list.length; i++) {
            list[i] = parseInt(list[i]);
        }
        return list;
    };
    var equivalent_list = function(old_list, new_list) {
        if(old_list.length != new_list.length) {
            return true;
        }
        for(var i=0; i<old_list.length; i++) {
            if(new_list.indexOf(old_list[i]) == -1) {
                return true;
            }
        }
        return false;
    };

    var fix_undefined = function(val) {
        if(val == 'undefined') {
            return null;
        }
        return val;
    };

    // TODO: this fixes a bug in Ext.url(D)encode
    old.s = fix_undefined(old.s);
    old.p = fix_undefined(old.p);
    old.n = fix_undefined(old.n);
    old.q = fix_undefined(old.q);
    old.l = fix_undefined(old.l);
    old.sa = fix_undefined(old.sa);
    old.gb = fix_undefined(old.gb);

    old.s = parseInt(old.s || 0);
    old.p = parseInt(old.p || 1);
    old.n = parseInt(old.n || 10);
    old.q = old.q || "";
    old.l = parseInt(old.l || 0);
    old.sa = old.sa || [];
    old.gb = old.gb || [];
    if(typeof(old.sa) != "object") old.sa = [old.sa];
    if(typeof(old.gb) != "object") old.gb = [old.gb];
    old.sa = force_int_list(old.sa);
    old.gb = force_int_list(old.gb);

    if(old.q != this.config.q) reload_courses = true;
    else if(old.p != this.config.p) reload_courses = true;
    else if(old.n != this.config.n) reload_courses = true;
    else if(old.s != this.config.s) reload_courses = true;
    else if(equivalent_list(old.sa, this.config.sa)) reload_courses = true;
    else if(equivalent_list(old.gb, this.config.gb)) reload_courses = true;

    if(old.l != this.config.l) reload_orgs = true;

    this.config = old;
    this.store_configuration();

    if(reload_orgs) {
        this.get_organizations_data(true);
    }
    else if(reload_courses) {
        this.get_catalog_data();
    }
    return true;
};

PBS.catalog.SearchFilter.store_configuration = function(historic) {
    var config = Ext.urlEncode(this.config);
    // Store the configuration in the cookie (for Firefox and Safari)
    //Ext.state.Manager.set('catalog_state', config);

    // Also store the state in the URL hash, for bookmarking and IE.
    document.location.replace('#' + config);
};

PBS.catalog.SearchFilter.setup = function() {
    // IDs are metadata constants
    this.filters = {
        'sa': [
            {id: 5, name: 'Instructional Strategy'},
            {id: 4, name: 'Instructional Technology'},
            {id: 1, name: 'Math'},
            {id: 3, name: 'Reading/Language Arts'},
            {id: 2, name: 'Science'}
        ],
        'gb': [
            {id: 20, name: 'PreK'},
            {id: 21, name: 'K-2'},
            {id: 22, name: '3-5'},
            {id: 23, name: '6-8'},
            {id: 24, name: '9-12'}
        ]
    };

    this.promotion = "";
    this.zipcode = "";

    // These names are horribly short because we serialize the configuration to the #anchor portion of the url.
    this.config = {};
    this.config.s = 0;
    this.config.q = "";
    this.config.l = 0;
    this.config.p = 1;
    this.config.n = 10;
    this.config.sa = [];
    this.config.gb = [];

    Ext.get('filter_search').on('blur', function(e, el) {
        PBS.catalog.SearchFilter.set_keyword_filter(Ext.get('filter_search').getValueNoTeaser());
    });
    Ext.get('filter_form').on('submit', function(e, el) {
        e.preventDefault();
        PBS.catalog.SearchFilter.set_keyword_filter(Ext.get('filter_search').getValueNoTeaser());
        PBS.catalog.SearchFilter.get_catalog_data();
    });

    PBS.widgets.tooltip.register('national_provider', 'National Section', 'Learners will discuss course topics and national teaching standards with educators from across the country in this online course.');
    PBS.widgets.tooltip.register('local_provider', 'Local Section', 'Learners will discuss course topics and state teaching standards with educators from their region in this online course.');

    this.post_results_setup();
};

PBS.catalog.SearchFilter.set_promotion = function(value) {
    this.promotion = value;
};

PBS.catalog.SearchFilter.set_show_filter = function(value) {
    this.config.s = value;
};

PBS.catalog.SearchFilter.set_keyword_filter = function(value) {
    this.config.q = value;
};

PBS.catalog.SearchFilter.set_zipcode = function(value) {
    this.zipcode = value;
};

PBS.catalog.SearchFilter.set_page = function(value) {
    this.config.p = value;
};

PBS.catalog.SearchFilter.set_num_per_page = function(value) {
    this.config.n = value;
};

PBS.catalog.SearchFilter.select_filters = function(filter_name, id) {
    if(this.config[filter_name].indexOf(id) == -1) {
        this.config[filter_name].push(id);
    }
};

PBS.catalog.SearchFilter.unselect_filters = function(filter_name, id) {
    this.config[filter_name].remove(id);
};

PBS.catalog.SearchFilter.clear_filters = function() {
    this.config.gb = [];
    this.config.sa = [];
};

PBS.catalog.SearchFilter.display_filters = function() {
    var populate_filters = function(filter_name, selected, unselected) {
        for(var i=0; i<this.filters[filter_name].length; i++) {
            var filter = this.filters[filter_name][i];
            if(this.config[filter_name].indexOf(filter.id) == -1) {
                unselected.push(
                    {tag:'dd', children: [
                        {tag: 'a', href: 'javascript:void(0);', title: 'Add this filter.', id: 'id_catalog_filter_'+filter.id, html: filter.name}
                    ]}
                );
            }
            else {
                selected.push(
                    {tag:'li', children: [
                        {tag: 'a', href: 'javascript:void(0);', title: 'Remove this filter.', id: 'id_catalog_filter_'+filter.id, cls: 'remove', children: [
                            {tag: 'img', cls: 'remove', alt: 'Remove', src: PBS.config.media_url + '/img/teacherline/remove.gif'}
                        ]}
                    ], html: ' ' + filter.name}
                );
            }
        }
    }.createDelegate(this);

    var register_filter_clicks = function(filter_name) {
        for(var i=0; i<this.filters[filter_name].length; i++) {
            var filter = this.filters[filter_name][i];
            if(this.config[filter_name].indexOf(filter.id) != -1) {
                Ext.get('id_catalog_filter_'+filter.id).on('click', function(e, el) {
                    PBS.catalog.SearchFilter.unselect_filters(this.filter_name, this.id);
                    PBS.catalog.SearchFilter.get_catalog_data();
                }, {filter_name:filter_name, id:filter.id});
            }
            else {
                Ext.get('id_catalog_filter_'+filter.id).on('click', function(e, el) {
                    PBS.catalog.SearchFilter.select_filters(this.filter_name, this.id);
                    PBS.catalog.SearchFilter.get_catalog_data();
                }, {filter_name:filter_name, id:filter.id});
            }
        }
    }.createDelegate(this);

    var selected_filters = [];
    var unselected_subjects = [{tag:'dt', html:'Subjects'}];
    var unselected_grades = [{tag:'dt', html:'Grades'}];
    populate_filters('sa', selected_filters, unselected_subjects);
    populate_filters('gb', selected_filters, unselected_grades);

    Ext.get('filter_search').dom.value = this.config.q;
    Ext.get('filter_search').fix_teaser();

    // Add keyword selected filter.
    if(this.config.q != '') {
        var text = this.config.q.substring(0, 15);
        if(this.config.q.length > 15) {
            text += '&hellip';
        }
        selected_filters.push(
            {tag:'li', children: [
                {tag: 'a', href: 'javascript:void(0);', title: 'Remove this filter.', id: 'id_catalog_filter_keywords', cls: 'remove', children: [
                {tag: 'img', cls: 'remove', alt: 'Remove', src: PBS.config.media_url + '/img/teacherline/remove.gif'}
            ]}
         ], html: ' Keywords: ' + text}
        );
    }

    // Add zipcode selected filter.
    if(this.zipcode != '') {
        selected_filters.push(
            {tag:'li', children: [
            {tag: 'a', href: 'javascript:void(0);', title: 'Remove this filter.', id: 'id_catalog_filter_zipcode', cls: 'remove', children: [
                {tag: 'img', cls: 'remove', alt: 'Remove', src: PBS.config.media_url + '/img/teacherline/remove.gif'}
             ]}
             ], html: ' ZIP code: ' + this.zipcode}
        );
    }

    // Add show selected filter.
    if(this.config.s == 2) {
        selected_filters.push(
            {tag:'li', children: [
            {tag: 'a', href: 'javascript:void(0);', title: 'Remove this filter.', id: 'id_catalog_filter_show', cls: 'remove', children: [
                {tag: 'img', cls: 'remove', alt: 'Remove', src: PBS.config.media_url + '/img/teacherline/remove.gif'}
             ]}
             ], html: ' Show: Scheduled Courses'}
        );
    }

    Ext.get('catalog_filters').update('');
    Ext.get('catalog_subjects').update('');
    Ext.get('catalog_grades').update('');

    var el = Ext.DomHelper.overwrite('catalog_filters', {
        tag:'div', children: [
                {tag:'h3', html:'Narrow By'},
                {tag:'ul', children: selected_filters}
        ]});

    var el = Ext.DomHelper.overwrite('catalog_subjects', {
        tag:'dl', children:unselected_subjects
    });

    var el = Ext.DomHelper.overwrite('catalog_grades', {
        tag:'dl', children:unselected_grades
    });

    register_filter_clicks('sa');
    register_filter_clicks('gb');

    if(this.config.q != '') {
        Ext.get('id_catalog_filter_keywords').on('click', function(e, el) {
            PBS.catalog.SearchFilter.set_keyword_filter('');
            PBS.catalog.SearchFilter.get_catalog_data();
        });
    }

    if(this.zipcode != '') {
        Ext.get('id_catalog_filter_zipcode').on('click', function(e, el) {
            PBS.catalog.SearchFilter.set_zipcode('');
            PBS.catalog.SearchFilter.get_organizations_data();
        });
    }

    if(this.config.s == 2) {
        Ext.get('id_catalog_filter_show').on('click', function(e, el) {
            PBS.catalog.SearchFilter.set_show_filter(0);
            PBS.catalog.SearchFilter.get_catalog_data();
        });
    }
};

PBS.catalog.SearchFilter.display_promotion_data = function(result) {
    Ext.get('catalog_announcements').update('');
    PBS.catalog.SearchFilter.display_promotion_code(result.data.promotion != null);

    if(!result.data.promotion) return;

    /* # TODO: add promotion description too (not just promotion code description). As soon as promotion comments field is added and communicated to stations.
       NOTE: Removed at Tim T's request.
     if(result.data.promotion.description) {
        var description = Ext.DomHelper.append('catalog_announcements', {
            tag: 'div', cls: 'msg'
        }, true);
        description.update(result.data.promotion.description);
    }*/

    if(result.data.promotion.code_description) {
        var description = Ext.DomHelper.append('catalog_announcements', {
            tag: 'div', cls: 'msg'
        }, true);
        description.update(result.data.promotion.code_description);
    }
};

PBS.catalog.SearchFilter.display_promotion_code = function(applied) {
    if(applied) {
        if(!Ext.get('promotion_code_remove')) {
            Ext.DomHelper.overwrite('promotion_code_container', {
                tag: 'p', children: [
                    {tag: 'a', href: 'javascript:void(0);', cls: 'remove', title: 'Remove promotion code', children: [
                        {tag: 'img', cls: 'remove', alt: 'Remove', id: 'promotion_code_remove', src: PBS.config.media_url + '/img/teacherline/remove.gif'}
                     ]},
                    ' Promo code applied'
                ]});
            Ext.get('promotion_code_remove').on('click', function(e, el) {
                PBS.catalog.SearchFilter.set_promotion(null);
                PBS.catalog.SearchFilter.get_promotion_data();
            });
        }
    }
    else {
        if(!Ext.get('promotion_code_label')) {
            Ext.DomHelper.overwrite('promotion_code_container', {
                tag: 'div', children: [
                    {tag: 'h2', html: 'Promotions'},
                    {tag: 'form', id: 'promotion_form', children: [
                        {tag: 'dl', children: [
                            {tag: 'dt', children: [
                                {tag: 'label', cls: 'input_value', htmlFor: 'promotion_code', html: 'Promo Code', id: 'promotion_code_label'}
                             ]},
                            {tag: 'dd', children: [
                                {tag: 'input', id: 'promotion_code', type: 'text', value: '', name: 'code'}
                             ]}
                         ]},
                        {tag: 'p', cls: 'submit', children: [
                            ' ',
                            {tag: 'input', id: 'promotion_submit', type: 'submit', value: 'Go', cls: 'green'}
                         ]},
                        {tag: 'p', children: [
                            {tag: 'a', cls: 'help tip', title: 'Promotion Code | If you recieved a promotion code, enter it here to recieve special offers on TeacherLine courses.', href: 'javascript:void(0);', html: ' ?'}
                         ]}
                     ]}
                ]});

            // Setup the textbox teaser.
            PBS.utils.setup_textbox_teasers('promotion_code_container');
            // Setup the tooltip.
            PBS.widgets.tooltip.setup('promotion_code_container');

            Ext.get('promotion_code').on('blur', function(e, el) {
                if(Ext.get('promotion_code')) {
                    PBS.catalog.SearchFilter.set_promotion(Ext.get('promotion_code').getValueNoTeaser());
                }
            });
            Ext.get('promotion_form').on('submit', function(e, el) {
                e.preventDefault();
                if(Ext.get('promotion_code')) {
                    PBS.catalog.SearchFilter.set_promotion(Ext.get('promotion_code').getValueNoTeaser());
                    PBS.catalog.SearchFilter.get_promotion_data();
                }
            }, true);
        }
        Ext.get('promotion_code').fix_teaser();
    }
};

PBS.catalog.SearchFilter.display_paginators = function(data) {
    Ext.select('.display_settings').each(function(el) {
        Ext.id(el);
        var paginator = new PBS.utils.Paginator(el.dom.id, data);
        paginator.page_request.addListener(function(kwargs) {
            if(kwargs.page) {
                PBS.catalog.SearchFilter.set_page(kwargs.page);
            }
            if(kwargs.num_per_page >= 0) {
                PBS.catalog.SearchFilter.set_num_per_page(kwargs.num_per_page);
            }
            PBS.catalog.SearchFilter.get_catalog_data();

            if (document.documentElement && document.documentElement.scrollTop) {
                document.documentElement.scrollTop = 0;
            }
            else if (document.body) {
                document.body.scrollTop = 0;
            }
        });
    });
};

PBS.catalog.SearchFilter.display_availability = function(has_promotion, localized) {
    if(has_promotion) {
        this.zipcode = '';
        Ext.get('catalog_availability').update('');
    }
    else {
        if(!Ext.get('catalog_availability_marker')) {
            var el = Ext.DomHelper.overwrite('catalog_availability', {
                tag: 'div', cls: 'body availability', children: [
                        {tag: 'h3', html: 'Availability', id: 'catalog_availability_marker'},
                        {tag: 'p', html: 'To see course schedule, please enter your school ZIP code.'},
                        {tag: 'form', id: 'school_form', method: 'get', action: '#', children: [
                                {tag: 'dl', cls: 'search', children: [
                                        {tag: 'dt', children: [
                                                {tag: 'label', cls: 'input_value', htmlFor: 'school_zip', html: 'ZIP'}
                                         ]},
                                        {tag: 'dd', children: [
                                                {tag: 'input', type: 'text', name: 'zipcode', maxlength: 5, id: 'school_zip', value: ''}
                                         ]}
                                 ]},
                                {tag: 'p', cls: 'submit', children: [
                                        ' ',
                                        {tag: 'input', type: 'submit', id: 'school_submit', value: 'Go', cls: 'green'}
                                 ]}
                         ]}
                ]});

            // Install the teaser listener first so that the teaser value is cleared on form submission.
            PBS.utils.setup_textbox_teasers('catalog_availability');

            Ext.get('school_zip').on('blur', function(e, el) {
                PBS.catalog.SearchFilter.set_zipcode(Ext.get('school_zip').getValueNoTeaser());
            });
            Ext.get('school_form').on('submit', function(e, el) {
                e.preventDefault();
                PBS.catalog.SearchFilter.set_zipcode(Ext.get('school_zip').getValueNoTeaser());
                PBS.catalog.SearchFilter.get_organizations_data();
            }, true);
        }
        Ext.get('school_zip').dom.value = this.zipcode;
        // Call the fix_teaser function created by setup_textbox_teasers.
        Ext.get('school_zip').fix_teaser();
    }

    if(!localized || this.config.s == 2) {
        Ext.get('catalog_show').update('');
    }
    else {
        if(this.config.s != 2) {
            var el = Ext.DomHelper.overwrite('catalog_show', {
                tag: 'div', cls: 'body show', children: [
                        {tag: 'dl', children: [
                                {tag: 'dt', html: 'Show'},
                                {tag: 'dd', children: [
                                        {tag: 'a', href: 'javascript:void(0);', id: 'catalog_filter_show', html: 'Scheduled Courses'}
                                 ]}
                         ]}
                ]});
            Ext.get('catalog_filter_show').on('click', function(e, el) {
                PBS.catalog.SearchFilter.set_show_filter(2);
                PBS.catalog.SearchFilter.get_catalog_data();
            });
        }
        else {
            var el = Ext.DomHelper.overwrite('catalog_show', {
                tag: 'div', cls: 'body show', children: [
                        {tag: 'dl', children: [
                                {tag: 'dt', html: 'Show'}
                         ]}
                ]});
        }
    }
};

PBS.catalog.SearchFilter.display_catalog_data = function(result) {
    for(var i=0; i<result.messages.length; i++) {
        var message = result.messages[i];
        var element = null;
        if(message.code == 'zipcode') {
            element = 'school_submit';
        }
        else if(message.code == 'promotion_code') {
            element = 'promotion_submit';
        }
        PBS.messages.display({'type': 'error', header: 'Whoops!', message: result.messages[i].text, element: element});
    }

    this.config.l = result.data.localized ? 1 : 0;
    this.display_availability(result.data.has_promotion, result.data.localized);
    this.display_filters();
    this.display_promotion_code(result.data.has_promotion);

    Ext.get('results').update('');

    this.display_paginators(result.data.paginator);

    var course_sections = {};
    for(var j=0; j<result.data.sections.length; j++) {
        var section = result.data.sections[j];
        var organization = 'National';
        var organization_tip = 'national_provider';
        var section_link = {tag: 'a', href: section.url, html: 'Details/Enroll&hellip;'};
        if(section.seats_available == 0) {
            section_link = {tag: 'a', href: section.url, html: 'Full&hellip;'};
        }
        
        if(section.organization.id != 168) {
            organization = 'Local';
            organization_tip = 'local_provider';
        }
        if(!course_sections[section.course]) {
            course_sections[section.course] = [];
        }
        
        course_sections[section.course].push({tag: 'tr', children: [
            {tag: 'td', cls: 'course_id', html: section.name},
            {tag: 'td', cls: 'name', children: [
                {tag: 'a', href: 'javascript:void(0);', cls: 'tip ' + organization_tip, html: organization}
            ]},
            {tag: 'td', cls: 'dates', html: Date.parseDate(section.date_start, 'Y-m-d').format('m/d/Y') + '&mdash;' + Date.parseDate(section.date_end, 'Y-m-d').format('m/d/Y')},
            {tag: 'td', cls: 'more', children: [
                section_link
             ]}
        ]});
    }

    for(var i=0; i<result.data.courses.length; i++) {
        var course = result.data.courses[i];
        var title = [
            course.name + ' ',
            {tag: 'strong', html: course.title + ' '}
        ];
        if(course.teacher_favorite) {
            title.push({tag: 'img', cls: 'tip teacher_favorite', title: 'This course is a teacher favorite', alt: 'Teacher Favorite', src: PBS.config.media_url + '/img/teacherline/teacher_favorite.gif'});
        }
        if(course.classroom_link) {
            title.push({tag: 'img', cls: 'tip classroom_link', title: 'This course asks learners to implement lessons with their class', alt: 'Classroom Link', src: PBS.config.media_url + '/img/teacherline/class_access.gif'});
        }

        var details = [];
        if(!course_sections[course.name] || course_sections[course.name].length == 0) {
            if(result.data.localized) {
                details.push({tag: 'table', cls: 'sections', children: [
                    {tag: 'tbody', children: [
                        {tag: 'tr', children: [
                            {tag: 'td', html: 'There are no sections currently available. Please check the annual schedule.'},
                            {tag: 'td', cls: 'more', children: [
                                {tag: 'a', title: 'Read more about this course', href: course.url, html: 'Details&hellip;'}
                             ]}
                         ]}
                     ]}
                 ]});
            }
            else {
                details.push({tag: 'table', cls: 'sections', children: [
                    {tag: 'tbody', children: [
                        {tag: 'tr', children: [
                            {tag: 'td', cls: 'more', children: [
                                {tag: 'a', title: 'Read more about this course', href: course.url, html: 'Details&hellip;'}
                             ]}
                         ]}
                     ]}
                 ]});
            }
        }
        else {
            details.push({tag: 'table', cls: 'sections', children: [
                {tag: 'tbody', children: course_sections[course.name]}
            ]});
        }

        var el = Ext.DomHelper.append('results', {
            tag: 'div', cls: 'result block2', children: [
                    {tag: 'div', cls: 'body', children: [
                            {tag: 'h3', cls: 'name', children: title},
                            {tag: 'div', cls: 'info', children: [
                                    {tag: 'dl', cls: 'subject', children: [
                                            {tag: 'dt', html: 'Subjects: '},
                                            {tag: 'dd', html: course.subject_areas.join(', ')}
                                     ]},
                                    {tag: 'dl', cls: 'grades', children: [
                                            {tag: 'dt', html: 'Grades: '},
                                            {tag: 'dd', html: course.grade_band}
                                     ]},
                                    {tag: 'dl', cls: 'hours', children: [
                                            {tag: 'dt', html: 'Hours: '},
                                            {tag: 'dd', html: course.hours}
                                     ]}
                             ]},
                            {tag: 'p', cls: 'description', html: course.description_short},
                            {tag: 'div', children: details}
                     ]}
            ]}, true);
    }

    if(result.data.courses.length == 0) {
        var el = Ext.DomHelper.overwrite("results", {
            tag: 'div', cls: 'msg', children: [
                    {tag: 'strong', html: 'No Results'},
                    {tag: 'p', html: 'The combination of filters that you have selected returned no results. Try removing filters from the "Course Search" bar on the left.'}
            ]});
    }

    Ext.get('results').fadeIn();

    Ext.select('.display_settings .results').highlight();
    Ext.select('#secondary .course_search .body').addClass('highlight');
    var remove_highlight = function() {
        Ext.select('#secondary .course_search .body').removeClass('highlight');
    };
    remove_highlight.defer(750);

    // Setup tooltips for the new catalog content.
    PBS.widgets.tooltip.setup('results');

    this.post_results_setup();
};

PBS.catalog.SearchFilter.post_results_setup = function() {
    Ext.select('#results .result').each(function(el, scope, index) {
        el.on("mouseover", function(e){
            if(!e.within(this, true)) {
                el = Ext.fly(this, '_internal');
                el.select('.sections').addClass('selected');
            }
        }, el.dom);

        el.on("mouseout", function(e) {
            if(!e.within(this, true)) {
                el.select('.sections').removeClass('selected');
            }
        }, el.dom);
    });
};

PBS.catalog.SearchFilter.display_organizations_data = function(result) {
    for(var i=0; i < result.data.organizations.length; i++) {
        var organization = result.data.organizations[i];
        if(organization.announcement) {
            var announcement = Ext.DomHelper.append('catalog_announcements', {
                tag: 'div', cls: 'msg'
            }, true);
            announcement.update(organization.announcement);
        }
    }
};

PBS.catalog.SearchFilter.get_catalog_data = function() {
    var callback = PBS.utils.create_callback({success: function(options, response, result) {
        if(!result.success) {
            PBS.messages.display({'type': 'error', header: 'Whoops!', message: 'There was an error processing your request. Please try again soon.' });
            return;
        }

        var show = 0;
        if(result.data.only_sections) {
            show = 2;
        }
        else if(result.data.localized) {
            show = 1;
        }

        PBS.catalog.SearchFilter.set_zipcode(result.data.zipcode);
        PBS.catalog.SearchFilter.set_show_filter(show);
        PBS.catalog.SearchFilter.display_catalog_data(result);
        PBS.catalog.SearchFilter.store_configuration();
    }});

    var connection = new Ext.data.Connection({timeout:30000});
    var url = PBS.config.site_url + '/jsonrpc/';

    var post_data = {
        "method": "get_catalog_courses_and_sections",
        "params": [{
            "subject_areas": this.config.sa,
            "grade_bands": this.config.gb,
            "keywords": this.config.q,
            "page": this.config.p,
            "num": this.config.n,
            "only_sections": (this.config.s == 2)
        }]
    };
    connection.request({url: url, method: 'post', params: Ext.encode(post_data), callback: callback});
    PBS.messages.loading();
};

PBS.catalog.SearchFilter.get_organizations_data = function(get_only) {
    var callback = PBS.utils.create_callback({success: function(options, response, result) {
        Ext.get('catalog_announcements').update('');

        if(!result.success) {
            PBS.messages.display({'type': 'error', header: 'Whoops!', message: 'There was an error processing your request. Please try again soon.' });
            return;
        }

        PBS.catalog.SearchFilter.display_organizations_data(result);
        PBS.catalog.SearchFilter.get_catalog_data();

        PBS.catalog.SearchFilter.store_configuration();
    }});

    var connection = new Ext.data.Connection({timeout:30000});
    var url = PBS.config.site_url + '/jsonrpc/';

    var post_data = {
        "method": get_only ? "get_catalog_organizations" : "set_catalog_localization_zipcode",
        "params": [{
            "zipcode": this.zipcode
        }]
    };
    connection.request({url: url, method: 'post', params: Ext.encode(post_data), callback: callback});
    PBS.messages.loading();
};

PBS.catalog.SearchFilter.get_promotion_data = function() {
    var callback = PBS.utils.create_callback({success: function(options, response, result) {
        PBS.catalog.SearchFilter.display_promotion_data(result);

        if(!result.success) {
            for(var i=0; i<result.messages.length; i++) {
                PBS.messages.display({'type': 'error', header: 'Whoops!', message: result.messages[i].text });
            }
            return;
        }

        PBS.catalog.SearchFilter.get_catalog_data();
    }});

    var connection = new Ext.data.Connection({timeout:30000});
    var url = PBS.config.site_url + '/jsonrpc/';

    var post_data = {
        "method": "set_session_promotion",
        "params": [{
            "code": this.promotion
        }]
    };
    connection.request({url: url, method: 'post', params: Ext.encode(post_data), callback: callback});
    PBS.messages.loading();
};
