// ### Part of the [Rosy Framework](http://github.com/ff0000/rosy)
/* grand-exchange.js */

// ## Local Namespace

// GrandExchange Page class

// Site-specifc namespace
var RuneScape = RuneScape || {};

// Page namespace
RuneScape.Page = RuneScape.Page || {};

// About specific instance
RuneScape.Page.GrandExchange = (function () {

 return RuneScape.Page.extend({

  vars : {},

  // About  page level functionality
  init : function (vars) {
   this.sup(vars);

   this.setDOMReferences();
   this.setupCatalogue();

   // Delay for IE?
   window.setTimeout($.proxy(this.setupGraphs, this), 0);
  },

  setDOMReferences : function () {
   this.vars.graphs = $("[data-module-class='Graph']");
   this.vars.fields = $(".customfield");
   this.vars.catalogue = $(".item-catalogue");

  },

  setupGraphs : function () {
   if (!this.vars.graphs.length) {
    return;
   }

   var i, j, module;

   for (i = 0, j = this.vars.graphs.length; i < j; i++) {
    module = new RuneScape.Module.ItemDetailGraph({
     graph : $(this.vars.graphs[i]),
     width : 578
    });
   }
  },

  setupCustomField : function () {
   var field, i, j;

   for (i = 0, j = this.vars.fields.length; i < j; i++) {
    field = new RED.Module.CustomFormField({
     field : $(this.vars.fields[i])
    });
   }
  },

  setupCatalogue : function () {
   var catalogue = new RuneScape.Module.Catalogue({
    parent : this.vars.catalogue
   });
  }

 });
}.call(RuneScape));


/* -----------------------------------------------------------------------------------------------*/
/* -------------------------------------------------------------------------------- SETUP POPUPS -*/
/* -----------------------------------------------------------------------------------------------*/

$(function(){

 var $res = $('.item-overlay-parent');
 if($res.length){

  var resOTop = $res.offset().top;

  var $itemShell = $("<div class='itemDetails'></div>").prependTo($res);

  var overlay = new RuneScape.Module.ItemDetailOverlay({
   target: $itemShell
  });

  $('.results')
   .addClass('js')
   .delegate('a', 'click', function(ev){ ev.preventDefault(); })
   .delegate('tr', 'click', function(ev){var $this = $(this);

    $this.addClass('loading');
    overlay.vars.item = $this.data("itemId");
    overlay.setupView(function(success){

     if(!success){
      // ajax request failed, follow the link
      location = $this.find('a')[0].href;
      return;
     }

     var resH = $res.height();
     var isH = $itemShell.height();

     // calculate ideal position
     var t = $this.offset().top - resOTop + $this.height() / 2 - isH / 2;

     // Stop it going beyond the top of the page;
     t = Math.max(t, 0);

     // Stop it going beyond the bottom of the page
     if( t + isH > resH ){ t = resH - isH; }

     $this.removeClass('loading');
     $itemShell
      .css({
       top: t+'px'
      })
      .fadeIn();

    });

   })
  ;

 }

});

