var $loader;

function update_search_results()
{
  $.doTimeout('show_loading', 300, function() {
    show_loading();
  });
  $('input[name=page]').val('1'); // reset page to 1
  var serialized = $('#search-form input[value!=]:not(.ignore),#search-form select[value!=]:visible:not(.ignore)').serialize();
  $.bbq.pushState(serialized, 2);
}

function update_reviews()
{ // non ajax right now
  $('#reviews-form').submit();
}

function bind_search_select_change()
{
  $('#search-form select[name!=category]:not(.ignore)').change(function() {
    if($(this).val() == '-')
      return; // don't update page for invalid selection
    update_search_results();
  });
}

function bind_reviews_select_change()
{
  $('#reviews-form select').change(function() {
    if($(this).val() == '-')
      return; // don't update page for invalid selection
    update_reviews();
  });
}

function show_loading()
{
  $('#loading').remove();
  var $a = $('#search-results');
  if(!$a.length)
    $a = $('#content');
  var pos = $a.offset();
  var $b = $("<div id='loading'>Loading...</div>").css({ zIndex: 12000, textAlign: 'center', fontSize: '14pt', padding: '20px', border: '2px solid #666', 'border-radius': '5px', '-moz-border-radius': '5px', '-webkit-border-radius': '5px', background: "#fff", position: 'absolute', top: pos.top+'px', left: (pos.left+$a.width()/2-100)+'px', height: '60px', width: '200px' });
  $b.append($loader);
  if(typeof $.fn.bgiframe == 'function')
    $b.bgiframe();
  $('body').append( $b );
}

function hide_loading()
{
  $('#loading').fadeTo(300, 0, function() {
    $(this).remove();
  });
}

$(document).ready(function() {
  
  $('#default-search-btn').replaceWith( $('<a id="search-btn" href="#">search</a>') );
  $('#search-btn').click( function() { $(this).parents('form').submit(); } );
  $('.hintbox1').inputHintBox({div:$('#hint-box-wrapper'),div_sub:'.hint-box',source:'attr',attr:'title',incrementLeft: -70,incrementTop: -110});
  $('.hintbox2').inputHintBox({div:$('#hint-box-wrapper'),div_sub:'.hint-box',source:'attr',attr:'title',incrementLeft: -70,incrementTop: -110});
  $('.hintbox3').inputHintBox({div:$('#hint-box-wrapper'),div_sub:'.hint-box',source:'attr',attr:'title',incrementLeft: -90,incrementTop: -76});
  $('.hintbox4').inputHintBox({div:$('#hint-box-wrapper'),div_sub:'.hint-box',source:'attr',attr:'title',incrementLeft: -130,incrementTop: -93});
  $('.hintbox5').inputHintBox({div:$('#hint-box-wrapper'),div_sub:'.hint-box',source:'attr',attr:'title',incrementLeft: -190,incrementTop: -93});
  $('#search-form select[name=category]').change(function() {
    // reset filters, checkboxes and selects
    $('input[name=page]').val('1');
    $('#search-form .filter-options select[name=tag-option]').val('');
    $('#search-form .filter-options input:checked').removeAttr('checked');
    $('#search-form .filter-options').css({ display: 'none' });
    $('#search-form input[name=brand]:visible').focus();
  });
  $('#suggest select[name=category]').change(function() {
    $('#suggest input[name=brand]').focus();
  });
  $('input[name=brand]').suggest("?action=autocomplete_brand", { minchars: 1, onSelect: function() { $('input[name=brand]').trigger('keyup') } } );
  $('#search .filter-options .group').prepend( $('<div class="clear-selection">[clear selection]</div>') );
  $('#search .clear-selection').click(function() {
    var $s = $(this).parent('div').find('select[value!=]');
    if($s.length)
      $s.val('');
    var $c = $(this).parent('div').find('input:checked');
    if($c.length)
      $c.removeAttr('checked');
    if($s.length || $c.length)
      update_search_results();
  });
  $('#reviews-filter-options .group').prepend( $('<div class="clear-selection">[reset]</div>') );
  $('#reviews-filter-options .clear-selection').click(function() {
    var $s = $(this).parent('div').find('select')
    if($s.val() != '')
      $s.val('').trigger('change');
  });
  
  // hover buttons
  $('.hover-button')
    .live('mouseover', function() {
      $(this).css({backgroundPosition: '0 -36px'});
    })
    .live('mouseout', function() {
      $(this).css({backgroundPosition: '0 0'});
    })
    .live('mousedown', function() {
      $(this).css({backgroundPosition: '0 -72px'});
    })
    .live('mouseup', function() {
      $(this).css({backgroundPosition: '0 0'});
    });
  
  // page-jump
  $('.page-jump')
    .live('mouseover', function() {
      $(this).css({backgroundPosition: '0 -25px'});
      $(this).find('span').css({backgroundPosition: 'right -25px'});
    })
    .live('mouseout', function() {
      $(this).css({backgroundPosition: '0 0'});
      $(this).find('span').css({backgroundPosition: 'right 0'});
    })
    .live('mousedown', function() {
      $(this).css({marginTop: '1px', backgroundPosition: '0 -50px'});
      $(this).find('span').css({backgroundPosition: 'right -50px'});
    })
    .live('mouseup', function() {
      $(this).css({marginTop: '0'});
    });

  var prev_data = null;
  // ajax search results
  $(window).bind( 'hashchange', function(e) {
    var data = $.param.fragment();
    if(data == prev_data) //SAME THING
      return;
    else if(data == '') // if empty, use the query string instead
      data = $.param.querystring();
    prev_data = data;
    $.post(
      window.location.pathname+'?js=1',//url
      data,
      function(data) { //callback
        $('#search-results').html( data );
        $.doTimeout('show_loading'); // cancel show loading
        hide_loading();
        bind_search_select_change();
        if($.reviews_admin && typeof $.reviews_admin.admin_bind_editables == 'function')
          $.reviews_admin.admin_bind_editables();
        var params = $.deparam.fragment(true);
        // update category, brand, item_name
        $('select[name=category]').val(params.category);
        $('input[name=brand]').val(params.brand);
        $('input[name=item_name]').val(params.item_name);
        update_search_filters();
        // repaint, bad safari :[]
        var $a = $('#container');
        var pos = $a.offset();
        var $b = $("<div id='repaint' />")
          .css({ background: '#fff', opacity: 0, position: 'absolute', top: pos.top, left: pos.left+1,
              width: $a.width()+'px', height: $a.height()+'px'
            });
        $('body').append($b);
        $b.fadeTo(50, 0, function() { $(this).remove(); });
      }
    );
  });

  // popular tags
  $.extend({
    reviews: {
      added_tags: {},
      update_popular_tags: function (category) {
        $.getJSON(
          window.location.pathname+'?action=get_popular_tags&category='+category,
          function(data) {
            var $p = $('.popular-tags');
            $p.html('');
            for(var x in data)
              $p.append(
                $('<a class="add-item-add-tag" href="#" rel="'+data[x].id+'">'+data[x].name+'</a>')
              ).append('&nbsp;&nbsp; ');
          }
        );
      }
    }
  });
  
  $('a.add-item-add-tag').live('click', function() {
    var that = $(this),
        id = that.attr('rel'),
        name = that.text();
        $t = $('textarea[name=tags]:visible')
        val = $t.val();
    if($.reviews.added_tags[id] === undefined)
      $t.val( val ? val+', '+name:val+name );
    $.reviews.added_tags[id] = true;
    that.addClass('tag-added');
    return false;
  });
  // add item popup
  var add_item_popup_open = false;
  $('#add-item-to-database').click(function() {
    if(add_item_popup_open)
      return;
      
    var category = '', brand = '', item_name = '';
    var $s = $('#search-form');
    if($s.length)
    {
      category = $s.find("select[name=category]").val();
      $.reviews.update_popular_tags(category);
      brand = $s.find('input[name=brand]').val();
      item_name = $s.find("input[name=item_name]").val();
    }
    var $x = $('#add-item-popup-wrapper');
    $x.find('select[name=category]')
      .val(category)
      .change(function() {
        $.reviews.update_popular_tags( $(this).val() );
      });
    $x.find('input[name=brand]').val(brand);
    $x.find('input[name=item_name]').val(item_name);
    
    $x.fadeIn(function() {
      $(window).trigger('resize'); // position autocomplete
    });
    return false;
  });
  $('#add-item-popup-wrapper .submit-add-item').click(function() {
    // validate
    var $f = $('#add-item-form');
    if($.trim($f.find('input[name=item_name]').val()) == '')
    {
      alert("Oops! You must enter the item description before you can add the item.");
      $f.find('input[name=item_name]').focus();
    }
    else if($f.find('select[name=category]').val() == '')
    {
      alert("Oops! You must select a category before you can add the item.");
      $f.find('select[name=category]').focus();
    }
    else
      $f.submit();
    return false;
  });
  $('#add-item-popup-wrapper .cancel-button').click(function() {
    for(var x in $.reviews.added_tags)
      $.reviews.added_tags[x] = undefined;
    $('textarea[name=tags]:visible').val('');
    var $x = $('#add-item-popup-wrapper');
    $x.fadeOut();
    return false;
  });

  $('.where-to-buy a').click(function() {
    // position popup relative to link
    var that = $(this);
        $x = $('#where-to-buy-popup'),
        my_offset = that.offset(),
        popup_parent_offset = $('#container').offset(),
        y = my_offset.top - popup_parent_offset.top,
        x = my_offset.left - popup_parent_offset.left - $x.width();
    
    $x.css({top: y+'px', left: x+'px'}).fadeIn();
    return false;
  });
  function close_where_to_buy() {
    $('#where-to-buy-popup').fadeOut();
  }
  $('#where-to-buy-popup').click(function(e) {
    e.stopPropagation();
  });
  $('body').click(close_where_to_buy);
  $('#where-to-buy-popup .close').click(function() {
    close_where_to_buy();
    return false;
  });

  // review popup
  var review_popup_open = false;
  $('.rate-item,.review-item-link').click(function() {
    if(review_popup_open)
      return;
      
    var $r = $('#review-popup-wrapper');
    $r.fadeIn(function() {
      $('form textarea:first').focus();
    });
    return false;
  });
  $('.submit-review').click(function() {
    $('#review-form').submit();
    return false;
  });
  $('#review-popup-wrapper .cancel-button').click(function() {
    var $r = $('#review-popup-wrapper');
    $r.fadeOut();
    return false;
  });
  $('#review-form').submit(function() {
    if($('input[name=rating]').val() == '0')
    {
      alert('Oops! You forgot to give your 1-5 rating of this item.');
      return false;
    }
    return true;
  });
  
  var search_popup_open = false;
  $('#new-search').click(function() {
    if(search_popup_open)
      return;
    var $p = $('#search-popup-wrapper');
    $p.fadeIn(function() {
      $(window).trigger('resize'); // position autocomplete
    });
    return false;
  });
  $('#search-popup-wrapper .cancel-button').click(function() {
    var $p = $('#search-popup-wrapper');
    $p.fadeOut();
    return false;
  });
  
  var $h = $('#helpful-hover');
  $('.thumbs-wrapper').hover(
    function() {
      $(this).doTimeout('hover', 500, function() {
        this.append($h);
        $h.fadeIn();
      });
    },
    function() {
      $(this).doTimeout('hover', 250, function() {
        $h.fadeOut();
      });
    }
  );
  var helpful_voted = {};
  $('.helpful .thumb').click(function() {
    var that = $(this),
        url = that.attr('href'),
        review_id = that.attr('rel');
    if(helpful_voted[review_id])
      return false;
    helpful_voted[review_id] = true;
    var bp = that.css('backgroundPosition');
    if(typeof bp == 'undefined')
      bp = that.css('background-position-x')+' '+that.css('background-position-y');
    bp = bp.split(' ');
    that.css({backgroundPosition: bp[0]+' -58px'});// keep x-pos
    
    $.get(
      url,
      function(data) {
        vote = parseInt(data);
        if(vote != 1 && vote != -1)
          return;
        var $s = that.parents('.helpful').find('.score span');
        $s.removeClass('good bad');
        var score = parseInt($s.text());
        if(isNaN(score))
          score = 0;
        var new_score = score+vote;
        $s.text(new_score);
        if(new_score > 0)
          $s.addClass('good');
        else if(new_score < 0)
          $s.addClass('bad');
        $s = that.parents('.helpful').find('.score');
        var orig_color = $s.css('backgroundColor');
        $s.css({backgroundColor: '#ffaa00'})
          .animate({backgroundColor: orig_color}, 1000);
      }
    );
    return false;
  });
  
  // text box limit chars
  var update_limit = function() {
    var str = $.trim($(this).val());
    var limit = $(this).data('limit');
    if(str.length > limit)
    {
      str = str.substring(0, limit);
      $(this).val(str);
      $(this).stop().css({ backgroundColor: "#d63"}).animate({backgroundColor: "#fff" }, 500);
    }
    $(this).next('.limit').find('span').text(limit - str.length);
  }
  $('form textarea').each(function() {
    var limit = $(this).next('.limit').find('span').text();
    $(this).data('limit', limit);
    $(this).keyup(update_limit);
  });

  // voting
  var original_width;
  var original_bp;
  var vote_width = 0;
  var hover_vote = 0;
  var selected_vote = 0;
  $('.vote .rating-bottom').hover(
    function() {
      var that = $(this);
      if(that.parents('.item').length)
      {
        $('#vote-info-popup').doTimeout('hover', 250, function() {
          this.fadeIn();
        });
      }
      var $b = that;
      var $t = that.find('.rating-top');
      original_bp = $t.css('backgroundPosition');
      if(typeof original_bp == 'undefined') // ie sux
        original_bp = $t.css('background-position-x')+' '+$t.css('background-position-y');
      $t.css({ 'background-position': '0 -74px' });
      $b.attr('title', '');
      original_width = $t.width();
      var steps = 5;
      var width = $b.width();
      var offset = that.offset();
      that.mousemove(function(e) {
        var mouse_x = e.pageX - offset.left;
        hover_vote = Math.ceil(mouse_x / (width / steps)); // 1-5
        var step_x = hover_vote * Math.floor(width / steps);
        $t.css({ width: step_x+'px' });
      });
    },
    function() {
      var that = $(this);
      that.unbind('mousemove');
      var $t = that.find('.rating-top');
      $t.css({ width: vote_width||original_width+'px' });
      if(!vote_width)
        $t.css({ 'background-position': original_bp });
      if(that.parents('.item').length)
      {
        $('#vote-info-popup').doTimeout('hover', 250, function() {
          this.fadeOut();
        });
      }
    }
  ).click(function() {
    var that = $(this);
    selected_vote = hover_vote;
    var $t = that.find('.rating-top');
    vote_width = $t.width();
    // update input element with rating
    var $i = that.parent().find('input');
    if($i.length)
      $i.val(selected_vote);
    else // ajax vote
    {
      var item_id = $('div.item').metadata().item_id;
      $.post(
        window.location.pathname+'?action=cast_vote', //url
        {item_id: item_id, vote: selected_vote}, //data
        function(data) { //callback
          $('input[name=rating]').val(selected_vote);
          var $x = $('#vote-thanks-popup');
          $x.css({top: '10px'})
            .fadeIn()
            .animate({top: '-35px'}, 1500, function() {
              $(this).fadeOut(1000);
            });
        }
      );
    }
    // change both votes
    $t = $('.vote .rating-top');
    $t.css({ width: vote_width+'px', 'background-position': '0 -74px' });
  });

  // search result page selector ajax
  $('#search-results a.page-jump').live('click', function() {
    var that = $(this),
        page = 1;
    
    // figure out the page
    var m = that.attr('href').match(/page([0-9]+)\.html/i);
    if(m)
      page = m[1];
    else
    {
      var qs = $.deparam.querystring(that.attr('href'), true);
      page = qs.page;
    }
    $('input[name=page]').val(page);

    $.doTimeout('show_loading', 400, function() {
      show_loading();
    });
    var serialized = $('#search-form input[value!=]:not(.ignore),#search-form select[value!=]:not(.ignore)').serialize();
    $.bbq.pushState(serialized, 2);
    
    return false;
  });
  
  $('#search-form').submit(function() {
    // remove empty form fields
    $('#search-form select[name=tag-option][value=],#search-form select.ignore').remove();
    return true;
  });

  // search filter ajax
  $('#search .filter-options input').click(function() {
    update_search_results();
  });
  
  $loader = $("<img id='loading-bar' src='/reviews/images/ajax-loader.gif'>").css({ display: 'block', margin: '10px auto' });
  
  if($.param.fragment())
    $(window).trigger('hashchange');
    
  if(typeof(update_search_filters) == 'function')
    update_search_filters();
  
  if($('#search-view-options').length)
    bind_search_select_change();
  else if($('#reviews-view-options').length)
    bind_reviews_select_change();

  $('abbr[class*=timeago]').timeago();
  
  // flash
  var $f = $('#flash');
  if( $f.length )
  {
    $f.find('.inner').css({opacity: 1});
    $f.css({display: 'block', opacity: 0});
    var win_w = $(window).width(),
        win_h = $(window).height(),
        flash_w = $f.width(),
        flash_h = $f.height(),
        x = Math.floor(win_w / 2 - flash_w / 2),
        y = Math.floor(win_h / 3 - flash_h / 2),
        timeout = $f.metadata().timeout || 5000; // default 5s
    $f.css({top: y+'px', left: x+'px'})
      .animate({opacity: 1, top: "-=100px"}, 1400)
      .doTimeout('fadeout', timeout, function() {
        $(this).fadeOut();
      });
  }
  $f.click(function(e) {
    e.stopPropagation();
  })
  function close_flash()
  {
    $f.doTimeout('fadeout');
    $f.fadeOut();
  }
  $f.find('.close')
    .click(function() {
      // force immediate fadeout
      close_flash();
      return false;
    });
  
  // move some popups to container div for positioning purposes
  $('.move-to-container').appendTo('#container');
});

