/*
*   The Keg App
*   Provides basic functionality for every page of the site
*
*   Requires:
*       Trapeze jQuery distribution
*
*   Marcos Abreu - May 12, 2009
*/

$.namespace("trapeze.TheKeg");

trapeze.TheKeg = $.Class.extend({
    locations : [],

    resize_shadow : function() {
        var wWindow = document.body.clientWidth;
        var width = '100%';
        if (wWindow < $('#SiteWrapper').width()) {
            width = $('#SiteWrapper').width();
        }
        $('#TopShadow').width(width);
    },

    
    filter_location : function(evt) {
        var filter_id = '';
        if ($(evt.currentTarget).attr('id') == 'LocationCountries')
            filter_id = 'LocationProvinces'
        else // == 'LocationProvinces'
            filter_id = 'LocationPlaces';

        if (($(evt.currentTarget).val() != '') && ($(evt.currentTarget).val() != '---------')) {
            var locations = jQuery.grep(this.locations, function(item, i){
                return (item.indexOf($(evt.currentTarget).val()) >= 0);
            });
            var items = [];
            for(var i=0; i<locations.length; i++) {
                var item = locations[i].slice(0,locations[i].lastIndexOf('('));
                if (filter_id == 'LocationProvinces')
                    var item = locations[i].slice((locations[i].lastIndexOf("(") + 1), locations[i].lastIndexOf(','));
                if (jQuery.inArray(item, items) < 0)
                    items.push(item);
            }
            if (filter_id == 'LocationProvinces') {
                $('#LocationPlaces').parent('.select-wrapper').remove();
            }
            if (filter_id == 'LocationPlaces') {
                this.build_selectbox(items, filter_id, $('#LocationLine'), false, this.pre_selected_place);
            } else {
                this.build_selectbox(items, filter_id, $('#LocationLine'), true);
            }
        } else {
            $('#'+filter_id).parent('.select-wrapper').remove();
            if (filter_id == 'LocationProvinces') {
                $('#LocationPlaces').parent('.select-wrapper').remove();
            }
        }
    },

    build_selectbox : function(list, list_id, jParent, doBind, pre_selection) {
        var opts = '<option val="">---------</option>';
        for (i=0; i<list.length; i++) {
            if ( pre_selection && list[i] == pre_selection ) {
                opts += '<option selected="selected" val="' + list[i] + '">' + list[i] + '</option>';
            } else {
                opts += '<option val="' + list[i] + '">' + list[i] + '</option>';
            }
        }
        if ($('#'+list_id).size() > 0) {
            $('#' + list_id + ' option').remove();
            $('#' + list_id).append(opts).trigger('change');
        } else {
            jParent.append('<select id="' + list_id + '">'+opts+'</select>');
            var form_selector = '#' + $('#id_0-location').parents('form').attr('id');
            new trapeze.StyleFormElements({selector:form_selector});
            if (list_id == 'LocationProvinces') {
                $('#'+list_id).parent('.select-wrapper').css('width', $('#'+list_id).width() + 18);
            }
        }

        if (doBind) { //if true bind the change event to the filter function
            $('#'+list_id).bind('change', this.filter_location.bind(this));
        } else { //else bind the change event to the change event of the original select box
            $('#'+list_id).bind('change', function() {
                $('#id_0-location').find("option:contains('" + $(this).val() + "')").attr('selected', 'true');
                $('#id_0-location').trigger('change');
            });
        }
    },

    split_location : function(jLocation) {
        // Store all the locations
        this.locations = jLocation.find('option').text().replace(/\)(\S)/g,')||$1').split('||');
        this.locations[0] = this.locations[0].replace(/-*/,'');


        previous_selection_made = false;

        // Get the pre-selected options, if any
        if (!($('option:selected', jLocation).attr('value') == '')) {
            previous_selection_made = true;
            selected_text = $('option:selected', jLocation).text();
            selected_country = selected_text.slice(selected_text.indexOf(',') + 2, -1);
            selected_province = selected_text.slice((selected_text.lastIndexOf("(") + 1), selected_text.lastIndexOf(','));
            selected_place = selected_text.slice(0, selected_text.lastIndexOf('('));
            // Set this so that the list creator can use it
            this.pre_selected_place = selected_place;
        }

        var countries = [];

        // Collect the unique countries
        for(var i=0; i<this.locations.length; i++) {
            var country = this.locations[i].slice((this.locations[i].indexOf(', ') + 2), -1);
            if (jQuery.inArray(country, countries) < 0) {
                countries.push(country);
            }
        }

        // Build the Country select box
        this.build_selectbox(countries, 'LocationCountries', $('#LocationLine'), true);

        // Set the selections to the pre selected values, if any
        if (previous_selection_made) {
            $('#LocationCountries').val(selected_country);
            $('#LocationCountries').trigger('change');
            $('#LocationProvinces').val(selected_province);
            $('#LocationProvinces').trigger('change');

            // the pre-selected place will be set by the list creator
        }
    },


    set_home_animation : function(animation_path, container_id) {
        var express_path = (trapeze.media_path+'flash/expressInstall.swf');
        var flashvars = {
			basePath:			'',
            prefsPath:          trapeze.prefs_path
        };
        var params = {
            menu:               'false',
            quality:            'best',
            scale:              'noscale',
            salign:             't',
            wmode:              'transparent',
            bgcolor:            "#FFFFFF",
            allowfullscreen:    'false',
            allowscriptaccess:  'always'
        };
        var attributes = {};

        swfobject.embedSWF(animation_path, container_id, "849", "400", "8", express_path, flashvars, params, attributes);
    },


    init : function() {
        this.resize_shadow();
        $(window).bind('resize', this.resize_shadow.bind(this));

        if ($('body.home-page').size()>0) {
            this.set_home_animation((trapeze.media_path+'flash/index.swf'),'FlashAlternativeContent');
        }

        if ($('body.search-results-page').size()>0){
            $('.location-search-result')
            .bind('click', function(){
                new_image = ($(this).css('background-image').indexOf('-down') > 0) ? 
                    $(this).css('background-image').replace('-down', '-up') : 
                    $(this).css('background-image').replace('-up', '-down');
                $(this).css('background-image', new_image).find('address').slideToggle('normal');
            })
            .find('address').slideUp(0);
        }

        if ($('body').attr('class') == 'step-1') {
            this.split_location($('#id_0-location'));
            $('#id_0-location').parent('.select-wrapper').hide();
        }

    }
});

$(function() {
    new trapeze.TheKeg();
});
