// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

//  jQuery

var NAG = {  

    // add roles for ARIA accessibility stuff for later
    addRoles: function(e) {
      jQuery('#hd').attr('role', 'banner');
      jQuery('#bd').attr('role', 'main');
      
    },
    add_RTE: function(text_target, rte_width, rte_height) {
      
      var Dom = YAHOO.util.Dm,
      Event = YAHOO.util.Event;
        //The Editor config
        var myConfig = {
            dompath: true,
            height: rte_height,
            // this is needed to filter out the crap that MS Word drops in
            filterWord: true,
            width: rte_width,
            focusAtStart: false,
            handleSubmit: true,
            toolbar: {

              buttons: [
              { group: 'textstyle', label: 'Font Style',
                buttons: [
                  { type: 'push', label: 'Bold', value: 'bold' },
                  { type: 'push', label: 'Italic', value: 'italic' },
                  { type: 'push', label: 'Underline', value: 'underline' }
                ]
              },
              { type: 'separator' },
              { group: 'insertitem', label: 'Insert Item',
                buttons: [
                  { type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: false }
                ]
              }
              ]
            }
        };
        myEditor = new YAHOO.widget.Editor(text_target, myConfig);
        // after editor has been painted onto the page, scroll to where it should be
        myEditor.render();
    },
    
    comment_switcher: function(elem1, elem2) {
      var col1, col2;
     // take first classname from tab
      jQuery(elem1, elem2).click(function(e) {
          e.preventDefault();
          col1 = e.currentTarget.className;
      });

      jQuery(elem2).click(function(e) {
          e.preventDefault();
          col2 = e.currentTarget.className;
      });
    },
    
    thoughtSwitcher: function() {
      
      jQuery(document).ready(function() {
        
        // remove dividing style
        jQuery('ul#suggestions').css('borderTop', 'none');
    
        jQuery('#tab_switcher > .comments a, #tab_switcher > .suggestions a, #tab_switcher > .stories a').click(function(e) {
          e.preventDefault();
          // hide based on ID
          jQuery('#comments, #suggestions, #stories, #comments_info, #suggestions_info, #stories_info, #comment_info').hide();
          
          // get id out of the target link
          var showMe = e.currentTarget.parentNode.className;
          if (showMe == 'comments'){

            jQuery('ul#tab_switcher').css('backgroundPosition', '-3px -16px');
          } else {
            jQuery('ul#tab_switcher').css('backgroundPosition', '-3px -87px');
          }          
          // use extracted id to show element again
          debug.info("#" + showMe + ", #" + showMe + "_info");
          jQuery("#" + showMe + ", #" + showMe + "_info").show();
        });
      });
    
    },
    
    sign_InSwitch: function() {
        // set min height to avoid ugly reflow, and hide 'sheet two'
        jQuery('.wrap').css('minHeight', 370);
        jQuery("#form_submit").append('<a class=" button next" href="#sign_up_one">Next step</a> <a class="button back" href="#sign_up_one">Back</a>');
        jQuery('#sign_up_two, #Submit, #form_submit a.back').hide();
        jQuery("#form_submit a.next").click(function(e) {
          // this validation step won't let you move forward to the next 'sheet' until these steps are valid
          if ( jQuery('#user_user_name').valid() && 
               jQuery('#user_first_name').valid() &&
               jQuery('#user_last_name').valid() &&
               jQuery('#user_email_name').valid() &&
               jQuery('#user_email_domain').valid() &&
               jQuery('#user_password').valid() &&
               jQuery('#user_password_confirmation').valid())
          {
            e.preventDefault(); 

            jQuery('#sign_up_one, #form_submit a.next').fadeOut("normal", function() {
              jQuery('#sign_up_two, #Submit, #form_submit a.back').fadeIn();
              jQuery('#form_submit a.back').click(function() {
                jQuery('#sign_up_two, #Submit, #form_submit a.back').fadeOut('normal', function() {
                  jQuery('#sign_up_one, #form_submit a.next').fadeIn();
                });

              });
            });
          }
        });        
        

    },
    
    addAccordion: function() {
      jQuery('#my_nag_menu').accordion({
            header: 'h4'
      });
    },
    
    new_thought_switcher: function() {
      jQuery('#category ul li input:radio').click(function(e) {
        // move background sprite to correct position to show relevant image, 
        // depending on what radio button was clicked
        switch (e.currentTarget.id){
        case 'thought_thought_type_wish' : $('#category ul').css({backgroundPosition: "450px -389px"}); 
        break;
        case 'thought_thought_type_rant' : $('#category ul').css({backgroundPosition: "450px -464px"});
        break;
        //default to showing an idea, 
        default : $('#category ul').css({backgroundPosition: "450px -538px"});
        break;
        }
        /* idea is at -390px*/
         /* rant is at -538*/
         /* wish is at -464*/
        });
    },
    
    top_nagger_switcher: function() {
      // on hover, set z-index of others to less than 5.
      // then this element to 10
      jQuery('#active_users ul > li > img').hover(function() {
        // hide others
        jQuery(this).parent().parent().find('li > div.user_content').hide();
        // show the relevant name for the user
        jQuery(this).parent().find('div.user_content').show();
      }, function() {
      });
      jQuery('#active_users ul > li > img').eq(0).trigger('mouseover');
    },
    
    flash_overlayer: function() {
      if (jQuery('#flash_notice').length) {
      jQuery('#overlay').css('opacity',0);
      jQuery('#overlay .bd').empty();
      jQuery('#flash_notice').appendTo('#overlay .bd');
      jQuery('#overlay').jOverlay();
      jQuery('#overlay').animate({opacity:1}, 500);
      }
    }, 
    
    increment_members: function(number, element) {
      // take the html
      var displayed_label = $(element).text().split(': ')[0];
      var displayed_number = $(element).text().split(': ')[1];
      // parse for the number
      displayed_number = parseInt(displayed_number);
      // increment the number
      displayed_number += number;
      // put the number back onto the page
      $(element).text([displayed_label,displayed_number].join(' '));
    },

    sign_in_validation : function() {
      // add validation against username formatting
      $.validator.addMethod("alphanumeric_test", function(value, element) { 
        return this.optional(element) || (/[0-9a-zA-Z_]+/).test(value); 
      }, "Please only use letters and numbers for your nag name");
      // TODO run check if username is available

      $('form#new_user').validate({
        rules: {
          'user[user_name]': {
            alphanumeric_test:true,
            required:true,
            maxlength:15
          },
          'user[first_name]': {required: true},
          'user[last_name]': {required:true},
          'user[email_name]': {required:true},
          'user[email_domain]': {required:true},
          'user[password]': {
            required:true,
            minlength:4
          },
          'user[password_confirmation]': {
            required:true,
            minlength:4
          }
        },
        messages: {
          'user[user_name]': {
            alphanumeric_test: "Please only use letters and numbers for your nag name",
            required: "You need a nag name to start nagging!"
          }
        }
      });
    },
    
    replace_image: function(e) {
      // debug.info('removing image on ' + $('#avatar_image li:last'));
      $('#avatar_image label.upload_description').append('<a class="clear_upload" href="#>Clear this upload?</a>');
      debug.info('fresh load form stored');
      NAG.freshImageUpload = $('#avatar_image li:last').clone();
      $('a.clear_upload').livequery("click", function() {
      debug.info('cleared image');
      $('#avatar_image li:last').remove();
      debug.info('adding clearer one');
      $('#avatar_image ').append(NAG.freshImageUpload);
      
      });
    },

    confirm_create_action: function() {
      $('.create_action').click(function(e) {
        debug.info('Standard behaviour stopped: ' + e.isDefaultPrevented());
        e.preventDefault();
        // clear overlay contents
        jQuery('#overlay').css('opacity',0);
        jQuery('#overlay .bd').empty();
        // add copy to confirm create action
        jQuery('<h2>Great!</h2><h2>You\'re about to to turn this suggestion into an action that other people can do.</h2><ul class="form_actions"></ul>').appendTo('#overlay .bd');
        debug.info(jQuery(this).closest('form'));
        jQuery(this).clone().wrap('<li></li>').addClass('confirm').appendTo('#overlay .bd ul');
        debug.info('Confirm class added: ' + jQuery(this).hasClass('true'));
        jQuery('#overlay .bd ul').prepend('<li class="cancel"><a href="#">Cancel</a></li>');
        
        // then display overlay
        jQuery('#overlay').jOverlay();
        jQuery('#overlay').animate({opacity:1}, 500);

        // allow cancel out
        
        // then allow ajax post to go to next page
        
      });
    }
  };

$(document).ready(function() {

  // add pngfix for IE6
  $('.pngfix').pngFix();
  
  // turn flash messages into overlays
  NAG.flash_overlayer();
  
  (function($) {

      // I've commented this out for now, because I was getting strange results with POSTING
    function register_ajax_links() {
      $("a.ajax_post").livequery("click", function(e) {
        e.preventDefault();
        $.ajax({url: this.href, type: "POST", dataType: "script"});
      });

      $("input.ajax_post").livequery("click", function(e) {
        e.preventDefault();
        $.ajax({url: $(this).closest("form").get(0).action, data: $(this).closest('form').serialize(), type: "POST", dataType: "script"});
      });

      $("input.ajax_delete").livequery("click", function(e) {
        e.preventDefault();
        $.ajax({url: $(this).closest("form").get(0).action, data: $(this).closest('form').serialize(), type: "DELETE", dataType: "script"});
      });

      // added this in until we can get ajax requests to work

      $("a.ajax_get").livequery("click", function(e) {
        e.preventDefault();
        $.ajax({url: this.href, type: "GET", dataType: "script"});
      });
      
      
      // adding in to show interaction
      $("div.invite a").livequery("click", function(e) {
//          console.log('starting the ill do it animation');
          $('div.invite a').fadeOut('medium', function() {
            $('div.thats_great').slideUp('medium', function() {
  //              console.log('appending, then sliding down');
                $('#nag_someone_holder').appendTo('#overlay .bd');
                $('#nag_someone_holder').slideDown();
            });            
          });
          e.preventDefault();
      });

    }

    function register_ive_done_it() {
        $("li.ive_done_it a").livequery("click", function(e) {
          e.preventDefault();
          $('#overlay').css('opacity',0);
          $('#overlay .bd').empty();
          $("#ive_done_it").clone().appendTo('#overlay .bd');
          $('#overlay').jOverlay();
          $('#overlay').animate({opacity:1}, 500);
      });
    }
  
    function register_nag_someone_else() {
      $("li.invite a").livequery("click", function(e) {
        e.preventDefault();
        $('#overlay').css('opacity',0);
        $('#overlay .bd').empty();
        $('div#invite_form').clone().appendTo('#overlay .bd');
        $('#overlay').jOverlay();
        $('#overlay').animate({opacity:1}, 500);
      });
    }


    function register_revealer_links() {
      $("a.revealer").livequery("click", function(e) {
          $('.thats_great').slideUp();
          $('a.revealer').hide('slow');
          e.preventDefault();
          $($(this).attr("href")).show();
      });
    }

    function register_email_adder() {
      $("a.add_more").livequery("click", function(e) {
        if (($('#recipients').hasClass('scrollbar') == false) && ($('.name_address').length > 3) ){
           $('#recipients').css({'overflow': 'auto', 'max-height': '400px'});
          $('#recipients').addClass('scrollbar');
        }
        $('#invite_form .name_address:last').clone().hide().insertAfter('#invite_form .name_address:last').slideDown('medium', function() {
        $('#invite_form .name_address:last span.remove a').fadeIn('medium');
      });
      $.center('#jOverlayContent');
      e.preventDefault();
      });
      $("span.remove a").livequery("click", function(e) {
        // walk up the dom to the nearest enclosing email/address holder
        $(this).closest('div.name_address').slideUp('medium', function() {
          $(this).remove();
          $.center('#jOverlayContent');
          e.preventDefault();
        });
      });
    }

    function register_overlay_close_links() {
      $("a.overlay_closer").livequery("click", function(e) {
        e.preventDefault();
        $.closeOverlay();
      });
    }

    function register_initially_hidden() {
      $(".initially_hidden").livequery(function() {
        $(this).hide();
        $(this).removeClass("initially_hidden");
      });
    }

    function register_add_a_story_link() {
      $("a.add_a_story").livequery("click", function(e) {
        $.closeOverlay();
      });
    }

    function register_inappropriate_link() {
      $("a.flag_for_admin").livequery("click", function(e) {
        $('#overlay .bd').empty();
        $("#overlay .bd").prepend($(this).siblings().find("div.inappropriate_overlay").html());
        $("#overlay").css("opacity", 100);
        $("#overlay").jOverlay();
      });
    }
    function append_activity_paginators () {
      // paginators are here because they make no sense without javascript
      if ($('.show_accounts').length || $('.pages_search').length ) {
        $('<ul id="paginator" class="clearfix"><li class="activities" id="activities_prev"><a href="">Previous</a></li><li class="activities" id="activities_next"><a href="">Next</a></li></ul>').insertAfter('#listing .first');
      // $('.activities_page').each(function(index) {
      // 
      //         $(this).addClass('page_' + (index + 1));
      //         $('<li class="activities"><a href="#">' + index + '</a></li>').addClass('trigger_' + index).addClass('trigger').insertBefore('li#activities_next');
      // 
      //       });
      //       $('li.trigger a').each(function(index) {
      //         $(this).click(function(e) {
      //           e.preventDefault();
      //           $('div.activities_page').hide();
      //           $('div.page_' + (index + 1)).show();
      //         });
      // 
      //       });
      }            
    }
    function check_visibility_of_paginator() {
      
      // show both paginators
      $("#activities_prev, #activities_next").show();      
      // then hide the prev button on page one
      if(NAG.pagination_count == 0){
        $("#activities_prev").hide();
      }
      // and hide the next  button on the last page
      if((NAG.pagination_count + 1) == $('.activities_page').length){
        $("#activities_next").hide();
      }
    }

    function register_account_pagination() {
      NAG.pagination_count = 0;
      debug.info("page count: " + $('.activities_page').length)
      debug.info("page counter: " + NAG.pagination_count)
      // chainging these two together makes IE7 skip showing any of the pages
      $(".activities_page").hide();
      $(".activities_page:first").show();
      check_visibility_of_paginator();

      // pagination
      $("#activities_prev").click(function(e) {
        e.preventDefault();
        NAG.pagination_count --;
        debug.info("page counter: " + NAG.pagination_count)
        debug.info("total pages: " + $('.activities_page').length)        
        $(".activities_page:visible").hide();
        $(".activities_page").eq(NAG.pagination_count).show();
        check_visibility_of_paginator();
      });
      $("#activities_next").click(function(e) {
        e.preventDefault();
        NAG.pagination_count ++;
        debug.info("page counter: " + NAG.pagination_count);
        debug.info("total pages: " + $('.activities_page').length);
        $(".activities_page:visible").hide();
        $(".activities_page").eq(NAG.pagination_count).show()        
        check_visibility_of_paginator();
      });
    }

    // now activate all the livequery listeners 
    
    $(function(){
      register_ajax_links();
      register_revealer_links();
      register_overlay_close_links();
      register_initially_hidden();
      register_email_adder();
      register_nag_someone_else();
      register_add_a_story_link();
      register_inappropriate_link();
      append_activity_paginators();
      register_account_pagination();
    });
  })(jQuery);
  if ($('#nag_toolbar').length){
    // add accordion to the sidebar
    NAG.addAccordion();
  }
  
  var ticker_count;
  var ticker_interval;

  $(document).ready(function(){
    // set position for animation
    $("ul#update_ticker li").css('position', 'absolute');
    
    // count number of updates to cycle through
    ticker_count = $("ul#update_ticker li").size();
    
    $("ul#update_ticker li").each(function(index) {
      $(this).css('left', ( (index * 200) - 200) );
    });

    ticker_interval = setInterval(headline_rotate,30000); //time in milliseconds
    $('#news_ticker').hover(function() {
      clearInterval(ticker_interval);
    }, function() {
      ticker_interval = setInterval(headline_rotate, 30000); //time in milliseconds
      headline_rotate();
    });
  });

  function headline_rotate() {
    // put first update to the back, ready for next cycle
    el = $("ul#update_ticker li").eq(0).remove();
    el.css('opacity', 0);
    el.css('left', ticker_count * 200 );
    el.appendTo("ul#update_ticker");
    el.css('opacity', 1);

    $("ul#update_ticker li").each(function(index) {
      $(this).animate({'left': ( (200 * index) - 200 ) }, 'slow', 'linear');
    });

  }
  
  if ($('.accounts_edit').length) {
    debug.info('adding the upload clear box');
    NAG.replace_image();
  }
  
  
  // Caretaker methods to fix formatting on focus on fields
  $('input.text').focus(function(e) {
    $(this).css({color: '#111', fontStyle: 'normal'});
  });
    // hide labels and populate inputs with search
    $('input#nav_search').attr('value', "Search");  
    $('input#nav_search, input#search').focus(function(e) {
      $(this).attr('value', '');
    });
  
    // clear the title from the input field on javascript on focus
      $('#title').focus(function(e) {
        if ($('#title').attr('value') == 'Title') {
        $(this).attr('value', '');
        }
      });
      
    // adjust styles on sign in box:
    // this should only clear the sign in box
    if ($('form#new_user_session').length) {
    $('form#new_user_session label:not(".remember_me label")').hide();
    $('input#user_session_email').attr('value', "Email");
    $('input#user_session_email').focus(function(e) {
      if ($(this).attr('value') == 'Email') {
        $(this).attr('value', '');
      }      
    });
    $('input#user_session_password').focus(function(e) {
      if ($(this).attr('value') == 'Password') {
        $(this).attr('value', '');      
      }
    });
    
    }

  // hide any js_hidden elements 
  $('.js_hidden').hide();

  // Add thought type switcher
  NAG.new_thought_switcher();
  


  // add rich text editor for nested_comments section
  if ($('body.thoughts_show')) {
  // if (console) {console.log('adding the rte');} 
    $('ul.suggestion_comments').hide();
    
        
        
    // add on click handler when p.expand_comments is clicked
      $('.expand_comments').wrap('<a href="#"></a>');
      $('.expand_comments').click(function(e) {
         $(this).closest('li.comment').find('ul.suggestion_comments').slideToggle();
         e.preventDefault();
      });
  }

  // Add the rich text editor if it's needed on the page, and the required objects exist
  if ($('#new_content').length && YAHOO.util.Event && YAHOO.util.Dom) {
  // if (console) {console.log('adding the rte');}
    $('#title').attr('value', 'Title');
    NAG.add_RTE('new_content', '517px', '414px');
  }


  // add rich text editor for actions section
  if ($('.new_suggestion').length && YAHOO.util.Event && YAHOO.util.Dom) {
  // if (console) {console.log('adding the rte');} 
    $('#title').attr('value', 'Title');
    NAG.add_RTE('suggestion_description', '517px', '250px');
  }
 
  // add rich text editor for stories section
  if ($('#new_story').length && YAHOO.util.Event && YAHOO.util.Dom) {
  // if (console) {console.log('adding the rte');} 
    NAG.add_RTE('story_story', '420px', '250px');
  }  
 
  // add rich text editor for comments section
  if ($('#comments form.new_comment').length && YAHOO.util.Event && YAHOO.util.Dom){
  // if (console) {console.log('adding the rte');} 
    $('#title').attr('value', 'Title');
    rte_target = $('ul.comments .comment_form form textarea').attr('id');
    $('ul.comments .comment_form form textarea').attr('id', rte_target+'_yui');
//    alert($('ul.comments .comment_form form textarea').attr('id'));
    NAG.add_RTE('comment_comment_yui', '415px', '250px');
    $('#comment_comment_yui_container').css('marginLeft', '110px');
  }
 
  // add switcher on thoughts page between suggestions and comments, then trigger the first click to show suggestions
  if ($('#tab_switcher').length) {
    NAG.thoughtSwitcher();
    if ($('li.suggestions a').length) {$('li.suggestions a').trigger('click');}
    // show comments by default, not stories
    if ($('li.stories a').length) {$('li.comments a').trigger('click');}

    // set convenience variable
    var anchor = document.location.href.split('#')[1];
    anchor = '#' + anchor;
    // if an anchor is in the comments tab, click the comments tab to show it, then scroll to it
    if ($('body.thoughts_show').length && $(anchor).parent().hasClass('comments')) {
        $('li.comments a').trigger('click');
        $.scrollTo(anchor);
      } else {
      //default to showing the suggestions
      $(anchor).closest('ul#suggestions > li.bubble').find('.suggestion_comments').slideDown('fast', function() {
      $.scrollTo(anchor);
      });
    }    
  }

  NAG.top_nagger_switcher();

  // this should only be called on the sign in page
  if ($('body.users').length && $('body.new').length) {
    NAG.sign_InSwitch();
    NAG.sign_in_validation();
  }
  
  // check for location bar having thoughts
  // then for location bar having comment
  
  //add placeholder for the Nag Guide

  NAG.confirm_create_action();

  if ($('body.actions_show').length){
    $('h4.explanation').eq(0).append('<div class="more_rant toggle"><p>More..</p></div>');
    $('.wrap').eq(0).hide();
    $('<div class="show_less"><a href="">Less...</a></div>').insertAfter('.wrap .thought h2').eq(0);

    $('div.show_less').click(function(e) {
      debug.info('show_less clicked'); 
      e.preventDefault();     
      $(this).closest('.wrap').slideToggle('400');
      $(this).parent().parent().prev().find('div.toggle:visible').fadeOut();
      $(this).parent().parent().prev().find('div.toggle:hidden').fadeIn();
    });
    $('h4.explanation').click(function(e) {
      debug.info('clicked');
      e.preventDefault();
      $(this).next().slideToggle('400');
      $(this).find('div.toggle:visible').fadeOut();
      $(this).find('div.toggle:hidden').fadeIn();
    });
  }

  if ($('body.actions_create').length || $('body.actions_new').length){
   debug.log('hiding the wraps')

   $('h4.explanation').eq(0).css('cursor', 'pointer').append('<div class="more_rant toggle"><p>More..</p></div>');
   $('h4.explanation').eq(1).css('cursor', 'pointer').append('<div class="more_suggestion toggle"><p>More...</p></div>');

   $('<div class="show_less"><a href="#">Less...</a></div>').insertAfter('.wrap .thought h2, .wrap .suggestion h2 ').eq(0);

   $('div.show_less').click(function(e) {
     debug.info('show_less clicked');   
      e.preventDefault();
     $(this).closest('.wrap').slideToggle('400');
     $(this).parent().parent().prev().find('div.toggle:visible').fadeOut();
     $(this).parent().parent().prev().find('div.toggle:hidden').fadeIn();
   });

   $('.wrap').eq(0).hide()
   $('.wrap').eq(1).hide()
   $('h4.explanation').click(function() {
    debug.info('show less clicked')
    $(this).next().slideToggle('400');
    $(this).find('div.toggle:visible').fadeOut();
    $(this).find('div.toggle:hidden').fadeIn();
   }); 
  }
  

});
