$(document).ready(function(){
  $('.accordion').kwicks({
    max: 490,
    sticky : true,
    event: 'click'
  });

  minifyHouses();
  animateHouses();
});

$(document).keydown(function(e) {
  if (e.which == 27) {
    removeReport();

    return false;
  }
});

function animateHouses() {
  $(".green_arrow").hover(
    function() {
      $(this).animate({"right": "-=10px"}, "normal");
    },
    function() {
      $(this).animate({"right": "+=10px"}, "normal");
    }
  );
}

function minifyHouses() {
  $('#houses h3').click(function() {
    $(this).parent().find('a.minimize').click();
  });
}

function reportHouse(id) {
  if ($('#report_' + id).hasClass('active')) {
    removeReport();

    return false;
  }

  var report = '<div id="report" class="modal" style="display: none">  <label>Reason?</label>  <input id="description" type="text">  <a class="submit">&gt;</a></div>';
  
  // Active state
  $('.report.active').removeClass('active');
  $('#report_' + id).addClass('active');

  // Remove previously created inputs
  $('#report').remove();
  
  // Append input to clicked li
  $('#report_' + id).after(report);
  $('#report').fadeIn();
  $('#report input').focus();

  // Bind event
  $('#report a.submit').click(function() {
    submitReport(id);
  });

  // Bind the enter key to submit the information
  $('#report input').bind('keypress', function(e) {
    if (e.keyCode==13) {
      $('a.submit').click();
    }
  });

  return false;
}

function removeReport() {
  $('div#report.modal').fadeOut();

  $('.report.active').removeClass('active');
}

function submitReport(id) {
  var value = $("#report #description").val();

  if (value) {
    $.getJSON('/ajax/report', { description: value, id: id}, function(json) {
     if (json.success) {
       alert('Thank you!');

       removeReport();
     } else {
       alert('An error has occurred, please try again later.');
     }
    });
  } else {
    alert('You must provide a reason!');
  }

  return false;
}

function minimizeHouse(id) {
  var $house = $('#house_' + id);
  var $content = $('#house_' + id + ' .minimizable');;

  if ($house.hasClass('closed')) {
    $house.removeClass('closed');

    $content.slideDown('normal', function() {
      $content.find('a.green_arrow, .bottom, .report').fadeIn('fast');
    });
  } else {
    removeReport();

    $content.find('a.green_arrow, .report').fadeOut('fast');

    $house.addClass('closed');
    $content.slideUp();
  }

  return false;
}

function showHouses(difficulty) {
  if ($('#' + difficulty).hasClass('active')) {
    return false;
  }

  $('.difficulty').slideUp();
  $('.difficulty.' + difficulty).slideDown();

  return false;
}