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

function initReviewModal(){
    $("#nyroModalContent #suggestion_form #product_name").focus();
    $("#nyroModalContent .product_rating").rating();
}

function openReviewModalFor(url) {
  $.get('/products/product_review_modal?url=' + url, function(data) {
    $.nyroModalManual({
      content: $(data), 
      endShowContent: function(elts, settings) { 
        initReviewModal();
      }
    });
  });
}

$(document).ready(function() {
  $.nyroModalSettings({minWidth: 470, minHeight: 400});
  $('#search_box, #invite_simple_form input[type="text"]').click(function() {
    $(this).val('');
  });
   
  if(typeof(products) == 'boolean')
  {
	   $.nyroModalManual({
      content: $("#relay").html(),
       endShowContent: function(elts, settings) { 
         initReviewModal();
       }
    });
  } 

  // Review form for edit
  
  $(".edit_reviews").click(function(e){
    e.preventDefault();
    $.ajax({
      type: "GET",
      url: this.href,
      error: function(data, textStatus) {
        document.location.href='/';
      },
      success: function(html) {
        $.nyroModalManual({
          content: $(html),
          endShowContent: function(elts, settings) {
            initReviewModal();
          }
        });
      }
    });
  });

  $(".delete_reviews").click(function(e){
    e.preventDefault();
    if (confirm('Are you sure?')){
      $.ajax({
        type: "DELETE",
        url: this.href,
        error: function(data, textStatus) {
          document.location.href='/';
        },
        success: function(html) {
          document.location.reload();
        }
      });
    }
  });

  // TAB NAVIGATION
  
  $("#product-tabs #product_nav a").click(function() {
    $("#reviews-tab, #features-tab, #company-background-tab, #links-tab").hide();
    $($(this).attr("href")).show();
    $("#product_nav li").removeClass("ui-state-active");
    $(this).parent("li").addClass("ui-state-active");
    return false;
  });

  // all .hiddable class links hides related (by rel attribute) tags
  $(".hiddable").click(function() {
    $("#" + this.rel).hide();
  });

  $("#hide_full_rating_link").click(function () {
    // see also .hiddable class event
    $(".small_rating").show();
  });

  // LOGIN FORM
  
  $("#login_form").submit(function() {
    $("#login_errors").html("<p>&nbsp;</p>");
    $.ajax({
      type: "POST",
      url: this.action,
      data: $(this).serialize(),
      error: function(data, textStatus) {
        $("#login_errors").html("<p>Wrong email or password. Try again.</p>")
      },
      success: function(html) {
        $("#login_form").html("<p>" + html + " <br /></p>");
        document.location.reload();
      }
    });
    return false; 
  });
  
  // SUGGESTION FORM

  $("#suggestion_form").live('submit', function() {
    var div = $(this).parent('div');
    $.ajax({
      type: "POST",
      url: this.action,
      data: $(this).serialize(),
      error: function(xhr, textStatus) {
        div.find("#suggestion_errors").html(xhr.responseText);
      },
      success: function(html) {
        div.html("<p>Thanks. Your suggestion has been sent.</p><p><a href=\"#\" class=\"close\">Close</a></p>");
        setTimeout($.nyroModalRemove, 3000);
      }
    });
    return false; 
  });

  // INVITATION FORM
  
  $("#invite_form").live('submit', function() {
    var div = $(this).parent('div');
    $.ajax({
      type: "POST",
      url: this.action,
      data: $(this).serialize(),
      error: function(xhr, textStatus) {
        div.find("#invite_errors").html(xhr.responseText);
      },
      success: function(html) {
        div.html("<p>Thanks for inviting your colleague.</p><p><a href=\"#\" class=\"close\">Close</a></p>");
        setTimeout($.nyroModalRemove, 3000);
      }
    });
    return false; 
  });
  
  $("#invite_simple_form").submit(function() {
    var email = $(this).find("input[type='text']").val();
    $.nyroModalManual({ 
      content: $('#inviteForm').html(), 
      endShowContent: function() {
        $("#nyroModalContent #invite_form #to").val(email)
      }
    });
    return false;
  });

  // FEEDBACK FORM

  $("#feedback_form").live('submit', function (){
    var div = $(this).parent('div');
    $.ajax({
      type: "POST",
      url: this.action,
      data: $(this).serialize(),
      error: function(xhr, textStatus) {
        div.find("#feedback_errors").html(xhr.responseText);
      },
      success: function(html) {
        div.html("<p>Thanks for your feedback.</p><p><a href=\"#\" class=\"close\">Close</a></p>");
        setTimeout($.nyroModalRemove, 3000);
      }
    });
    return false; 
  });

  $("#flag_form").live('submit', function (){
    var div = $(this).parent('div');
    $.ajax({
      type: "POST",
      url: this.action,
      data: $(this).serialize(),
      error: function(xhr, textStatus) {
        div.find("#feedback_errors").html(xhr.responseText);
      },
      success: function(html) {
        div.html("<p>Thank you.  We will take a look at the review.</p><p><a href=\"#\" class=\"close\">Close</a></p>");
        setTimeout($.nyroModalRemove, 3000);
      }
    });
    return false; 
  });

  // HANDLE CLOSE LINKS IN MODALS
  
  $("#nyroModalWrapper a.close").live('click', function() {
    $.nyroModalRemove();
    return false;
  });
  
  // INIT RATING

  $('.review_rating').rating();
  $('.review_rating').rating("readOnly");
  $('.pre_rating').rating({
    callback: function(value, link){
      $('#nyroModalContent .product_rating').rating('select',value);
      $('#product_add_review').show();
      $(".small_rating").hide();
    }
  });
  
  // TOP SEARCH BOX AUTOCOMPLETE

  // init autocompletion
  $("#search_box").autocomplete(autocompleteDataSearch, {
    selectFirst: false,
    formatItem: function(item) {
      return item.text;
    },
    matchContains: true
  }).result(function(event, item) {
    if (item.url) {
      window.location = item.url;
    } else {
      $.nyroModalManual({ 
        content: $('#suggestionForm').html(), 
        endShowContent: function(elts, settings) { 
          $("#nyroModalContent #suggestion_form #product_name").focus();
        }
      });
    }
  });
  
  // handle "enter" key and mouse press in top search
  $("#header .search_button").click(function() {
    var keyword = $("#header #search_box").val();
    var resultsNum = 0;
    var url;
    if (keyword != '' && keyword != 'search...') {
      $.each(autocompleteDataSearch, function() {
        if (this.text.toLowerCase() == keyword.toLowerCase()) {
          url = this.url;
          resultsNum += 1;
        }
      });
    }
    if (resultsNum == 1) {
      window.location = url;
      return false;
    }
    return true;
  });
  
  // RELAY NOW BOX

  // init autocompletion
  $("#relay_product_name").autocomplete(autocompleteData, {
    formatItem: function(item) {
      return item.text;
    }
  }).result(function(event, item) {
    if (item.url) {
      openReviewModalFor(item.url);
    } else {
      $.nyroModalManual({ 
        content: $('#suggestionForm').html(), 
        endShowContent: function(elts, settings) { 
          $("#nyroModalContent #suggestion_form #product_name").focus();
        }
      });
    }
  });
  
  // handle "enter" key and mouse press in "relay now" box
  $("#relay_box form").submit(function() {
    var keyword = $("#relay_product_name").val();
    var found = false;
    if (keyword != '') {
      $.each(autocompleteData, function() {
        if (this.text.toLowerCase() == keyword.toLowerCase()) {
          openReviewModalFor(this.url);
          found = true;
          return false;
        }
      });
    }
    return !found;
  });
  
  // INIT NEW REVIEW

  $('.relay_product').click(function(e) {
    e.preventDefault();
    $.nyroModalManual({
      content: $('#relay').html(),
      endShowContent: function(elts, settings) {
        initReviewModal();
      }
    });
  });
  
  $('.relay_product_list').click(function(e) {
    e.preventDefault();
    var url = '/products/product_list_review_modal';
    var matches = /^relay_product_list_(vendor|category)_(\d+)/.exec(this.id);
    if (matches !== null && matches.length >= 3) {
      //we've matched both parentheses
      url = url + '?filter='+matches[1]+'&id=' + matches[2];
    }
    $.nyroModalManual({
      url: url,
      endShowContent: function(elts, settings) {
        $('.choose_product_for_review').click(function(e) {
          e.preventDefault();
          $('#review_product_id').val(this.rel);
          $('.relay_product_name').html("Your review of: " + this.innerHTML);
          $('#nyroModalContent').html($('#relay').html());
          initReviewModal();
        });
      }
    });
  });

  //COMMENTS

  $('.show_comments_link').click(function(e) {
    e.preventDefault();
    var placeholderId = this.id.replace(/_link$/,'');
    var placeholder = $('#' + placeholderId);
    var showLink = $(this);
    var hideLink = $('#hide_' + this.id);
    showLink.hide();
    hideLink.show();
    hideLink.click(function(e) {
      e.preventDefault();
      placeholder.hide();
      hideLink.hide();
      showLink.show();
    });
    $.ajax({
      type: 'GET',
      url: this.href,
      error: function(xhr, textStatus) {
        placeholder.html(xhr.responseText);
      },
      success: function(html) {
        placeholder.html(html);
        initCommentFormObserver(placeholderId);
        initCommentActionLinksObservers(placeholderId);
      }
    });
    placeholder.show();
  });

  function initCommentFormObserver(placeholderId) {
    var placeholder = $('#' + placeholderId);
    var form = placeholder.find('form');
    form.submit(function(e) {
      e.preventDefault();
      $.ajax({
        type: 'POST',
        url: this.action,
        data: $(this).serialize(),
        error: function(xhr, textStatus) {
          placeholder.html(xhr.responseText);
        },
        success: function(html) {
          placeholder.html(html);
          initCommentFormObserver(placeholderId);
          initCommentActionLinksObservers(placeholderId);
        }
      });
    });
  }

  function initCommentActionLinksObservers(parentId){
    $('#' + parentId + ' a.edit_comment_link').click(function(e) {
      e.preventDefault();
      var placeholder = $(this).parents('div.comment').get(0);
      $.ajax({
        type: 'GET',
        url: this.href,
        error: function(xhr, textStatus) {
          $(placeholder).html(xhr.responseText);
        },
        success: function(html) {
          $(placeholder).html(html);
          initCommentActionLinksObservers(placeholder.id);
          initCommentFormObserver(placeholder.id);
        }
      });
    });

    $('#' + parentId + ' a.delete_comment_link').click(function(e) {
      e.preventDefault();
      if (confirm('Are you sure?')){
        var placeholder = $(this).parents('div.comment').get(0);
        $.ajax({
          type: 'DELETE',
          url: this.href,
          error: function(xhr, textStatus) {
            $(placeholder).html(xhr.responseText);
          },
          success: function(html) {
            $(placeholder).html(html);
            initCommentActionLinksObservers(placeholder.id);
            initCommentFormObserver(placeholder.id);
          }
        });
      }
    });
  }

  // REVIEW REQUESTS
  var reviewRequestClicked = false;
  $('.review_request_link').click(function(e) {
    e.preventDefault();
    if (!reviewRequestClicked) {
      reviewRequestClicked = true;
      $.ajax({
        type: 'POST',
        url: this.href,
        complete: function() {
          $('#review_request').html('Your request has been sent');
        }
      });
    }
  });

  function initRequestFormObserver(){
    $('#review_request_form').submit(function(e) {
      e.preventDefault();
      $.ajax({
        type: 'POST',
        url: this.action,
        data: $(this).serialize(),
        error: function(xhr, textStatus) {
          $('#review_request').html(xhr.responseText);
          initRequestFormObserver();
        },
        success: function(html) {
          $('#review_request').html(html);
          initRequestFormObserver();
        }
      });
    });
  }
  initRequestFormObserver();
});
