if(typeof Array.prototype.indexOf === "undefined"){
  Array.prototype.indexOf = function(e){
    for(var i=0; i<this.length; i++){
      if(this[i] === e) return i;
    }
    return -1;
  };
};

function dispatch(map){
  var path = location.href.replace(root_path, "");
  $.each(map, function(key, fn){
    var m;
    m = path.match(key);
    if(m) $(function(){fn.apply(null, m);});
  });
}

$.fn._mouseover_freeze = function(){
  var src = $(this).attr("src");
  $(this).attr("src", src.replace(".png", "_h.png")).unbind("mouseover").unbind("mouseout");
};

dispatch({
  "": function(){
    $(".hover").each(function(){
      var img = $(this);
      var src = $(this).attr("src");
      img.hover(function(){
        img.attr("src", src.replace(".png", "_h.png"));
      }, function(){
        img.attr("src", src);
      });
    });

    // collection menu
    var collections = $("#main-menu .collections-list");
    $("#main-menu .collections").click(function(){
      if(collections.queue().length !== 0) return;
      if(collections.css("display") === "none"){
        collections.css("opacity", 0).slideDown(600).animate({opacity: 1}, 600);
      }else{
        collections.animate({opacity: 0}).slideUp(600);
      }
    });

    if($("#welcome").length !== 0){
      (function(){
        var imgs = $("#welcome .animation img").map(function(){return $(this);});
        var enter = $("#welcome .enter");
        enter.css({opacity: 0, display: "block"});

        setTimeout(function(){
          imgs[0].fadeIn(1500, function(){
            imgs[1].fadeTo(500, 0.3, function(){
              imgs[1].fadeOut(2000);
            });
            imgs[2].fadeIn(2500);
            setTimeout(function(){
              enter.animate({opacity: 1}, 1000);
              enter.find("img").animate({"margin-top": "6px"}, 600);
            }, 2000);
          });
        }, 500);
      })();
    }
  },

  "^/top$": function(){
    var imgs = $("#main-visual img").map(function(){return $(this);});
    var current = 0;
    imgs[current].show();
    var animation = function(){
      var next = (current + 1) % imgs.length;
      imgs[current].fadeOut(2500);
      imgs[next].fadeIn(2500, function(){
        current = next;
        setTimeout(animation, 4000);
      });
    };

    setTimeout(animation, 4000);
  },

  "^/(news|our-brand|shop|contact|company)": function(m1, m2){
    $("#main-menu ."+m2)._mouseover_freeze();
  },

  "^/news": function(){
    (function(){
      var container = $("#news .list");
      if(container.length !== 0){
        var items = container.find(".item");
        var boxes = [
          $('<div class="list-box" />').appendTo(container),
          $('<div class="list-box" />').appendTo(container),
          $('<div class="list-box" />').appendTo(container)
        ];
        var box_heights = [0, 0, 0];
        items.each(function(i, item){
          setTimeout(function(){
            var min_box_index = box_heights.indexOf(Math.min.apply(null, box_heights));
            boxes[min_box_index].append($(item).fadeIn());
            box_heights[min_box_index] += 1;
          }, 100*i);
        });
      }
    })();

    $(".back img").click(function(){
      history.back();
    });
  },

  "^/new-arrivals$": function(){
    $("#main-menu .collections-list").show();
    $("#main-menu .collections")._mouseover_freeze();
    //$("#main-menu .new-arrivals")._mouseover_freeze();
  },

  "^/collections/.*": function(){
    $("#main-menu .collections-list").show();
    $("#main-menu .collections")._mouseover_freeze();
  },

  "^/collections/mens/standard": function(){
    //$("#main-menu .standard")._mouseover_freeze();
  },

  "^/(top|news|our-brand|shop|contact|company|collections)": function(){
    $.cookie("cat_items_padding", "", {path: "/"});    
  },

  "^/collection/[^\\/]+?$": function(){
    $("#main-menu .collections-list").show();
    $("#main-menu .collections")._mouseover_freeze();

    /* category items */
    (function(){
      var container = $(".same-category-items");
      var ul = container.find("ul");
      var left_max = parseInt(ul.css("left"));
      var left_min = left_max - (ul.find("li").length - 4) * 140;

      ul.find("li").each(function(i){
        $(this).css("left", i * 140 + "px");
      });

      var cat_items_padding = parseInt($.cookie("cat_items_padding", {path: "/"}) || ul.css("left"));
      if(left_min <= cat_items_padding && cat_items_padding <= left_max){
        ul.css("left", cat_items_padding + "px");
      }

      container.find(".prev").click(function(){
        var left = parseInt(ul.css("left")) + 140;
        if(ul.queue().length === 0 && left <= left_max){
          ul.animate({"left": left+"px"});
          $.cookie("cat_items_padding", left, {path: "/"});
        }
      });
      container.find(".next").click(function(){
        var left = parseInt(ul.css("left")) - 140;
        if(ul.queue().length === 0 && left >= left_min){
          ul.animate({"left": left+"px"});
          $.cookie("cat_items_padding", left, {path: "/"});
        }
      });
    })();

    /* main image changer */
    (function(){
      var timeout_id;
      var main_image = $("#collections .detail .image img");
      main_image.data("src", main_image.attr("src"));

      $("#collections .detail .variations a img").hover(function(){
        if(timeout_id) clearTimeout(timeout_id);
        main_image.attr("src", $(this).attr("data-main-image"));
      }, function(){
        timeout_id = setTimeout(function(){
          main_image.attr("src", main_image.data("src"));
        }, 150);
      });
    })();

    /* lightbox */
    $("a[rel='lightbox']").lightBox();
  },

  "^/contact": function(){
    $("#contact .back").click(function(){
      $("[name='contact-action']").attr("value", "back");
      $("#contact").submit();
    }).css("cursor", "pointer");
  }
});


/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {
  // key and at least value given, set cookie...
  if(arguments.length > 1 && String(value) !== "[object Object]"){
    options = jQuery.extend({}, options);
    if (value === null || value === undefined) {
      options.expires = -1;
    }
    if (typeof options.expires === 'number') {
      var days = options.expires, t = options.expires = new Date();
      t.setDate(t.getDate() + days);
    }

    value = String(value);

    return (document.cookie = [
      encodeURIComponent(key), '=',
      options.raw ? value : encodeURIComponent(value),
      options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
      options.path ? '; path=' + options.path : '',
      options.domain ? '; domain=' + options.domain : '',
      options.secure ? '; secure' : ''
    ].join(''));
  }

  // key and possibly options given, get cookie...
  options = value || {};
  var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
  return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

