(function() {

  var DOM = YAHOO.util.Dom;
  var Event = YAHOO.util.Event;

  YAHOO.namespace('gaia.app');

  YAHOO.gaia.app.storefront = function() {
    var store_id = -1;
    var prev_store_id = 0;
    var cache = {
        'relateditems': {},
        'displays': {},
        'avatars': {},
        'listing': {}
    };

    var related = {
        '13':'babargains.html',
        '16': 'carshop.html',
        '18': 'cashshop.html',
        '9': 'faktori.html',
        '8': 'fishing.html',
        '23': 'phinphang.html',
        '14': 'prizejoy.html',
        'default': 'avatar.html'
    };

    var displays = {
        3: {'show': 4, 'total': 4 },
        1: {'show': 5, 'total': 15 },
        18: {'show': 5, 'total': 5 },
        14: {'show': 2, 'total': 2 },
        13: {'show': 1, 'total': 1 },
        22: {'show': 4, 'total': 4 },
        4: {'show': 2, 'total': 2 },
        9: {'show': 1, 'total': 1 },
        10: {'show': 1, 'total': 1 },
        16: {'show': 2, 'total': 2 },
        7: {'show': 4, 'total': 23, 'exclude': [20,21,22,23] },
        2: {'show': 5, 'total': 22, 'exclude': [3,4,5] },
        5: {'show': 4, 'total': 57 },
        6: {'show': 4, 'total': 10 },
        12: {'show': 10, 'total': 11,
             /* exclude (array): remove from the list of random images used */
             'exclude': [4,10, 11],
             /* static (object): never pick a random image for this position */
             'static': {4:true, 10:true},
             /* skip (object): never pick an image for this position */
             'skip': {5:true, 7:true, 8:true} },
        25: {'show': 4, 'total': 61, 'exclude': [5,37,38,39,40] },
        26: {'show': 2, 'total': 17 },
        23: [ {'swf': 'phinphang_candyCorn.swf', 'w': 115, 'h': 165 },
              {'swf': 'phinphang_memphis.swf', 'w': 112, 'h': 256 },
              {'swf': 'phinphang_turtle.swf', 'w': 100, 'h': 100 },
              {'swf': 'phinphang_peelunger.swf', 'w': 100, 'h': 100 },
              {'swf': 'phinphang_lt_omg.swf', 'w': 200, 'h': 200 },
              {'swf': 'phinphang_gramster.swf', 'w': 100, 'h': 100 }
            ]
    };

    var rand;
    var current_mo;
    var tp;

    return {

      init: function() {
        var SF = YAHOO.gaia.app.storefront;
        /* add click handler for directory entries */
        Event.addListener('store-navigation', 'click', SF.changeStore, {}, SF);
        Event.addListener('store-navigation', 'mouseover', SF.storeOver, {}, SF);
        Event.addListener('gaia_content', 'mouseover', SF.storeOut, {}, SF);

        if (YAHOO.env.ua.ie == 6) {
          Event.addListener('enter_store', 'mouseover', function(e) {
            var target = Event.getTarget(e);
            DOM.addClass(target, 'enter_hover');
          });

          Event.addListener('enter_store', 'mouseout', function(e) {
            var target = Event.getTarget(e);
            DOM.removeClass(target, 'enter_hover');
          });
        }

        tp = YAHOO.gaia.widgets.ToolPanel;
      },

      changeStore: function(e) {
        var target = Event.getTarget(e);
        var change = false;

        /* don't trigger a change store on the quick enter click */
        if (target.tagName.toLowerCase() == 'a') {
            return;
        }

        if (DOM.hasClass(target, 'store_listing')) {
          change = true;
        } else {
          target = DOM.getAncestorByClassName(target, 'store_listing');
          if (target != null) {
            change = true;
          }
        }

        if (!change) {
          return;
        }

        if (DOM.hasClass(target, 'disabled')) {
          return;
        }

        var sid = target.getAttribute('sid');
        if (store_id == sid) {
          return;
        }

        this.setActiveStore(sid, target);
        /* get avatars */
        this.getStoreAvatars();
        /* get displays */
      },

      setActiveStore: function(id, store_el) {
        if (id == store_id) {
          return;
        }

        /* default to 1 if not given a number */
        if (isNaN(parseInt(id))) {
          id = 1;
        }

        var div = DOM.get('store_landing');
        DOM.removeClass(div, 'store_' + store_id);
        DOM.addClass(div, 'store_' + id);

        div = DOM.get('bd');
        DOM.removeClass(div, 'store_' + store_id);
        DOM.addClass(div, 'store_' + id);

        /* remove the previous 'current' store */
        var el = this.getStoreListingDiv(store_id);
        if (el != null) {
          DOM.removeClass(el, 'current');
        }

        /* highlight the new 'current' store */
        var el = this.getStoreListingDiv(id);
        if (el != null) {
          DOM.addClass(el, 'current');
        }

        /* scroll to the select store on load */
        if ((store_el == null) && (id != 0)) {
          var store_nav = DOM.get('store-navigation');
          var offset = 0;

          var el = this.getStoreListingDiv(id);
          /* calculate offset based on store-navigation's offset */
          offset = el.offsetTop - store_nav.offsetTop;

          /* don't scroll for the first store */
          if (offset > 50) {
            store_nav.scrollTop = offset;
          }
        }

        var link = DOM.get('enter_link');
        var url = DOM.get('enter_' + id);
        if (url != null) {
          link.href = url.href;
        }

        prev_store_id = store_id;
        store_id = id;

        this.getRelatedItems();
        this.getStoreDisplays();
      },

      getStoreDisplays: function() {
        if (this.replaceStoreDisplays()) {
          return;
        }

        var div = document.createElement('div');
        div.id = 'display_' + store_id;

        if (displays[store_id] == null) {
          div.innerHTML = "";
        } else {
          if (store_id == 23) {
            var anim;
            var path = 'http://' + GAIA_config('graphics_server') +'/images/gaia_global/body/storefront/displays/';
            var display;

            for(i=0;  i < displays[store_id].length; i++) {
              display = document.createElement('div');
              DOM.addClass(display, 'mann' + (i+1));

              anim = document.createElement('embed');
              anim.setAttribute('type', 'application/x-shockwave-flash');
              anim.setAttribute('wmode', 'transparent');
              anim.width = displays[store_id][i]['w'];
              anim.height = displays[store_id][i]['h'];
              anim.src =  path + displays[store_id][i]['swf'];

              display.appendChild(anim);

              div.appendChild(display);
            }

            this.setStoreDisplays(div);
            this.replaceStoreDisplays();

            return;
          }

          var display;
          var total = displays[store_id]['total'];

          /* easy case.  just create a list of elements */
          if (displays[store_id]['total'] == displays[store_id]['show']) {
            for(i = 1; i <= total; i++) {
              display = document.createElement('div');
              DOM.addClass(display, 'mann' + i + ' ' + 'img' + i);

              div.appendChild(display);
            }
          } else {
            /* these shops have more images than there are displays.  pick the
               images to show at random */
            this.initRandom(total);

            var show_num = displays[store_id]['show'];

            if (displays[store_id]['exclude']) {
              this.initExcludeList();

              /* just in case: make sure we don't get stuck in an infinite loop */
              var total = displays[store_id]['total'] - displays[store_id]['exclude'].length;
              if (total < show_num) {
                show_num = total;
              }
            }

            for(i = 1; i <= show_num; i++) {
              if (displays[store_id]['skip'] && displays[store_id]['skip'][i]) {
                continue;
              }

              display = document.createElement('div');
              
              if (displays[store_id]['static'] && displays[store_id]['static'][i]) {
                DOM.addClass(display, 'mann' + i + ' ' + 'img' + i);
              } else {
                DOM.addClass(display, 'mann' + i + ' ' + 'img' + this.getRandom());
              }

              div.appendChild(display);
            }
          }
        }

        this.setStoreDisplays(div);
        this.replaceStoreDisplays();
      },

      getStoreAvatars: function() {
        if (this.replaceStoreAvatars()) {
          return;
        }

        YAHOO.util.Connect.asyncRequest('GET', '/market/avatars/' + store_id, {
          success: function(obj) {
            this.setStoreAvatars(obj.responseText);
            this.replaceStoreAvatars();
          },
          failure: function() {},
          scope: this
        });

      },

      getRelatedItems: function() {
        if (this.replaceRelatedItems()) {
          return;
        }

        YAHOO.util.Connect.asyncRequest('GET', '/static/market/' + this.getRelatedItemsFile(), {
          success: function(obj) {
            this.setRelatedItems(obj.responseText);
            this.replaceRelatedItems();
          },
          failure: function() {},
          scope: this
        });
      },

      setRelatedItems: function(content) {
        var id = this.getRelatedItemsId();
        cache['relateditems'][id] = content;
      },

      replaceRelatedItems: function() {
         /* nothing to do if this doesn't exist on the page */
        var ri = DOM.get('related_items');
        if (ri == null) {
          return true;
        }

        var id = this.getRelatedItemsId();
        if (cache['relateditems'][id] == undefined) {
          return false;
        }

        ri.innerHTML = cache['relateditems'][id];

        return true;
      },

      getRelatedItemsId: function() {
        if (related[store_id] != undefined) {
          return store_id;
        } else {
          return 'default';
        }
      },

      getRelatedItemsFile: function() {
        return related[this.getRelatedItemsId()];
      },


      setStoreDisplays: function(div) {
        if (div == null) {
          return;
        }

        var container = DOM.get('displays_container');
        container.appendChild(div);

        cache['displays'][store_id] = 1;
      },

      replaceStoreDisplays: function() {
        if (cache['displays'][store_id] == undefined) {
          return false;
        }

        var displays = DOM.get('storefront_displays');
        var container = DOM.get('displays_container');

        if (prev_store_id >= 1) {
          var old = DOM.get('display_' + prev_store_id);
          displays.removeChild(old);
          container.appendChild(old);
        }

        if (store_id >= 1) {
          var add = DOM.get('display_' + store_id);
          container.removeChild(add);
          displays.appendChild(add);
        }

        return true;
      },

      setStoreAvatars: function(content) {
        cache['avatars'][store_id] = {
            'ts': (new Date()).getTime()
        };

        var div = DOM.get('avatars_' + store_id);
        if (div == null) {
          div = document.createElement('div');
          div.id = 'avatars_' + store_id;

          var avis = DOM.get('storefront_avis');
          avis.appendChild(div);
        }

        div.innerHTML = content; 
      },

      replaceStoreAvatars: function() {
        if ( (cache['avatars'][store_id] == undefined) ||
               /* replace every 5 minutes */
             ( (cache['avatars'][store_id]['ts'] + (1000 * 60 * 5)) < (new Date()).getTime() ) ) {
          return false;
        }

        DOM.removeClass('avatars_' + prev_store_id, 'active');
        DOM.addClass('avatars_' + store_id, 'active');

        return true;
      },

      storeOver: function(e) {
        var target = this.getTargetStore(e);

        if (current_mo == target) {
          return;
        }

        DOM.removeClass(current_mo, 'active');

        current_mo = target;
        tp.hide();

        if (! DOM.hasClass(target, 'disabled')) {
          DOM.addClass(target, 'active');
        } else {
          target._orientation = tp.getOrientationClass(target, true);
          tp.setClicked(target);
          tp.show();
        }
      },

      storeOut: function(e) {
        if (current_mo == null) {
          return;
        }

        var target = this.getTargetStore(e);
        if (target == null) {
          DOM.removeClass(current_mo, 'active');
          current_mo = null;
          tp.hide();
        }
      },

      getTargetStore: function(e) {
        var target = Event.getTarget(e);

        if (! DOM.hasClass(target,'store_listing')) {
          target = DOM.getAncestorByClassName(target, 'store_listing');
        }

        return target;
      },

      getStoreListingDiv: function(store_id) {
          /* return it if cached */
          if (cache['listing'][store_id] != null) {
            return cache['listing'][store_id];
          }

          /* nothing to do if the cache has already been created and the store wasn't found */
          if (cache['listing']['cached'] != null) {
            return null;
          }

          /* cache all the store listings */
          var elements = DOM.getElementsByClassName('store_listing', 'div', 'store-navigation');
          var sid;

          for(i in elements) {
            sid = elements[i].getAttribute('sid');
            if (sid != null) {
              cache['listing'][sid] = elements[i];
            }
          }

          cache['listing']['cached'] = 1;

          if (cache['listing'][store_id] != null) {
            return cache['listing'][store_id];
          } else {
            return null;
          }
      },

      /* get a unique random number */
      getRandom: function() {
        var num;

        while(1) {
          num = Math.ceil(Math.random()*rand['max']);
          if (num && (rand[num] == null)) {
            rand[num] = 1;

            return num;
          }
        }
      },

      /* forget any previous random numbers and set the max */
      initRandom: function(max) {
        rand = {'max': max}
      },

      initExcludeList: function() {
        var list = displays[store_id]['exclude'];
        if (list == undefined) {
          return;
        }

        for(i = 0; i < list.length; i++) {
          rand[list[i]] = 1;
        }
      }
    };
  }();
}());
