﻿(function($) {

  $.fn.gPodmenu = function(options) {

    var caller = this;
    var initialListID, navlist, time = null;
    var crumbList = [];
    var i = 0;
 
    var opts = $.extend( 
    {
      filePath: "/pro/IboxServlet?p=IXS0523",
      refreshAjax: true,
      queryString: null,
      listWidth: 180,
      resetWhenInactive: true,
      resetPeriod: 3500
    }, options); 

    var filePath = (opts.refreshAjax || opts.queryString) ?
	
    (opts.filePath + '?' + ((opts.refreshAjax) ? 't=' + new Date().getSeconds() + '&' : '') + (opts.queryString))
    : opts.filePath;

    if (!navlist) {
      loadNavList();
    }


    function loadNavList() {
		
      $.ajax({
        type: "GET",
        url: "/pro/IboxServlet?p=IXS0523",
        dataType: "html",
        error: AjaxFail,
        success: buildMenu
      });
	
    };

    function AjaxFail(XMLHttpRequest, strStatus, strError) {
		
      caller.html('<div style="font-weight:bold;color:red;padding:5px;">Error:<br/>The menu was not able to load.<br/> Please refreshing your browser</div>  ');
      return;
    }

    function buildMenu(datalist, strStatus) {
		
      caller.empty();

      navlist = $(datalist);
      $('ul', navlist).css({ 'position': 'absolute', 'left': opts.listWidth * 2 + 'px', 'top': '0px' })
      .each(function() {
        var ul = $(this);
        ul.prev()
              .addClass('parent')
              .click(function(e) {
                e.preventDefault();
                goDown(ul.attr('id'));
              });
      });

      //append the screens and their breadcrumbs
      var rows = 0;
      $('ul', navlist).each(function(i) {
        var thisList = $(this).clone(true).each(function() { $('li>ul', this).remove(); });
        $('a', thisList).each(function() {
          if (this.href == window.location) {
            currentListID = ($(this).closest('ul').attr("id"));
            initialListID = currentListID
            $(this).parent().html(this.text).attr("id", "currentPage");
          }
        });
        if ($('li', thisList).size() > rows) { rows = $('li', thisList).size(); }
        caller.append(thisList);
        crumbList[this.id] = buildBreadcrumb($(this));
      });


      // restyle the conatiners and position the initial list
      caller
      .css({ 'position': 'absolute', 'width': opts.listWidth * 3 + 'px', 'left': opts.listWidth * -1 + 'px', 'top': 'auto' })
      .height((rows * 19) + 10)
      .parent().height((rows * 19) + 50);

      var currentList = $('#' + initialListID, caller).css({ 'left': opts.listWidth * 1 + 'px' });
      updateBreadcrumb(initialListID);
      navlist.remove();
      caller.parent().mouseenter(function(e) { clearReset(); }).mouseleave(function(e) { resetMenu(); })
      return;
    }

    function replaceStaticContent() {
      caller
      .css({ 'position': 'absolute', 'width': opts.listWidth * 3 + 'px', 'left': opts.listWidth * -1 + 'px', 'top': 'auto' })
      .height((rows * 19) + 10)
      .parent().height((rows * 19) + 50);

      var staticListID = $('ul:first', caller).attr("id");
      currentListID = staticListID;
      initialListID = currentListID;

      var currentList = $('#' + currentListID, caller).css({ 'left': opts.listWidth * 1 + 'px' });
      updateBreadcrumb(currentListID);
      caller.parent().mouseenter(function(e) { clearReset(); }).mouseleave(function(e) { resetMenu(); })
      navlist.remove();
      return;
    }


    function buildBreadcrumb(thisList) {
      return thisList.parents('ul').map(function() {
        var text = ($(this).prev().text() == '') ? 'Hem' : $(this).prev().text();
        return '<li><a href="#" rel="' + this.id + '">' + text + '</a></li>';
      }).get().reverse().join('');
    }

    function updateBreadcrumb(indexName) {
      var bc = $('#navCrumbDiv');
      bc.empty().append(crumbList[indexName])
      .find('a').click(function(e) { e.preventDefault(); goUp(this.rel) });
      bc.find('li').wrap('<ul>');
      bc.append('<div>' + indexName + '</div>').blur();
      return;
    }

    function goDown(nextListID) {
      $('#' + currentListID, caller)
      .animate({ left: '0px' }, 200, null, function() { setAsCurrent(nextListID) });
      $('#' + nextListID, caller).css({ 'left': opts.listWidth * 2 + 'px' })
      .animate({ left: opts.listWidth * 1 + 'px' }, 200);
      return;
    }
    function setAsCurrent(ListID) {
      updateBreadcrumb(ListID);
      currentListID = ListID;
      return;
    }

    function goUp(nextListID) {
      $('#' + currentListID, caller)
      .animate({ left: opts.listWidth * 2 + 'px' }, 200, null, function() { setAsCurrent(nextListID) });
      $('#' + nextListID, caller)
      .css({ 'left': '0px' })
      .animate({ left: opts.listWidth * 1 + 'px' }, 200);
      return;
    }


    function resetMenu() {
      if (opts.resetWhenInactive) {
        time = setTimeout(function() { resetToInitial(); }, opts.resetPeriod);
      }
    }
    function clearReset() {
      clearTimeout(time);
      return;
    }
    function resetToInitial() {
      var il_position = $('#' + initialListID).css('left').replace(/px/, '');
      if (il_position != opts.listWidth) {
        (il_position < opts.listWidth) ? goUp(initialListID) : goDown(initialListID);
      }
      clearTimeout(time);
      return;
    }



  }

})(jQuery);
