/**
* Frontend Javascripts
*/
 
/**
* Unobtrusive Javascript
* - Keep the views clear of javascripts by 
*   working on the DOM when ready
*/
$(document).ready(function() {
  
  // handle any user functionality
  userNotAuthed();
  userApplication();
  
  // handle submissions/reviews
  periods();
  
  // handle comment/boards functionality
  comments();
  boards();
  
  // handle autocompleting fields
  suggestField();
  
  // handle tabbed pages
  tabbed();
  
  // handle Top Report Cards
  topReportCards();
  
  // handle Top Chart
  topChart();
  
  // handle Review Process Question Descriptions
  reviewQuestionDescriptions();
  
  // hoverable elements
  $('.hoverable').mouseover(function() {
    $(this).fadeTo('fast', 0.5);
  }).mouseout(function() {
    $(this).fadeTo('fast', 1);
  });
  
  // lightbox
  $('.gallery .thumbnail').lightBox({fixedNavigation:true});
  
  if ($('.container.scout_forum.scouts').length > 0) {
    new filterRegion.init(
      $('.new-region-country[name*=country_id]'), 
      $('.new-region-province[name*=province_id]'), 
      $('.new-region-city[name*=city_id]')
    );
  }
  
  // launch audio player
  $('.launch-audio-player').click(function(e) {
    e.preventDefault();
    
    // open the audio player
    window.open('/player', 'MLSAudioPlayer', 'directories=false,height=390,location=false,menubar=false,resizable=false,scrollbars=false,status=false,toolbar=false,width=640');
  });
  
  // disable forms
  if ($('form[class*=disabled]').length > 0) {
    var $elements = $("form[class*=disabled]").find('input, textarea, select');
    $elements.attr("disabled", "disabled");
  }
  
  // make the artist details appear after selecting the first 3 questions
  if ($("form#ReviewForm").length) {
    $context = $("form#ReviewForm");
    
    $("tr.appearable input:radio", $context).click(function(e) {
      
      // loop through possible inputs
      $("tr.appearable input:radio:checked", $context).each(function(e) {
        var val = $(this).val();
        var rel = $(this).attr("rel");
        
        $("input:hidden[rel="+ rel + "-bottom]", $context).val(val);
      });
      
      var totalChecked = $("tr.appearable input:radio:checked", $context).length;
      
      if (totalChecked == 3) {
        $('#artist_details').fadeIn();
        
        $("tr.appearable input:radio", $context).each(function(e) {
          $(this).attr("disabled", true);
        });
      };
    });
  };
  
  if ($("a.review_track").length) {
    $("a.review_track").click(function(e) {
      e.preventDefault();
      
      // open the review track
      window.open($(this).attr("href"), 'MLSReviewTrack', 'directories=false,height=75,location=false,menubar=false,resizable=false,scrollbars=false,status=false,toolbar=false,width=400');
    });
  }
  
  
  // blockUI when saving
  $('form[name=SubmitForm]').submit(function(e) {
    $('.content').block({
      message: '<h2 style="color: #000000; line-height: 120%; padding: 10px; text-align: center;">Saving.. Please wait.<br />Uploading MP3s may take a while - please be patient.</h2>'
    });
    
    $('a').bind('click', function(e) {
      return confirm('Your information is currently being saved.\rAre you sure you want to leave?\rNote: All information will be lost.');
    });
  });
  
  // toggler
  $("a[class*=toggler]").click(function(e) {
    e.preventDefault();
    
    var element = $(this).attr("rel");
    
    $("#" + element).toggle();
  });
  
});

/**
 * The following function will make the header login screen render nicely
 * for browsers that support JS
 *
 * @access public
 */
function userNotAuthed() {
  if ($('.header_login .not-authed').length == 0) return;
  
  $('.header_login .not-authed label').remove();
  
  $('.not-authed .text-field.login.email').css({'background-image': 'url("/img/frontend/login-header-field-bg-email.gif")'});
  $('.not-authed .text-field.login.password').css({'background-image': 'url("/img/frontend/login-header-field-bg-password.gif")'});
  
  $('.not-authed .text-field.login').focus(function(e) {
    $(this).css({'background-image': 'url("/img/frontend/login-header-field-bg.gif")'});
  });
  
  $('.not-authed .text-field.login.email').blur(function(e) {
    if ($(this).val() == "") $(this).css({'background-image': 'url("/img/frontend/login-header-field-bg-email.gif")'});
  });
  
  $('.not-authed .text-field.login.password').blur(function(e) {
    if ($(this).val() == "") $(this).css({'background-image': 'url("/img/frontend/login-header-field-bg-password.gif")'});
  });
}

/**
 * The following functionality is specific to the User Application process
 *
 * @access public
 */
function userApplication() {
  if ($('.container.scout.application').length > 0 || $('.container.myscout.edit').length > 0) {
    
    // blockUI when saving
    $('form[name=ApplyForm]').submit(function(e) {
      $('.content').block({
        message: '<h2 style="color: #000000; padding: 10px; text-align: center;">Saving.. Please wait.</h2>'
      });
      
      $('a').bind('click', function(e) {
        return confirm('Your information is currently being saved.\rAre you sure you want to leave?\rNote: All information will be lost.');
      });
    });
    
    // closest major city
    if ($('#request-new-city').length > 0) {
      $('.request-new-city').click(function(e) {
        e.preventDefault();

        $('.content').block({
          message: $('#request-new-city'),
          css: {cursor: 'auto', height: '285px', width: '500px'}
        });
        
        $('.new-region-cancel').click(function(e) {
          e.preventDefault();
          $('.content').unblock();
        });
        
        $('#request-new-city form').submit(function(e) {
          e.preventDefault();
          
          $('#request-new-city form').block({
            message: '<h2 style="color: #000000; padding: 10px; text-align: center;">Saving.. Please wait.</h2>',
            css: {width: '55%'}
          });
          
          // POST the values (send email)
          $.ajax({
            cache: false,
            data: $('#request-new-city form').serialize(),
            type: 'POST',
            timeout: 7500,
            url: '/users/region.ajax',
            success: function(data){
              responseData = new String(data);
              
              if (responseData.indexOf('success') >= 1) {
                $('#request-new-city form').unblock().block({
                  timeout: 5000,
                  centerX: true,
                  centerY: true,
                  css: {border: 'none', padding: '8px', width: '80%'},
                  message: data,
                  onUnblock: function(element, options) {
                    $('.content').unblock();
                  }
                });
              } else {
                $('#request-new-city form').unblock().block({
                  timeout: 3500,
                  centerX: true,
                  centerY: true,
                  css: {border: 'none', padding: '8px', width: '80%'},
                  message: data
                });
              }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
              $('.content').unblock().block({
                timeout: 5000,
                centerX: true,
                centerY: true,
                css: {width: '55%'},
                message: '<h2 style="color: #000000; line-height: 18px; padding: 10px; text-align: center;">There was an error submitting a new region.<br />Please try your request again.</h2>'
              });
            }
          });
        });
      });

      new filterRegion.init(
        $('.new-region-country[name*=country_id]'), 
        $('.new-region-province[name*=province_id]'), 
        $('.new-region-city[name*=city_id]')
      );
    };
    
    // student fields
    $('#ProfileStudent').change(function() {
      var current = $('.is_student').css('display');
      
      if (current == 'none') {
        $('.is_student').fadeIn();
      } else {
        $('.is_student').fadeOut();
      }
    });
    
    // musician fields
    $('#ProfileMusician').change(function() {
      var current = $('.is_musician').css('display');
      
      if (current == 'none') {
        $('.is_musician').fadeIn();
      } else {
        $('.is_musician').fadeOut();
      }
    });
  }
};

/**
 * Handles Submission/Review pages
 *
 * @access public
 */
  function periods() {
    if ($('.container.periods.submission .add-location').length > 0) {
      $('.container.periods.submission .add-location').live('click', function(e) {
        e.preventDefault();
        
        $.ajax({
          cache: false,
          url: '/periods/fieldset/render:_performance',
          complete: function(e) {
            $('#location-body').append(e.responseText);
            
            $('#location-body tr:even').removeClass('light').addClass('dark');
            $('#location-body tr:odd').removeClass('dark').addClass('light');
          }
        });
      });
      
      $('.container.periods.submission .remove-location').live('click', function(e) {
        e.preventDefault();
        
        $(this).closest('tr').fadeOut('normal', function(e) {
          $(this).remove();
          
          $('#location-body tr:even').removeClass('light').addClass('dark');
          $('#location-body tr:odd').removeClass('dark').addClass('light');
        });
      });
    }
  }


/**
 * The following functionality is specific to the Comment sections
 *
 * @access public
 */
function comments() {
  if ($('.comments').length > 0) {
    var message = '<h2 style="color: #000000; padding: 10px; text-align: center;">Saving.. Please wait.</h2>';

    // adding topics and replies
    $('form[name=Comment]').submit(function(e) {
      $(this).block({message: message});
    });

    // comment management
    $('table.replies tr').each(function(e) {
      var $item = $(this);
      var $id = $(this).attr('rel');

      $('.r_content', $item).editable('/comments/editable/'+ $id, {
        loadurl: '/comments/editable/'+ $id,
        name: 'content',
        type: 'textarea',
        cancel: 'Cancel',
        submit: 'Save',
        indicator: '<img src="/img/common/loading-small.gif" /> Please wait...',
        tooltip: 'Click to edit...' 
      });

      $('div.management a', $item).bind('click', function(e) {
        e.preventDefault();

        switch ($(this).attr('name')) {
          case "delete":
            if (confirm('Are you sure you want to delete this comment?')) {
              $('td.reply-details', $item).wrapInner('<div class="blockUI"></div>');
              $('td.reply-details div.blockUI', $item).height($('td.reply-details', $item).height() - 4);
              $('td.reply-details div.blockUI', $item).block({message: '<h2 style="color: #ff0000; padding: 10px; text-align: center;">Removing..</h2>'});
              
              $.post($(this).attr('href'), null, function(e) {
                $('.responseMessage').html('<div class="alertMessage"><div class="alertMessage"><div class="success"><p class="item">You have successfully added a new comment.</p></div></div></div>');
                $('.responseMessage').stop('fx');
                $('.responseMessage').css('opacity', '1');
                $('.responseMessage').show(0);
                $('.responseMessage').fadeOut(4000);
                
                $item.fadeOut('normal', function(e) {
                  $item.remove();
                  
                  $('table.replies tr').removeClass('dark');
                  $('table.replies tr').removeClass('light');

                  $('table.replies tr:even').addClass('dark');
                  $('table.replies tr:odd').addClass('light');
                });
              });
            }
          break;
          case "edit":
            $('.r_content', $item).trigger('click');
          break;
          case "quote":
            var quote = $(this).attr('rel');
            var value = $('#CommentContent').val();

            if (value == "") $('#CommentContent').val("@" + quote + ": ");
            if (value != "") $('#CommentContent').val(value + "\r\r@" + quote + ": ");

            $('html,body').animate({scrollTop: $('form[name=Comment]').offset().top}, 'slow');
          break;
        }
      });
    });
  }
};

/**
 * The following functionality is specific to the Message Board sections
 *
 * @access public
 */
function boards() {
  if ($('.container.scout.board').length > 0) {
    var message = '<h2 style="color: #000000; padding: 10px; text-align: center;">Saving.. Please wait.</h2>';
    
    // adding topics and replies
    $('form[name=BoardPost]').submit(function(e) {
      $(this).block({
        message: message
      });
    });
    
    $('form[name=BoardTopic]').submit(function(e) {
      $(this).block({
        message: message
      });
    });
    
    
    // post management
    $('table.replies tr').each(function(e) {
      var $item = $(this);
      var $id = $(this).attr('rel');
      
      $('.r_content', $item).editable('/boards/editable/'+ $id, {
        loadurl: '/boards/editable/'+ $id,
        name: 'content',
        type: 'textarea',
        cancel: 'Cancel',
        submit: 'Save',
        indicator: '<img src="/img/common/loading-small.gif" /> Please wait...',
        tooltip: 'Click to edit...' 
      });
      
      $('div.management a', $item).bind('click', function(e) {
        e.preventDefault();
        
        switch ($(this).attr('name')) {
          case "delete":
            if (confirm('Are you sure you want to delete this post?')) {
              $('td.reply-details', $item).wrapInner('<div class="blockUI"></div>');
              $('td.reply-details div.blockUI', $item).height($('td.reply-details', $item).height() - 4);
              $('td.reply-details div.blockUI', $item).block({message: '<h2 style="color: #ff0000; padding: 10px; text-align: center;">Removing..</h2>'});
              
              $.post($(this).attr('href'), null, function(e) {
                $('.boardMessage').html('<div class="alertMessage"><div class="alertMessage"><div class="success"><p class="item">You have successfully added a new comment.</p></div></div></div>');
                $('.boardMessage').stop('fx');
                $('.boardMessage').css('opacity', '1');
                $('.boardMessage').show(0);
                $('.boardMessage').fadeOut(4000);
                
                $item.fadeOut('normal', function(e) {
                  $item.remove();
                  
                  $('table.replies tr').removeClass('dark');
                  $('table.replies tr').removeClass('light');

                  $('table.replies tr:even').addClass('dark');
                  $('table.replies tr:odd').addClass('light');
                });
              });
            }
          break;
          case "edit":
            $('.r_content', $item).trigger('click');
          break;
          case "quote":
            var quote = $(this).attr('rel');
            var value = $('#BoardPostContent').val();
            
            if (value == "") $('#BoardPostContent').val("@" + quote + ": ");
            if (value != "") $('#BoardPostContent').val(value + "\r\r@" + quote + ": ");
            
            $('html,body').animate({scrollTop: $('form[name=BoardPost]').offset().top}, 'slow');
          break;
        }
      });
    });
    
    // topic management
    $('ul.common.board.management li a').bind('click', function(e) {
      e.preventDefault();
      
      switch ($(this).attr('name')) {
        case "lock":
          $(this).attr('name', 'unlock').text('Unlock Topic');
          $.ajax({cache: false, url: $(this).attr('href')});
        break;
        case "unlock":
          $(this).attr('name', 'lock').text('Lock Topic');
          $.ajax({cache: false, url: $(this).attr('href')});
        break;
        case "sticky":
          $(this).attr('name', 'unsticky').text('Unsticky Topic');
          $.ajax({cache: false, url: $(this).attr('href')});
        break;
        case "unsticky":
          $(this).attr('name', 'sticky').text('Sticky Topic');
          $.ajax({cache: false, url: $(this).attr('href')});
        break;
        case "delete":
          if (confirm('Are you sure you want to delete this topic?')) {
            document.location.href = $(this).attr('href');
          }
        break;
        case "move":
          var url = $(this).attr('href');
        
          $('#switchBoards').fadeIn();
          $('#switchBoards').change(function(e) {
            document.location.href = url + '/board_id:' + $(this).val();
          });
        break;
      }
    });
  }
};

/**
* Setup Autocompleting (Suggestion) fields
*
* @access public
*/
function suggestField() {
  $('.autocomplete').each(function(e) {
    if ($(this).attr('rel') == undefined) { 
      return true; // 'continue;' was throwing an error -- changed to 'return true;' according to http://docs.jquery.com/Utilities/jQuery.each
    }
    
    var pieces = $(this).attr('rel').split(':');
    
    var url = '/'+ pieces[0] +'/autocomplete';
    if (pieces.length == 3) url += '/assoc:'+ pieces[1] +'/field:'+ pieces[2];
    if (pieces.length == 2) url += '/field:'+ pieces[1];
    
    $('.autocomplete').autocomplete({
      url: url,
      autoFill: true,
      mustMatch: true,
      multipleSeparator: null
    });
  });
};

/**
* Handle tabbed content management pages
* 
* @access public 
*/
function tabbed() {
  if ($('ul.tabs li').length > 0) {
    var $tabs = $('ul.tabs li a');
    
    var rels = new Array();
    $tabs.each(function(e) {
      panel = $(this).attr('href').split(/\/panel:/i);
      if (panel.length == 2) panel = panel[1];
      rels[e] = panel;
    });
    
    $tabs.click(function(e) {
      e.preventDefault();
      
      // hide all non-clicked
      for (var a = 0; a < rels.length; a++) $('div.panels').children('#'+rels[a]).hide();
      
      // get the panel name
      panel = $(this).attr('href').split(/\/panel:/i);
      if (panel.length == 2) panel = panel[1];
      rels[e] = panel;
      
      // show the clicked
      $('div.panels').children('#'+panel).show();
      $('input#active-panel').val(panel);
    });
  };
};

/**
* Handle the Top Report Cards (ajax refreshing)
*
* @access public
*/
function topReportCards() {
  if ($('.container.scout_forum.ranking').length > 0) {
    $('#RankingFilterForm').submit(function(e) {
      e.preventDefault();
      
      $('#top_container').block({
        centerX: true,
        centerY: false,
        css: {top: '100px', width: '40%'},
        message: '<h2 style="color: #000000; padding: 10px; text-align: center;">Loading Results.. Please wait.</h2>'
      });
      
      $.ajax({
        cache: false,
        type: 'GET',
        timeout: 7500,
        url: '/scout/forum/ranking/'+ $('#RankingFilterPeriodId').val() +'/'+ $('#RankingFilterLimit').val() +'.ajax',
        success: function(data){
          $('#top_container').unblock();
          
          $('#top_container').html(data);
          $('#top_container table tbody').hide();
          $('#top_container table tbody').stop('fx');
          $('#top_container table tbody').fadeIn('fast');
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          $('#top_container').unblock().block({
            timeout: 5000,
            centerX: true,
            centerY: false,
            css: {top: '100px', width: '55%'},
            message: '<h2 style="color: #000000; line-height: 18px; padding: 10px; text-align: center;">There was an error loading these Report Cards.<br />Please try your request again.</h2>'
          });
        }
      });
    });
  }
};

/**
* Handle the Top Charted Submissions (ajax refreshing)
*
* @access public
*/
function topChart() {
  if ($('.container.scout_forum.basic_chart').length > 0) {
    $('#ChartFilterForm').submit(function(e) {
      e.preventDefault();
      
      $('#top_container').block({
        centerX: true,
        centerY: false,
        css: {top: '100px', width: '40%'},
        message: '<h2 style="color: #000000; padding: 10px; text-align: center;">Loading Results.. Please wait.</h2>'
      });

      $.ajax({
        cache: false,
        type: 'GET',
        timeout: 7500,
        url: '/scout/forum/chart/'+ $('#ChartFilterPeriodId').val() +'/'+ $('#ChartFilterLimit').val() +'.ajax',
        success: function(data){
          $('#top_container').unblock();

          $('#top_container').html(data);
          $('#top_container table tbody').hide();
          $('#top_container table tbody').stop('fx');
          $('#top_container table tbody').fadeIn('fast');
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          $('#top_container').unblock().block({
            timeout: 5000,
            centerX: true,
            centerY: false,
            css: {top: '100px', width: '55%'},
            message: '<h2 style="color: #000000; line-height: 18px; padding: 10px; text-align: center;">There was an error loading the Chart.<br />Please try your request again.</h2>'
          });
        }
      });
    });
  }
};


/**
* Review Question Descriptions
*
* @access public
*/
function reviewQuestionDescriptions() {
  if ($('.container.periods.review').length > 0) {
    $('td.question').hover(function(e) {
      if ($('div', this).text() != '') {
        $('#show_description p').fadeIn('normal');
        $('#show_description p').text($('div', this).text()); 
      }
    }, function(e) {
      $('#show_description p').hide();
      $('#show_description p').text();
    });
  }
};