MM = {};

MM.UI = {
    
    modal_showing: false,
    
    showModal: function (div_id, add_css, call_after) {
        if(MM.UI.modal_showing) { MM.UI.hideModal(); }
        
        $('.smokescreen').show();
        //$('#'+div_id).css(add_css).show();
        $('#'+div_id).show();
        
        
        MM.UI.modal_showing = div_id;
        
        if(call_after) { call_after(); }
    },
    
    hideModal: function (call_after) {
        $('.smokescreen').fadeOut(150);
        $('#'+MM.UI.modal_showing).fadeOut(150);
        MM.UI.modal_showing = false;
        
        if(call_after) { call_after(); }
    },
    
    populateEmbedModal: function (title, file_path, image_path) {
        
        base_url = 'http://www.ministryflix.com';
        code = '<embed' +
               ' src="'+base_url+'/player/clipplayer.swf"' +
               ' width="320"' +
               ' height="260"' +
               ' allowscriptaccess="always"' +
               ' type="video"' +
               ' flashvars="file=' + file_path + '&image=' + image_path + '"' +
               '/>';
        /*code =  '<object type="application/x-shockwave-flash" data="'+base_url+'/player/clipplayer.swf?&file='+base_url+file_path+'&image='+base_url+image_path+'" width="320" height="240" wmode="transparent">' +
                '<param name="movie" value="'+base_url+'/player/clipplayer.swf?autoStart=false&file='+file_path+'&image='+image_path+'" />' +
                '<param name="wmode" value="transparent" />' +
                '</object>';*/
        
        $('span[id=embed_video_title]').text(title);
        $('textarea[name=video_code]').val(code);
    },
    
    initializeClipJqmLinks: function() {
    },
    
    // IE7 hack: IE7 won't bind inline onclick events that are appended to the DOM after page load.
    // Traverses every anchor of class "ajax_loader" and programatically binds the eval'd result of 
    // the element's onclick attribute. Using this until inline javascript is factored out to this file.
    rebindOnclickForIE7: function() {
        if(jQuery.browser.msie) {
            $('.ajax_loader').each(function() {
               $(this).bind('click', function() { eval($(this).attr('onclick')); });
            });
        }
    },
    
    flowplayerOptions: function(el) {
        return {
        
            key: '#$1431fb716f89d82f15a',

            logo: {
                url: '/images/ministryflix_flash_watermark.png',
                bottom: 12,
                left: 15,
                opacity: 0.8,
                width: '250px',
                height: '47px',
                
                displayTime: 0,  // show for the entire duration of the video
                // fadeSpeed: 0,
                fullscreenOnly: false
                
            },
            
            
            playlist: [
                {
                    url: el.attr('thumbpath'),
                     scaling: 'fit'
                },
    
                 { 
                    url: el.attr('filepath'), 
                    autoPlay:    false,
                    autoBuffering: false,
                    scaling:    'fit'
                }
            ],
            
                
            
            canvas: {
                backgroundGradient: 'none',
                backgroundColor: '#000',
                padding: 0
            },
            
            plugins: {
                controls: {
                    wmode: 'transparent',
                    url: '/player/flowplayer.controls-3.2.1.swf',
                    
                    // control bar widgets
                    all: false,
                    play: true,
                    volume: true,
                    time: true,
                    scrubber: true,
                    
                    // autohiding
                    autoHide: {
                        enabled: true,
                        fullscreenOnly: false,
                        hideDelay: 1,
                        hideDuration: 800,
                        hideStyle: 'move',
                        mouseOutDelay: 2000
                    }
                }
            }
            
        };
    },
    
    initializeFlowplayer: function(id) {
        
        if(id === undefined) { id = 'flowplayer'; }
        
        el = $('#'+id);
        el.show();
        
        if(el.attr('filepath') !== undefined) {
            MM.UI.installedFlowplayer = $f(id, { wmode: 'transparent', src: '/player/flowplayer.commercial-3.2.2.swf' }, MM.UI.flowplayerOptions(el));
        }
    },
    
    showPreviewFromNewsletter: function(asset_id) {
        $('#modal_newsletter_preview #mnp_content').load('/ajax.html', { component: 'showNewsletterPreview', id: asset_id }, function() {
            $('#modal_newsletter_preview').jqmShow();
            MM.UI.initializeFlowplayer('flowplayer_newsletter_preview');
        });
    },
    
    showModalRegisterForm: function() {
        
        $('#modal_registrationForm .loading').show();
        $('#modal_registrationForm #mrf_content').hide();
        $('#modal_registrationForm').jqmShow();
        
        $('#modal_registrationForm #mrf_content').load('/ajax.html', { component: 'showModalRegistrationForm' }, function() {
            $('#modal_registrationForm .loading').hide();
            $('#modal_registrationForm #mrf_content').show();
        });
        
        return false;
    },
    
    // IE7 hack: to prevent IE7 from forcing user to click on flash video player to 'activate ActiveX control'
    activateIE7Control: function () {
        objects = document.getElementsByTagName("object");
        for (var i = 0; i < objects.length; i++) { objects[i].outerHTML = objects[i].outerHTML; }
    }
};

MM.Ajax = {
    loadClip: function() {
        el = $(this);
        options = {
          component:        (el.attr('component') === undefined ? 'clip' : el.attr('component'))
        };
        
        if(el.attr('asset_id') !== undefined) {
            options.asset_id = el.attr('asset_id');
        } else {
            options.package_id = el.attr('package_id');
        }
        
        if(el.attr('context') !== undefined) { options.context = el.attr('context'); }
            
        $('#gallery_ajax_loading').show();
        
        $('#left_pane').load('/ajax.html', options,
            function() {
                // tigger google analytics tracker
                //pageTracker._trackPageview(el.attr('href'));
                
            
                MM.UI.initializeClipJqmLinks();
                MM.UI.initializeFlowplayer();
                //MM.UI.activateIE7Control();
                $('#gallery_ajax_loading').hide();
            }
        );
        
        return false;
    },
    
    loadGallery: function() {
        el = $(this);
        
        // set options with element's XHTML attributes
        if(el.attr('qs') === undefined) {
            options = {
              component:        (el.attr('component') === undefined ? 'gallery' : el.attr('component')),
              category_name:    el.attr('category_name'),
              gallery:            el.attr('gallery')
            };
            
            if(el.attr('producer_id') !== undefined) {
                options.producer_id = el.attr('producer_id');
            }
            
            if(el.attr('sort') !== undefined) {
                options.sort = el.attr('sort');
            }
            
            if(el.attr('submenu_cat') !== undefined) {
                options.submenu_cat = el.attr('submenu_cat');
            }
            
            if(el.attr('subcategory_name') !== undefined) {
                options.subcategory_name = el.attr('subcategory_name');
            }
            
            if(el.attr('search_query') !== undefined) {
                options.search = el.attr('search_query');
            }
            
            var query_string = '';
        } else {
            options = {};
            var query_string = el.attr('qs');
        }
            
        load_url = (el.attr('ajax_route') === undefined || el.attr('ajax_route') == '' ? '/ajax.html' : el.attr('ajax_route'));
        
        $('#gallery_ajax_loading').show();
        
        $('#center_pane').load(load_url+'?'+query_string, options,
            function(data) {
                $('#gallery_ajax_loading').hide();
                
                // bind gallery dropdowns
                $('#gallery_sort_dropdown_button').applyDropdown({ dropdown_selector: '#gallery_sort_dropdown' });
                $('#gallery_category_dropdown_button').applyDropdown({ dropdown_selector: '#gallery_category_dropdown' });
                
                // tigger google analytics tracker
                //pageTracker._trackPageview(el.attr('href'));
            }
        );
        
        return false;
        
    },
    
    submitQuicksearchForm: function() {
        el = $('#gallery_quicksearch_form');
        
        options = {
          component:        'galleryProducer',
          producer_id:        el.attr('producer_id'),
          gallery:            el.attr('gallery'),
          submenu_cat:        el.attr('submenu_cat'),
          search:            escape($('.quicksearch_input').val())
        };
        
        $('#gallery_ajax_loading').show();
        
        $('#center_pane').load(el.attr('ajax_route'), options,
            function() {
                $('#gallery_ajax_loading').hide();
            }
        );
        
        return false;
    },
    
    submitBasicSearchForm: function() {
        
        
        
        options = {
          component:        'gallerySearchBasic',
          search:            escape($('#search_input_wrapper .basic_search_input').val())
        };
        
        $('#center_pane').load('/ajax.html', options,
            function() {
                // bind gallery dropdowns
                $('#gallery_sort_dropdown_button').applyDropdown({ dropdown_selector: '#gallery_sort_dropdown' });
                $('#gallery_category_dropdown_button').applyDropdown({ dropdown_selector: '#gallery_category_dropdown' });
            }
        );
                
        
    },
    
    loadSavedItems: function() {
        
        var el = $(this);
        
        var options = {
                component:    'gallerySaved',
                saved_type:    'movies'
        };
        
        if(el.attr('saved_type') !== undefined) { options.saved_type = el.attr('saved_type'); }
        
        $('#gallery_ajax_loading').show();
        
        $('#center_pane').load('/ajax.html', options,
            function(data) {
                $('#gallery_ajax_loading').hide();
                
                // trigger google analytics tracker
                //pageTracker._trackPageview(el.attr('href'));
            }
        );
        
        return false;
    },
    
    toggleSaveItem: function() {
                var el = $(this);
        
        time = new Date(); // added to request params to dodge IE cache
        
                var options = {};
        options.time = time.getTime();
        if(options.component === undefined) { if(el.attr('component') === undefined) { options.component = 'toggleSaveItem'; } else { options.component = el.attr('component'); } }
        if(options.asset_id === undefined) { options.asset_id = el.attr('asset_id'); }
        
        $('#gallery_ajax_loading').show();
        
        $.getJSON('/ajax.html', options, function(data) {
            if(data.error == 0) {
                if(options.callback === undefined) {
                    $('#save_item'+options.asset_id).html(data.new_state);
                    $('#saved_asset'+options.asset_id).hide();
                    
                    if(data.user_has_saved_movies || data.user_has_saved_packages) {
                        /*el_saved_tab_anchor = $('#gallery_tabs_anchor_saved_movies');
                        el_saved_tab = $('#gallery_tabs_anchor_saved_movies .gallery_tab');
                        el_saved_tab_anchor.addClass('ajax_load_gallery').removeClass('ajax_load_gallery_inactive');
                        el_saved_tab.attr('id', 'gallery_tab_saved_movies_off');*/
                        $('#uml_saved_movies_inactive').attr('id', 'uml_saved_movies');
                    } else {
                        /*el_saved_tab_anchor = $('#gallery_tabs_anchor_saved_movies');
                        el_saved_tab = $('#gallery_tabs_anchor_saved_movies .gallery_tab');
                        el_saved_tab_anchor.addClass('ajax_load_gallery_inactive').removeClass('ajax_load_gallery');
                        el_saved_tab.attr('id', 'gallery_tab_saved_movies_inactive');*/
                        $('#uml_saved_movies').attr('id', 'uml_saved_movies_inactive');
                    }
                        
                } else {
                    
                }
                    
            } else { alert(data.error); }
            
            $('#gallery_ajax_loading').hide();
        });
        
        return false;
    },
    
    toggleSavePackage: function() {
        
        el = $(this);
        
        time = new Date(); // added to request params to dodge IE cache
        
        var options = {};
        options.time = time.getTime();
        if(options.component === undefined) { if(el.attr('component') === undefined) { options.component = 'toggleSavePackage'; } else { options.component = el.attr('component'); } }
        if(options.package_id === undefined) { options.package_id = el.attr('package_id'); }
        
        $('#gallery_ajax_loading').show();
        
        $.getJSON('/ajax.html', options, function(data) {
            if(data.error == 0) {
                if(options.callback === undefined) {
                    $('#save_item'+options.package_id).html(data.new_state);
                    $('#saved_asset'+options.package_id).hide();
                    
                    if(data.user_has_saved_movies || data.user_has_saved_packages) {
                        /*el_saved_tab_anchor = $('#gallery_tabs_anchor_saved_movies');
                        el_saved_tab = $('#gallery_tabs_anchor_saved_movies .gallery_tab');
                        el_saved_tab_anchor.addClass('ajax_load_gallery').removeClass('ajax_load_gallery_inactive');
                        el_saved_tab.attr('id', 'gallery_tab_saved_movies_off');*/
                        $('#uml_saved_movies_inactive').attr('id', 'uml_saved_movies');
                    } else {
                        /*el_saved_tab_anchor = $('#gallery_tabs_anchor_saved_movies');
                        el_saved_tab = $('#gallery_tabs_anchor_saved_movies .gallery_tab');
                        el_saved_tab_anchor.addClass('ajax_load_gallery_inactive').removeClass('ajax_load_gallery');
                        el_saved_tab.attr('id', 'gallery_tab_saved_movies_inactive');*/
                        $('#uml_saved_movies').attr('id', 'uml_saved_movies_inactive');
                    }
                        
                } else {
                }
                    
            } else { alert(data.error); }
            
            $('#gallery_ajax_loading').hide();
        });
        
        return false;
    },
    
    
    toggleSaveItemFromNewsletterPreview: function() {
        
        options = {
                callback: function(data, options) {
                    $('#modal_newsletter_preview').jqmHide();
                }
        };
        
        MM.Ajax.toggleSaveItem(options, '.clip_save');
        
    },
    
    bindAjaxEvents: function() {
        // check if jquery 1.3.x is loaded before calling $.live() (to fix conflicts in producer pages dependent on 1.2.x)
        if(jQuery.isFunction($(document).live)) {
            $('.ajax_load_gallery').live("click", MM.Ajax.loadGallery);
            $('.ajax_load_gallery_inactive').live("click", function() { return false; });
            $('.ajax_load_clip').live("click", MM.Ajax.loadClip);
            $('.ajax_toggle_buy').live("click", function() { MM.Cart.addItemFromClip('clip_buy'); return false; });
            $('.clip_buy_anchor').live("click", function() { return false; }); // prevent full page load with JS enabled
            $('.ajax_toggle_save_item').live("click", MM.Ajax.toggleSaveItem);
            $('.ajax_toggle_save_package').live("click", MM.Ajax.toggleSavePackage);
            $('.ajax_login_required').live("click", function() { $('#modal_loginRequired').jqmShow(); });
            $('.newsletter_preview_login_required').live("click", function() { $('#modal_newsletter_preview').jqmHide(); $('#modal_loginRequired').jqmShow(); });
            
            $('#uml_saved_movies_inactive').live("click", function() { return false; });
            $('#uml_saved_movies, .ajax_load_saved').live("click", MM.Ajax.loadSavedItems);
            
            
            $('.trigger_ipod_popup').live("click", function() {
                if(jQuery.trim($('#clip_buy').text()) == 'In cart') {
                    MM.Cart.addItemFromClip('clip_buy');
                } else {
                    $('#modal_ipod_license').jqmShow();
                }
            });
            
            $('.newsletter_preview_toggle_buy').live("click", MM.Cart.addItemFromNewsletterPreviewPopup);
            $('.newsletter_preview_toggle_save_item').live("click", MM.Ajax.toggleSaveItemFromNewsletterPreview);
            
            $('#search_input_wrapper .basic_search_submit').live("click", MM.Ajax.submitBasicSearchForm);
        }
    }
};


MM.Cart = {
    /*
     * addItem options:
     *   submit_url: url for GET request
     *   version_id: asset's version_id that will be added to cart
     *   ipod_only:  add at ipod price
     */
        
    itemsInCart: 0,
    
    updateItemsInCart: function(add_to) {
        MM.Cart.itemsInCart += add_to;
        
        if(MM.Cart.itemsInCart == 0) {
            $('#label_items_in_cart').text('No');
        } else {
            $('#label_items_in_cart').text(MM.Cart.itemsInCart);
        }
        
        if(MM.Cart.itemsInCart == 1) {
            $('#label_items_text').text('item');
        } else {
            $('#label_items_text').text('items');
        }
    },
    
    addItem: function(options, el_id) {
        
        if(el_id === undefined) {
            el = $(this);
        } else {
            el = $("#" + el_id);
        }
        
        if(options.submit_url === undefined) { options.submit_url = el.attr('submit_url'); }
        if(options.check_hd === undefined) { options.check_hd = el.attr('check_hd'); }
        if(options.asset_id === undefined) { options.asset_id = el.attr('asset_id'); }
        if(options.ipod_only === undefined) { options.ipod_only = el.attr('ipod_only'); }
        if(options.hd_price === undefined) { options.hd_price = el.attr('hd_price'); }
            
        $('#gallery_ajax_loading').show();
        
        if(options.check_hd == 1 && jQuery.trim($('#clip_buy').html()) == 'Buy') {
            MM.Cart.showHdAvailablePopup(options.asset_id, options.hd_price);
        } else {
            time = new Date(); // added to request params to dodge IE cache
            $.getJSON(options.submit_url, { 'component': 'toggleCartItem', 'asset_id': options.asset_id, 'ipod_only' : options.ipod_only, 'with_hd' : options.with_hd, 'time': time.getTime() },
                      function(data) {
                          if(data.error == 0) {
                              if(data.recommended_id) { MM.Cart.loadRecommended({ submit_url: options.submit_url, recommended_id: data.recommended_id }); }
                              if(options.callback !== undefined) { options.callback(options, data); }
                          } else {
                              alert(data.error); 
                          }
                          
                          $('#gallery_ajax_loading').hide();
                      });
        }
        
        return false;
    },
    
    togglePackage: function(options) {
        $.getJSON(options.submit_url, { 'component': 'toggleCartPackage', 'package_id': options.package_id },
                                      function(data) {
                                          if(data.error == 0) {
                                              if(options.callback) { options.callback(options, data); }
                                          } else {
                                              alert(data.error); 
                                          } 
                                      });
        return false;
    },
    
    addRecommendedToCart: function(options) {
        $.getJSON(options.submit_url, { 'component': 'toggleCartItem', 'asset_id': options.asset_id, 'recommended_by': options.recommended_by },
                  function(data) {
                      if(data.error == 0) {
                          $('#modal_recommendation').jqmHide();
                          MM.Cart.updateItemsInCart(1);
                      } else {
                          alert(data.error); 
                      }
                  });
        return false;
    },
    
    loadRecommended: function(options) {
        $('#modal_recommendation #modal_recommendation_content').load(options.submit_url, { component: 'showRecommendation', recommended_id: options.recommended_id }, function() {
            $('#modal_recommendation').jqmShow();
            MM.UI.initializeFlowplayer('flowplayer_recommend');
        });
    },
    
    
    showHdAvailablePopup: function(asset_id, hd_price) {
        $('#modal_hdAvailable #hd_available_asset_id').val(asset_id);
        $('#modal_hdAvailable #hd_additional_price').text(hd_price);
        
        $('#modal_hdAvailable').jqmShow();
    },
    
    addItemFromHdAvailablePopup: function(with_hd, ajax_route) {
        MM.Cart.addItem({ submit_url: ajax_route,
                          asset_id:   $('#modal_hdAvailable #hd_available_asset_id').val(),
                          ipod_only:  0,
                          check_hd:   0,
                          with_hd:    with_hd,
                          callback:   function(options, data) {
                            $('#modal_hdAvailable').jqmHide();
                            $('#clip_buy').html(data.new_state);
                            if(data.new_state == 'Buy') { MM.Cart.updateItemsInCart(-1); } else { MM.Cart.updateItemsInCart(1); }
                          }
                        });
    },
    
    addItemFromClip: function(el_id) {
        
        if(el_id === undefined) {
            el = this;
            el_id = el.id;
        } else {
            el = $('#'+el_id);
        }
        
        options = {
                    callback: function(options, data) {
                        $('#clip_buy').html(data.new_state);
                        if(data.new_state == 'Buy') { MM.Cart.updateItemsInCart(-1); } else { MM.Cart.updateItemsInCart(1); }
                        return false;
                    }
        };
        
        MM.Cart.addItem(options, el_id);

        return false;
    },
    
    addItemFromIpodUpgradePopup: function(ipod_only) 
    {
        options = {
                callback: function(options, data) {
                    $('#modal_ipod_license').jqmHide();        
                    $('#clip_buy').html(data.new_state);
                    if(data.new_state == 'Buy') { MM.Cart.updateItemsInCart(-1); } else { MM.Cart.updateItemsInCart(1); }
                },
                ipod_only:    ipod_only
        };
        
        MM.Cart.addItem(options, 'clip_buy');
    },
    
    addItemFromNewsletterPreviewPopup: function()
    {
        options = {
                callback: function(options, data) {
                    $('#modal_newsletter_preview').jqmHide();
                }
        };
        
        MM.Cart.addItem(options, 'clip_buy');
       }
};


MM.Form = {
        submitProducerForm: function(submit_url) {
            // compile form values for request
            form_values = { name:   $('#pc_name').val(),
                            email:  $('#pc_email').val(),
                            message:  $('#pc_message').val(),
                            producer_id:   $('#pc_producer_id').val() };
            
            // remove all error formatting
            $('#pc_submit').attr('disabled', 'disabled').val('Sending...');
            
            $.getJSON(submit_url, form_values, function(data) {
                
                $('.pc_error').hide();
                $('#producer_contact_form input').removeClass('pc_input_error');
                
                if(data.success == 0) {
                    // has errors
                    $.each(data.errors, function(key, val) {
                        $('#pc_'+key+'_error').html(val).fadeIn(300);
                        $('#pc_'+key).addClass('pc_input_error');
                    });
                    
                    $('#pc_submit').attr('disabled', '').val('Send email');
                    
                } else {
                    // success
                    alert(data.message);
                    
                    $('#pcf_wrapper').hide();
                    $('#pcf_success').show();
                }
            });
        
            return false;
        },
        
        submitAjaxForm: function(submit_url, form_id, form_keys, success_callback) {
            
            return function(e) {
                original_submit_value = $(form_id + ' #submit').val();
                
                // compile form values object
                form_values = {};
                $.each(form_keys, function(key, val) { form_values[val] = ($(form_id + ' #' + val).attr('type') == 'checkbox') ? $(form_id + ' #' + val).attr('checked') : $(form_id + ' #' + val).val(); });
                
                // disable submit button until request completes
                $(form_id + ' #submit').attr('disabled', 'disabled').val('Loading...');
                
                
                $.post(submit_url, form_values, function(data) {
                    // remove error formatting
                    $(form_id + ' .mf_error').hide();
                    $(form_id + ' input, '+form_id+' select, '+form_id+' textarea').removeClass('mf_input_error');
                    
                    if(data.success == 0) {
                        // has errors
                        $.each(data.errors, function(key, val) {
                            $(form_id + ' #'+key+'_error').html(val).fadeIn(300);
                            $(form_id + ' #'+key).addClass('mf_input_error');
                        });
                        
                        $(form_id + ' #submit').attr('disabled', '').val(original_submit_value);
                        
                    } else {
                        $.each(form_keys, function(key, val) {
                            $(form_id + ' #' + val).val('');
                        });
                        $(form_id + ' #submit').attr('disabled', '').val(original_submit_value);
                        
                        success_callback(data);
                        return false;
                    }
                }, 'json');
                
                return false;
            };
        }
        
    };

    
MM.UI.DropdownMenu = {
    menu_timeout_ms:    500,
    menu_open_timer:    null,
    menu_close_timer:   null,
    active_menu_id:     null,
    
    open: function(div_class) {
    
        if(MM.UI.DropdownMenu.active_menu_id != div_class) {
            MM.UI.DropdownMenu.closeNow();
            MM.UI.DropdownMenu.active_menu_id = div_class;
            //$('.' + div_class + ' .dropdown').slideDown(200);
            $('.' + div_class + ' .dropdown').show();
            //$(document).bind('click', WALLY.UI.DropdownMenu.close);
            //$('#clickable_background_layer').show().click(function() { WALLY.UI.DropdownMenu.close(); });
        }
        
        //$('#' + WALLY.UI.DropdownMenu.active_menu_id + ' .top_most').css({'background-color': '#B7C6E9'});
        //$('#' + WALLY.UI.DropdownMenu.active_menu_id + ' .dropdown').css({'background-color': '#D8DFEA'});
        
        MM.UI.DropdownMenu.cancelCloseTimeout();
        MM.UI.DropdownMenu.menu_open_timeout = null;
    },
    
    closeNow: function() {
        if(MM.UI.DropdownMenu.active_menu_id) {
            $('.' + MM.UI.DropdownMenu.active_menu_id + ' .dropdown').hide();
        }
        MM.UI.DropdownMenu.cleanup();
    },
    
    close: function() {
        if(MM.UI.DropdownMenu.active_menu_id) {
            //$('.' + MM.UI.DropdownMenu.active_menu_id + ' .dropdown').hide(150); //.css({'background-color': '#DBE1EC'});
            $('.' + MM.UI.DropdownMenu.active_menu_id + ' .dropdown').hide(); //.css({'background-color': '#DBE1EC'});
        }
        MM.UI.DropdownMenu.cleanup();
    },
    
    cleanup: function() {
        //$('#' + WALLY.UI.DropdownMenu.active_menu_id + ' .top_most').css({'background-color': '#768FCA'});
        MM.UI.DropdownMenu.cancelCloseTimeout();
        MM.UI.DropdownMenu.active_menu_id = null;
        //$(document).unbind('click', WALLY.UI.DropdownMenu.close);
        //$('#clickable_background_layer').hide()
    },
    
    beginCloseTimeout: function() {
        MM.UI.DropdownMenu.menu_close_timer = window.setTimeout(MM.UI.DropdownMenu.close, MM.UI.DropdownMenu.menu_timeout_ms);
        //console.info('began close timeout');
    },
    
    cancelCloseTimeout: function() {
        if(MM.UI.DropdownMenu.menu_close_timer) {
            window.clearTimeout(MM.UI.DropdownMenu.menu_close_timer);
            MM.UI.DropdownMenu.menu_close_timer = null;
            //console.info('close timeout canceled');
        }
    },
    
    reset: function(div_class) {
        $('.' + div_class + ' .tab_link').unbind('mouseover');
        $('.' + div_class + ' .tab_link').unbind('mouseout');
        $('.' + div_class + ' .dropdown').unbind('mouseover');
        $('.' + div_class + ' .dropdown').unbind('mouseout');
        MM.UI.DropdownMenu.cleanup();
    },
    
    bindEvents: function(div_class) {
        $('.' + div_class + ' .tab_link').bind('mouseover', function() {
            MM.UI.DropdownMenu.menu_open_timeout = window.setTimeout(function(){ MM.UI.DropdownMenu.open(div_class); }, 200);
            //console.info('tab mouseover');
        });
        
        /*$('.' + div_id + ' #header_button').bind('click', function() {
            //$(document).unbind();
            //MM.UI.DropdownMenu.open(div_id);
            //$(document).bind('click', WALLY.UI.DropdownMenu.close);
        });*/
        
        $('.' + div_class + ' .tab_link').bind('mouseout', function() {
            if(MM.UI.DropdownMenu.menu_open_timeout != null) {
                window.clearTimeout(MM.UI.DropdownMenu.menu_open_timeout);
                MM.UI.DropdownMenu.menu_open_timeout = null;
            } else {
                MM.UI.DropdownMenu.beginCloseTimeout();
            }
            //console.info('tab mouseout');
        });
        
        $('.' + div_class + ' .dropdown').bind('mouseover', function() {
            MM.UI.DropdownMenu.cancelCloseTimeout();
            //console.log('mouseover');
        });
        $('.' + div_class + ' .dropdown').bind('mouseout', function() {
            MM.UI.DropdownMenu.beginCloseTimeout();
            //console.info('mouseout');
        });
    }
};


MM.Blog = {
    
    submitComment: function(blog_item_id) {
        
        ajax_route = $('#ajax_route').html();
        
        $.get(ajax_route,
               { component_module: 'blog', component: 'ajaxLeaveComment', item_id: blog_item_id, comment: $('#add_comment_'+blog_item_id+' textarea').val() },
               function(data) {
                   $('#item_comments_'+blog_item_id).prepend(data);
                   $('#add_comment_'+blog_item_id).hide();
                   MM.Blog.showComments(blog_item_id);
                   $('#add_comment_'+blog_item_id+' textarea').val('');
                   
                   MM.Blog.commentKeypressHandler(blog_item_id);
                   
               }, 'html');
    },
    
    toggleComments: function(item_id) {
        if($('#show_comments_link_'+item_id).html() == 'Show comments') {
            $('#show_comments_link_'+item_id).html('Hide comments');
            $('#item_comments_'+item_id).show();
        } else {
            $('#show_comments_link_'+item_id).html('Show comments');
            $('#item_comments_'+item_id).hide();
        }
    },
    
    showComments: function(item_id) {
        $('#show_comments_link_'+item_id).show();
        $('#show_comments_link_'+item_id).html('Hide comments');
        $('#item_comments_'+item_id).show();
    },
    
    countCommentCharacters: function(item_id) {
        $('#comment_char_remaining_'+item_id).text(500 - $('#add_comment_'+item_id+' textarea').val().length);
        $('#comment_char_overage_'+item_id).text($('#add_comment_'+item_id+' textarea').val().length - 500);
    },

    commentKeypressHandler: function (item_id) {
        MM.Blog.countCommentCharacters(item_id);
            
        if($('#add_comment_'+item_id+' textarea').val().length > 500) {
            $('#comment_remaining_message_'+item_id).hide();
            $('#comment_overage_message_'+item_id).show();
        } else {
            $('#comment_overage_message_'+item_id).hide();
            $('#comment_remaining_message_'+item_id).show();
        }
    },
    
    ajaxLoad: function (ajax_route, ajax_params) {
        
        ajax_params.component_module = 'blog';
        ajax_params.component = 'centerPane';
        
        $('#center_pane').load(ajax_route, ajax_params, function() {
            $('.blog_menu_items li a.showing').removeClass('showing');
            
            if(ajax_params.context == 'archive') {
                $('.blog_menu_items li a#month_'+ajax_params.month+'_'+ajax_params.year).attr('class', 'showing');
            
            } else if(ajax_params.context == 'producer') {
                $('.blog_menu_items li a#prod_'+ajax_params.username).attr('class', 'showing');
            }
        });
    }
};


MM.Newsletter = {
    
    ajaxLoad: function(ajax_route, newsletter_id) {
        $('#center_pane').load(
            ajax_route,
            { component_module: 'newsletter', component: 'centerPane', id: newsletter_id },
            function() {
                //MM.Newsletter.initializeFlash(newsletter_id);
                MM.UI.activateIE7Control();
                $('.nl_title').removeClass('nl_title_selected');
                $('#nl_title_'+newsletter_id).addClass('nl_title_selected');
                
            });
    },
    
    initializeFlash: function(newsletter_id) {
        return true;
        
      if (AC_FL_RunContent == 0) {
        alert("This page requires AC_RunActiveContent.js.");
      } else {
        AC_FL_RunContent(
          'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
          'width', '750',
          'height', '535',
          'src', 'fn',
          'quality', 'best',
          'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
          'align', 'middle',
          'play', 'true',
          'loop', 'false',
          'scale', 'showall',
          'wmode', 'window',
          'devicefont', 'false',
          'id', 'fn',
          'bgcolor', '#ffffff',
          'name', 'fn2',
          'menu', 'false',
          'allowFullScreen', 'false',
          'allowScriptAccess','sameDomain',
          'movie', 'fn',
          'FlashVars', 'nl='+newsletter_id,
          'salign', ''
          ); //end AC code
      }
    }

    
};

(function($) {
    $.fn.extend({
        
        applyDropdown: function(opts) {
            
            
            return this.each(function() {
                var o = opts;
                
                var obj = $(this);
                var dropdown = $(o.dropdown_selector);
                
                var mouseout_timeout_ms = 500;
                var close_timeout = null;
                
                var pub = {
                    
                    open: function() {
                        dropdown.show();
                        pub.end_close_timeout();
                        return false;
                    },
                    
                    close: function() {
                        dropdown.hide();
                    },
                    
                    begin_close_timeout: function() {
                        pub.end_close_timeout();
                        close_timeout = setTimeout(pub.close, mouseout_timeout_ms);
                    },
                    
                    end_close_timeout: function() {
                        clearTimeout(close_timeout);
                    }
                    
                };
                
                // bind obj events
                obj.bind('click', pub.open);
                obj.bind('mouseover', pub.end_close_timeout);
                obj.bind('mouseout', pub.begin_close_timeout);
                dropdown.bind('mouseover', pub.end_close_timeout);
                dropdown.bind('mouseout', pub.begin_close_timeout);
                
            });
            
        }
        
        
    });
})(jQuery);


$(document).ready(function() { 
    // bind ajax events
    MM.Ajax.bindAjaxEvents();
    
    
    // initialize jqModal windows
    //$('.jqmWindow').jqm({modal: true, overlay: 0, closeClass: 'jqmClose' });
    $('.jqmWindowModal').jqm({modal: true, overlay: 0, closeClass: 'jqmClose' });
    $('.jqmWindowPopup').jqm({modal: false, overlay: 1, closeClass: 'jqmClose' });
    
    // flowplayer
    MM.UI.initializeFlowplayer();
    
    // auto-activate flash video object for IE7
    //MM.UI.activateIE7Control();
    
    // dropdowns
    $('#gallery_sort_dropdown_button').applyDropdown({ dropdown_selector: '#gallery_sort_dropdown' });
    $('#gallery_category_dropdown_button').applyDropdown({ dropdown_selector: '#gallery_category_dropdown' });
    $('#producer_search_dropdown_box').applyDropdown({ dropdown_selector: '#producer_search_dropdown' });
    
});
