var bindings;
bindings = {


  /**************************************************************************************************** ALL ***/


  all: function() {

    // ensure there's no whitespace beneath the background image when the window gets too tall

    if (jQuery(window).height() > 950) {
      jQuery('body').css('background-position','50% bottom');
    }
    jQuery(window).unbind('resize');
    jQuery(window).bind('resize', function() {
      if (jQuery(this).height() > 950) {
        jQuery('body').css('background-position','50% bottom');
      } else {
        jQuery('body').css('background-position','50% -15px');
      }
    });

  },


  /**************************************************************************************** NON-APPLICATION ***/


  non_application: function() {

    // show a "latest news" qtip

    jQuery('ul#footer a#blog').closest('li').qtip({
      content: {
        text: "<a href='http://syphir.posterous.com/' id='latest_post'><b>Latest Post:</b> Age condition (finally) available! <small>(May 3)</small></a>",
        prerender: true
      },
      style: {
        name: 'blue',
        tip: { corner: 'bottomMiddle', size: { x:12, y:18 } },
        background: '#FFFFFF',
        border: { width: 1, radius: 3 },
        'font-size': '12px',
        textAlign: 'center',
        width: 330,
        padding: 8
      },
      position: {
        corner: { target: 'topMiddle', tooltip: 'bottomMiddle' }
      },
      show: { ready: true, when: { target: jQuery('#scapegoat'), event: 'mouseover' } },
      hide: { delay: 2592000000, when: 'inactive' }
    });
    
  },


  /*************************************************************************************************** HOME ***/


  login: function() {

    // clicking the "sign in to get started!" link should put the focus in the sign in box

    jQuery('a#sign_in').unbind('click');
    jQuery('a#sign_in').bind('click', function() {
      jQuery('input#user_login').focus();
      return false;
    });

    // submitting the login form checks for empty data

    jQuery('form#login_form').unbind('submit');
    jQuery('form#login_form').bind('submit', function() {
      var email = jQuery('input#user_login').val();
      if (common.trim(email) == '') {
        return false;
      }
    });

  },


  /*********************************************************************************************** PRODUCTS ***/


  products: function() {

    // highlight all the examples, so people know you can hover over them

    function animate_features(i, type, max) {
      if (i>=max) {
        setTimeout(function() { animate_features(0, type, max); }, 15000);
        return;
      }
      var total_time = 3600;
      jQuery('div#'+type+' ul.features li:eq('+i+')').animate({backgroundColor:'lightYellow'}, (total_time/max), 'swing', function() {
        animate_features(i+1, type, max);
        jQuery(this).animate({backgroundColor:'transparent'}, (total_time/max)*1.5, 'linear', function() {
          jQuery(this).css({backgroundColor:''});
        });
      });
    }
    animate_features(0, 'rules', 6);
    animate_features(0, 'smartpush', 3);

    // hover effects for Rules

    var rules_hover_timeout;

    jQuery('div#page_content.products div#rules.section ul.features li').unbind('mouseover');
    jQuery('div#page_content.products div#rules.section ul.features li').bind('mouseover', function() {
      var hover_title = jQuery(this).attr('hover_title');
      var $rules_pic = jQuery('div#rules_pic');
      if (hover_title == "arrival_time") {
        $rules_pic.stop().css({'background-position':'0px -260px'}).html('Your email should conform to <b>your</b> schedule.');
      } else if (hover_title == "reply_probability") {
        $rules_pic.stop().css({'background-position':'0px -520px'}).html('Focusing on what\'s important has never been so easy.');
      } else if (hover_title == "age") {
        $rules_pic.stop().css({'background-position':'0px -780px'}).html('Keep your inbox clean, organized, and clutter-free.');
      } else if (hover_title == "num_recipients") {
        $rules_pic.stop().css({'background-position':'0px -1040px'}).html('Avoid getting lost in the crowd.');
      } else if (hover_title == "delay") {
        $rules_pic.stop().css({'background-position':'0px -1300px'}).html('Your email should conform to <b>your</b> schedule.');
      } else if (hover_title == "smartpush") {
        $rules_pic.stop().css({'background-position':'0px -1560px'}).html('Never miss an important email.');
      } else {
        return;
      }
      clearTimeout(rules_hover_timeout);
    });

    jQuery('div#page_content.products div#rules.section ul.features li').unbind('mouseout');
    jQuery('div#page_content.products div#rules.section ul.features li').bind('mouseout', function() {
      rules_hover_timeout = setTimeout(function() {
        jQuery('div#rules_pic').css({'background-position':'0px 0px'}).text('');
      }, 250);
    });
    
    // hover effects for SmartPush

    var smartpush_hover_timeout;

    jQuery('div#page_content.products div#smartpush.section ul.features li').unbind('mouseover');
    jQuery('div#page_content.products div#smartpush.section ul.features li').bind('mouseover', function() {
      var hover_title = jQuery(this).attr('hover_title');
      var $smartpush_pic = jQuery('div#smartpush_pic');
      if (hover_title == "alerts") {
        $smartpush_pic.css({'background-position':'0px -325px'});
      } else if (hover_title == "sensitivity") {
        $smartpush_pic.css({'background-position':'0px -650px'});
      } else if (hover_title == "rules") {
        $smartpush_pic.css({'background-position':'0px -975px'});
      } else {
        return;
      }
      clearTimeout(smartpush_hover_timeout);
    });

    jQuery('div#page_content.products div#smartpush.section ul.features li').unbind('mouseout');
    jQuery('div#page_content.products div#smartpush.section ul.features li').bind('mouseout', function() {
      smartpush_hover_timeout = setTimeout(function() {
        jQuery('div#smartpush_pic').css({'background-position':'0px 0px'});
      }, 250);
    });
  },


  /************************************************************************************************ ACCOUNTS ***/


  accounts: function() {

    // expanding and collapsing rules

    jQuery('div#rules_list div.rule img, div#rules_list div.rule h3').unbind('click');
    jQuery('div#rules_list div.rule img, div#rules_list div.rule h3').bind('click', function() {
      var image = jQuery(this).closest('div.rule').find('img');
      var rule = jQuery(this).closest('div.rule');
      rule.find('div.details').slideToggle('slow', function() {
        if (image.attr('alt') == 'collapse rule') rule.find('a.delete_rule').fadeIn();
      });
      if (image.attr('alt') == 'expand rule') {
        image.attr('title','click to collapse').attr('src','/images/rules/collapse_rule.png').attr('alt','collapse rule');
      } else {
        image.attr('title','click to expand').attr('src','/images/rules/expand_rule.png').attr('alt','expand rule');
        rule.find('a.delete_rule').hide();
      }
    });

    // show the time zone form

    jQuery('a#show_tz_form').die('click');
    jQuery('a#show_tz_form').live('click', function() {
      jQuery(this).fadeOut('slow', function() {
        jQuery(this).remove();
      });
      jQuery('form#time_zone_form').slideDown('slow');
      return false;
    });

    // show the invite-a-friend form

    jQuery('a#show_inv_form').die('click');
    jQuery('a#show_inv_form').live('click', function() {
      jQuery(this).fadeOut('slow', function() {
        jQuery(this).remove();
      });
      jQuery('form#inv_form').slideDown('slow');
      return false;
    });

    // yft on click

    jQuery('a.mbdls_reference').die('click');
    jQuery('a.mbdls_reference').live('click', function() {
      common.flash(jQuery('div.option:first'));
      return false;
    });

    // qtip dialogs

    jQuery('a#create_rule.instructions').qtip({
      content: {
        text: "Your account doesn't have any rules in effect. Get started by creating a new rule, and by configuring your options to the right.",
        prerender: true
      },
      style: {
        name: 'blue',
        tip: { corner: 'topRight', size: { x: 18, y: 24 } },
        background: '#FFFFFF',
        border: { width: 1, radius: 4 },
        'font-size': '16px',
        width: 350,
        padding: 10
      },
      position: {
        corner: { target: 'bottomLeft', tooltip: 'topRight' }
      },
      show: { ready: true, when: { target: jQuery('#scapegoat'), event: 'mouseover' } },
      hide: { delay: 2592000000, when: 'inactive' }
    });

  },


  /*************************************************************************************************** TOUR ***/


  tour: function() {

    jQuery('a#tour_signup').unbind('click');
    jQuery('a#tour_signup').bind('click', function() {
      common.change_pane(4);
      return false;
    });

    jQuery('a.next_button').unbind('click');
    jQuery('a.next_button').bind('click', function() {
      var pane = parseInt(jQuery(this).closest('div.pane').attr('pane'));
      common.change_pane(pane + 1);
      return false;
    });

    jQuery('a.back_button').unbind('click');
    jQuery('a.back_button').bind('click', function() {
      var pane = parseInt(jQuery(this).closest('div.pane').attr('pane'));
      common.change_pane(pane - 1);
      return false;
    });

    jQuery('a.pane_selector_link').unbind('click');
    jQuery('a.pane_selector_link').bind('click', function() {
      var pane = parseInt(jQuery(this).attr('pane'));
      common.change_pane(pane);
      return false;
    });
  },


  /******************************************************************************************** SUGGESTIONS ***/


  suggestions: function () {

    // default 'suggestion' text in text boxes

    jQuery('input[suggestion]').unbind('blur');
    jQuery('input[suggestion]').bind('blur', function() {
      var textbox = jQuery(this);
      if (textbox.val().length == 0) {
        //textbox.val(textbox.attr('suggestion')).css({'color':'#AAAAAA', 'font-style':'italic', 'font-size':'12px'});
        textbox.val(textbox.attr('suggestion')).css({'color':'#AAAAAA', 'font-style':'italic'});
      } else if (textbox.attr('id') == 'user_login'
              && textbox.val() != textbox.attr('suggestion')
              && textbox.val().search('@') == -1) {
        textbox.val(textbox.val()+"@gmail.com");
      }
    });

    jQuery('input[suggestion]').unbind('focus');
    jQuery('input[suggestion]').bind('focus', function() {
      if (jQuery(this).val() == jQuery(this).attr('suggestion')) {
        jQuery(this).val('').css({'color':'', 'font-style':'', 'font-size':''});
      }
      jQuery(this).click();
    });

  },


  /************************************************************************************************** RULES ***/


  rules: function() {
    
    // tooltip for getting started by selecting step 1

    jQuery('ol.rules_navigation li.tooltip[step=1]').qtip({
      content: {
        text: "Click here to get started.",
        prerender: true
      },
      style: {
        name: 'blue', tip: { corner: 'bottomMiddle' }, border: { width: 1, radius: 4 }, 'background':'#FFFFFF', 'font-size': '14px', padding: 7
      },
      position: {
        corner: { target: 'topMiddle', tooltip: 'bottomMiddle' },
        adjust: { x: -30 }
      },
      show: { ready: true, when: { target: jQuery('#scapegoat'), event: 'mouseover' } },
      hide: { delay: 0, when: { target: jQuery('ol.rules_navigation li'), event: 'click' } }
    });

    // (DE)SELECTING a condition/action

    jQuery('div.rules_list a').unbind('click');
    jQuery('div.rules_list a').bind('click', function() {
      var option = jQuery(this);
      if (!option.hasClass('unimplemented') && !option.attr('disabled')) {
        option.toggleClass('selected');
        common.update_rules_area(jQuery(this).attr('key'), 'select');
      }
      return false;
    });

    jQuery('div.popup a.popup_remove').unbind('click');
    jQuery('div.popup a.popup_remove').bind('click', function() {
      var key = jQuery('div.selected_step div.popup').attr('key');
      jQuery('div.selected_step div.rules_list a[key='+key+']').click();
      return false;
    });

    // EDITING a condition/action

    jQuery('div.selected_step span.highlight').die('click');
    jQuery('div.selected_step span.highlight').live('click', function() {
      var key = (jQuery(this).attr('id') == 'coverage_highlight') ? 'coverage' : jQuery(this).closest('li').attr('key');
      if (jQuery(this).hasClass('inactive')) {
        jQuery('div.selected_step div.rules_list a[key='+key+']').click();
      } else {
        common.update_rules_area(key, 'edit');
      }
    });

    // making changes in the rules popup

    jQuery('div.popup input, div.popup select').unbind('change');
    jQuery('div.popup input, div.popup select').bind('change', function() {
      var key = jQuery('div.selected_step div.popup').attr('key');
      common.modify_selected_list(key);
    });

    // saving changes to the rules popup

    jQuery('div.popup input.popup_save').unbind('click');
    jQuery('div.popup input.popup_save').bind('click', function() {
      var key = jQuery('div.selected_step div.popup').attr('key');
      common.close_popup(key, true);
    });

    // closing the rules popup without saving changes

    jQuery('div.popup img.popup_close').unbind('click');
    jQuery('div.popup img.popup_close').bind('click', function() {
      var key = jQuery('div.selected_step div.popup').attr('key');
      common.close_popup(key, false);
    });

    jQuery('div.popup a.popup_cancel').unbind('click');
    jQuery('div.popup a.popup_cancel').bind('click', function() {
      var key = jQuery('div.selected_step div.popup').attr('key');
      common.close_popup(key, false);
      return false;
    });

    // navigating the steps of rule creation

    jQuery('ol.rules_navigation li').unbind('click');
    jQuery('ol.rules_navigation li').bind('click', function() {
      // hide the currently-selected step
      if (jQuery('div.selected_step div.popup')) {
        var key = jQuery('div.selected_step div.popup').attr('key');
        if (key) common.close_popup(key, false);
      }
      jQuery('div.selected_step').removeClass('selected_step');
      // show the newly-selected step
      var step_number = jQuery(this).attr('step');
      var step_div = jQuery('div.step[id=step'+step_number+']');
      step_div.addClass('selected_step');
      if (step_number==1 || step_number==2) common.make_scrollable(step_div.find("div.rules_list_wrapper"), step_div.find("div.rules_list"));
      // if it's the last step, modify the summary
      if (step_number == 3) {
        if (jQuery('div#step1 fieldset.chosen').length) {
          jQuery('div#final_conditions img').attr('src', '/images/status_complete.png').attr('alt', 'complete');
        } else {
          jQuery('div#final_conditions img').attr('src', '/images/status_incomplete.png').attr('alt', 'incomplete');
        }
        if (jQuery('div#step2 fieldset.chosen').length) {
          jQuery('div#final_actions img').attr('src', '/images/status_complete.png').attr('alt', 'complete');
        } else {
          jQuery('div#final_actions img').attr('src', '/images/status_incomplete.png').attr('alt', 'incomplete');
        }
      }
      // possibly display the submit button
      if (jQuery('div#step3 img[alt=complete]').length == 3) {
        jQuery('input#submit_rule').removeAttr('disabled').fadeIn('slow');
      } else {
        jQuery('input#submit_rule').attr('disabled','true').fadeOut('slow');
      }
    });

    // naming the rule

    jQuery('div#step3 input#rule_name').unbind('keyup');
    jQuery('div#step3 input#rule_name').bind('keyup', function() {
      // change image based on whether or not user has typed a name
      var val = jQuery(this).val();
      if ((val != "") && (val != jQuery(this).attr('suggestion'))) {
        jQuery('div#final_name img').attr('src', '/images/status_complete.png').attr('alt', 'complete');
      } else {
        jQuery('div#final_name img').attr('src', '/images/status_incomplete.png').attr('alt', 'incomplete');
      }
      // possibly display the submit button
      if (jQuery('div#step3 img[alt=complete]').length == 3) {
        jQuery('input#submit_rule').removeAttr('disabled').fadeIn('slow');
      } else {
        jQuery('input#submit_rule').attr('disabled','true').fadeOut('slow');
      }
    });

    // prevent the "enter" key from unintentionally submitting the entire form instead of just a popup (unless we're in the last textbox)

    jQuery('form#rules_container').unbind('keypress');
    jQuery('form#rules_container').bind('keypress', function(e) {
      if (e.keyCode == 13) {
        var target = jQuery(e.target);
        if (target.attr('name') == "rule[name]") {
          jQuery('form#rules_container').submit();
        } else {
          var popup = target.closest('div.popup');
          if (popup.length) {
            common.modify_selected_list(popup.attr('key'));
            popup.find('input.popup_save').click();
          }
        }
        return false;
      }
    });

    jQuery('div.popup').unbind('keypress');
    jQuery('div.popup').bind('keypress', function(e) {
      if (e.keyCode == 13) {
        var popup = jQuery(this);
        if (popup.length) {
          common.modify_selected_list(popup.attr('key'));
          popup.find('input.popup_save').click();
        }
        return false;
      }
    });

    // submitting the rules wizard form

    jQuery('form#rules_container').unbind('submit');
    jQuery('form#rules_container').bind('submit', function() {
      var this_form = jQuery(this);
      // Ensure that conditions and actions have been chosen.
      if (jQuery('div#step1').find('fieldset.chosen').length == 0) {
        alert("Please choose at least one condition for your rule.");
        jQuery('ol.rules_navigation li[step=1]').click();
        return false;
      }
      if (jQuery('div#step2').find('fieldset.chosen').length == 0) {
        alert("Please choose at least one action for your rule.");
        jQuery('ol.rules_navigation li[step=2]').click();
        return false;
      }
      // Ensure that the rule was given a name.
      if ((jQuery('input#rule_name').val() == '') || (jQuery('input#rule_name').val() == jQuery('input#rule_name').attr('suggestion'))) {
        alert("Please give your rule a name.");
        jQuery('ol.rules_navigation li[step=3]').click();
        jQuery('input#rule_name').focus();
        return false;
      }
      // Remove unused conditions/actions from the form.
      this_form.find('fieldset').each(function() {
        if (!jQuery(this).hasClass('chosen') && (jQuery(this).attr('id') != 'coverage')) jQuery(this).remove();
      });
    });

    // conditions test-search

    jQuery('div#step1 input#test_search').unbind('click');
    jQuery('div#step1 input#test_search').bind('click', function() {
      // close any open popup
      if (jQuery('div.selected_step div.popup').attr('key')) common.close_popup();
      // show test-search box loading
      var loading_html = '<img title="close" src="/images/rules/popup_close.png" class="popup_close" alt="close" />'
                       + '<h3>Search Results</h3>'
                       + '<div class="clear"></div>'
                       + '<p class="subheader"><img src="/images/rules/searching.gif" /></p>';
      jQuery('div#matching_emails').html(loading_html).fadeIn();
      // perform search using ajax
      var conditions = common.test_search();
      new Ajax.Request('/accounts/perform_search/' + conditions, {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + AUTH_TOKEN,
        onComplete:function(request) {
          jQuery('div#matching_emails').html(request.responseText);
        }
      });
    });

    // closing the test search results

    jQuery('div#matching_emails img.popup_close').die('click');
    jQuery('div#matching_emails img.popup_close').live('click', function() {
      jQuery('div#matching_emails').hide();
    });

    // clicking the text box for a new label should select the corresponding radio button; same with the select box

    jQuery('input[name=rule\\[actions\\]\\[label_3\\]]').unbind('click');
    jQuery('input[name=rule\\[actions\\]\\[label_3\\]]').bind('click', function() {
      jQuery('input[name=rule\\[actions\\]\\[label_1\\]][value=new]').click();
    });

    jQuery('select[name=rule\\[actions\\]\\[label_2\\]]').unbind('click');
    jQuery('select[name=rule\\[actions\\]\\[label_2\\]]').bind('click', function() {
      jQuery('input[name=rule\\[actions\\]\\[label_1\\]][value=existing]').click();
    });

  },


  /************************************************************************************* RULES AND ADMIN CP ***/


  rules_and_admin_cp: function() {

    // expanding and collapsing rules

    jQuery('div#rules_list div.rule img, div#rules_list div.rule h3').unbind('click');
    jQuery('div#rules_list div.rule img, div#rules_list div.rule h3').bind('click', function() {
      var image = jQuery(this).closest('div.rule').find('img');
      var rule = jQuery(this).closest('div.rule');
      rule.find('div.details').slideToggle('slow', function() {
        if (image.attr('alt') == 'collapse rule') rule.find('a.delete_rule').fadeIn();
      });
      if (image.attr('alt') == 'expand rule') {
        image.attr('title','click to collapse').attr('src','/images/rules/collapse_rule.png').attr('alt','collapse rule');
      } else {
        image.attr('title','click to expand').attr('src','/images/rules/expand_rule.png').attr('alt','expand rule');
        rule.find('a.delete_rule').hide();
      }
    });

  },


  /*********************************************************************************************** ADMIN CP ***/


  admin_cp: function() {

    // auto-collapse metrics; clicking the h3 will show them
    jQuery('div[section]').hide();
    jQuery('h3[section]').unbind('click');
    jQuery('h3[section]').bind('click', function() {
      var section = jQuery(this).attr('section');
      jQuery('div[section='+section+']').toggle();
    });

    // clear tables

    jQuery('a.clear_link').die('click');
    jQuery('a.clear_link').live('click', function() {
      var this_link = jQuery(this);
      if (!this_link.hasClass('disabled')) {
        this_link.addClass('disabled');
        var table = this_link.attr('table');
        var account_id = this_link.attr('account_id');
        new Ajax.Request('/admin/clear_table/?id=' + account_id + '&table=' + table, {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + AUTH_TOKEN,
          onComplete:function(request) {
            if (request.responseText == 'success') {
              jQuery('span#' + table + '_count').text("0");
            } else {
              alert(request.responseText);
            }
            this_link.removeClass('disabled');
          }
        });
      }
      return false;
    });

    // count labels

    jQuery('a#count_labels').die('click');
    jQuery('a#count_labels').live('click', function() {
      var this_link = jQuery(this);
      if (!this_link.hasClass('disabled')) {
        this_link.addClass('disabled');
        var account_id = jQuery(this).attr('account_id');
        new Ajax.Request('/admin/count_labels/' + account_id, {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + AUTH_TOKEN,
          onComplete:function(request) {
            jQuery('#label_count').text(request.responseText);
            this_link.removeClass('disabled');
          }
        });
      }
      return false;
    });

    // delete labels

    jQuery('a#remove_labels').die('click');
    jQuery('a#remove_labels').live('click', function() {
      var this_link = jQuery(this);
      if (!this_link.hasClass('disabled')) {
        this_link.addClass('disabled');
        var account_id = jQuery(this).attr('account_id');
        new Ajax.Request('/admin/remove_labels/' + account_id, {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + AUTH_TOKEN,
          onComplete:function(request) {
            if (request.responseText != 'success') {
              alert(request.responseText);
            } else {
              jQuery('#label_count').text("...?");
            }
            this_link.removeClass('disabled');
          }
        });
      }
      return false;
    });

    // remove alias

    jQuery('a.remove_alias').die('click');
    jQuery('a.remove_alias').live('click', function() {
      var this_link = jQuery(this);
      if (!this_link.hasClass('disabled')) {
        this_link.addClass('disabled');
        var account_id = this_link.attr('account_id');
        var alias = this_link.attr('alias');
        new Ajax.Request('/admin/remove_alias/?id=' + account_id + '&alias=' + alias, {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + AUTH_TOKEN,
          onComplete:function(request) {
            if (request.responseText != 'success') {
              alert(request.responseText);
              this_link.removeClass('disabled');
            } else {
              this_link.fadeOut(500, function() {
                this_link.remove();
              });
            }
          }
        });
      }
      return false;
    });

    // add/remove invitations

    jQuery('a.change_invites').die('click');
    jQuery('a.change_invites').live('click', function() {
      var this_link = jQuery(this);
      var act = this_link.attr('act');
      var account_id = this_link.attr('account_id')
      if (!this_link.hasClass('disabled')) {
        this_link.addClass('disabled');
        var table = this_link.attr('table');
        var account_id = this_link.attr('account_id');
        new Ajax.Request('/admin/change_invites/?id=' + account_id + '&act=' + act, {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + AUTH_TOKEN,
          onComplete:function(request) {
            if (request.responseText == 'error') {
              alert('error');
            } else {
              jQuery('span#invites_count').text(request.responseText);
            }
            this_link.removeClass('disabled');
          }
        });
      }
      return false;
    });
  }
};
