var main = function() {
  var isSmartPhone = /AppleWebKit/.test(navigator.userAgent) && /(Mobile|Android)/.test(navigator.userAgent);
  var isIE6 = $.browser.msie && Math.floor($.browser.version) == 6;
  var isIE7 = $.browser.msie && Math.floor($.browser.version) == 7;
  var isIE8 = $.browser.msie && Math.floor($.browser.version) == 8;
  var isIOS = /iphone|ipad|ipod/i.test(navigator.userAgent);

  if(isIE6) document.execCommand('BackgroundImageCache', false, true);
  if (isIOS) {
    $('body,#wrap').css({ width:1100 });
    $('.navi>li').css({ width:194 });
    $('#side ul.sub-navi li a').css({ width:149 });
  }

  // rollover
  $('.rollover').live('mouseover mouseout', function(e) {
    if(isSmartPhone) return;
    if(isIE6 || isIE7 || isIE8) {
      if(e.type == 'mouseover') $(this).css('backgroundPositionY', 'bottom');
      else if(e.type == 'mouseout') $(this).css('backgroundPositionY', 'top');
      return;
    }
    if($(this).hasClass('not')) return;
    var span = $(this).find('.rollover_s');
    if(!span.length) {
      span = $('<span class="rollover_s"></span>');
      $(this).append(span);
      var pos = [
        $(this).css('backgroundPositionX'),
        $(this).css('backgroundPositionY')
      ];
      if(!pos[0]) pos = $(this).css('backgroundPosition').split(' ');
      var y = (pos[1] == 'top') ? 'bottom' : '100%';
      var x = pos[0];
      var i = $(this).css('backgroundImage');
      span.css({backgroundPosition: x + ' ' + y, backgroundImage: i});
    }
    var duration = 240;
    var cls = $(this).attr('class') || '';
    var m = cls.match(/(?:^|\s)d(\d+)/);
    if(m) duration = parseInt(m[1]);
    if(e.type == 'mouseover') {
      span.stop().fadeTo(duration, 1.0);
    }else if(e.type == 'mouseout') {
      span.stop().fadeTo(duration * 1.5, 0.0);
    }
  });
  $('#side').live('mouseover mouseout', function(e) {
    if(e.type == 'mouseover') $('#content').css('z-index', -1);
    else if(e.type == 'mouseout') $('#content').css('z-index', 1);
  });

  // popup
  jQuery.extend({wopen: function(url, name, w, h) {
    var win;
    var centerH = (screen.height-h) / 2;
    var centerW = (screen.width-w) / 2;
    win = window.open(url, name, 
      'toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=yes,resizable=yes,width='
      + w + ',height=' + h + ',left=' + centerW + ',top=' + centerH + ''
    );
    win.focus();
  }});
  $('a.popup,area.popup').live('click', function () {
    var w = 950;
    var h = 700;
    var cls = $(this).attr('class') || '';
    var m = cls.match(/(?:^|\s)w(\d+)/);
    if(m) w = parseInt(m[1]);
    m = cls.match(/(?:^|\s)?h(\d+)/);
    if(m) h = parseInt(m[1]);
    var t = $(this).attr('target') || '_blank';
    $.wopen($(this).attr('href'), t, w, h);
    return false;
  });

  // setup navigation
  $('#side ul.navi li:has(ul.sub-navi)').hover(
    function() {
      if(isIE6) $(this).find('ul.sub-navi').show(1);
      else $(this).find('ul.sub-navi').fadeIn(180);
    },
    function() {
      $(this).find('ul.sub-navi').fadeOut(180);
    }
  );

  // load unload functions
  var that = {};
  jQuery.fn.extend({
    contentLoad: function(func) {
      if(func) {
        that.contentLoad = func;
      } else {
        if(that.contentLoad) that.contentLoad.apply(this);
        that.contentLoad = function() {};
      }
    },
    contentUnload: function(func) {
      if(func) {
        that.contentUnload = func;
      } else {
        if(that.contentUnload) that.contentUnload.apply(this);
        that.contentUnload = function() {};
      }
    },
    iOSSpriteFix: function() {
      if (!isIOS) {
        return;
      }
      $(this).each(function (index, element) {
        var match = $(this).css('backgroundImage').match(/url\((.+)\)/);
        if (match) {
          var w = $(this).css('width'), h = $(this).css('height'), pos = [
            $(this).css('backgroundPositionX'),
            $(this).css('backgroundPositionY')
          ];
          var img = new Image();
          img.onload = function () {
            var match;
            if (match = pos[0].match(/(\d+)%/)) {
              pos[0] = (parseInt(w) - img.width) * match[1] / 100;
            } else if (match = pos[0].match(/(\d+)px/)) {
              pos[0] = -parseInt(match[1]);
            }
            if (match = pos[1].match(/(\d+)%/)) {
              pos[1] = (parseInt(h) - img.height) * match[1] / 100;
            } else if (match = pos[1].match(/(\d+)px/)) {
              pos[1] = -parseInt(match[1]);
            }
            var canvas = $('<canvas></canvas>').attr({ width:w, height:h });
            var context = canvas.get(0).getContext('2d');
            context.drawImage(img, pos[0], pos[1]);
            $(element).css({ backgroundImage:'url(' + canvas.get(0).toDataURL() + ')' });
            
            if ($(element).hasClass('rollover') && $(element).find('.rollover_s').length == 0) {
              pos[1] = parseInt(h) - img.height;
              context.drawImage(img, pos[0], pos[1]);
              $('<span class="rollover_s"></span>').appendTo($(element)).css({ backgroundImage:'url(' + canvas.get(0).toDataURL() + ')' });
            }
          };
          img.src = match[1];
        }
      });
    }
  });
  
  $('.rollover').iOSSpriteFix();

  // rewrite urls
  var replaceUrl = function(link) {
    link.each(function() {
      var href = $(this).attr('href');
      if(href.indexOf('http://' + location.host) == 0) {
        href = href.replace('http://' + location.host, ''); 
      }
      var newhref = '';
      if(/^\/contents/.test(href)) {
        newhref = href.replace(/^\/contents\//, '#/').replace(/\.html$/, '/');
      } else if(href == '/') {
        newhref = '/#/index';
      } else {
        return;
      }
      $(this).attr('href', newhref);
      $(this).click(function() {
        var href = $(this).attr('href');
        if(!/^#/.test(href)) return true;
        //loader(href);
      });
    });
  };
  replaceUrl($('a'));


  // ajax
  var loader = function(hash) {

    var fade = function() {
      var d = $.Deferred();
      $('#content').fadeTo(500, 0.0, d.resolve);
      return d.promise();
    };
    var ajax = function() {
      var url = hash.replace(/#\//, '/contents/').replace(/\/$/, '') + '.html';
      return $.get(url);
    };
    $.when(ajax(), fade()).then(function(res) {
      $().contentUnload();
      var html = res[0].replace(/^[\S\s]*<!-- content -->/, '')
                       .replace(/<!-- \/content -->[\S\s]*$/, '');
      $('html, body').stop().animate({'scrollTop': 0}, 250);
      $('#content').html(html).fadeTo(500, 1.0, function() {
        replaceUrl($('#content a'));
      });
      $('#content .rollover, .sample-grid *').iOSSpriteFix();
      $('.navi .rollover').removeClass('not');
      $('.navi .rollover_s').hide();
      $('.navi .rollover[href="' + hash + '"]').addClass('not');
      $('.navi ul.sub-navi').hide();
      $('#content').css('z-index', 1);
      // fix height
      $('#side .banners').css('margin-bottom', 0);
      var df = $('html,body').height() - $('#side').height();
      $('#side .banners').css('margin-bottom', (df > 0) ? df : 0);
      if(isSmartPhone) {
        if(/^#\/index/.test(hash)) {
          $('#content').css({'margin-left': 195, width: 829});
          $('#top-image img').css({width: 829, height: '590px !important'});
        } else {
          $('#content').css({'margin-left': 210});
        }
      }
      $().contentLoad();
      // google analytics
      _gaq.push(['_trackPageview', location.pathname + location.hash]); 
    }).fail(function() {
      $('#content').html('<p class="p404">お探しのページが見つかりません</p>').fadeTo(500, 1.0);
    })
  };
  
  // intro
  if (location.hash.length < 2 && !isSmartPhone) {
    location.hash = '#/intro/';
  }
  
  // url routing
  var hash = location.hash.length > 1 ? location.hash : '#/index/';
  loader(hash);
  
  var title = document.title;
  
  setInterval(function () {
    var new_hash = location.hash.length > 1 ? location.hash : '#/index/';
    if (hash != new_hash) {
      hash = new_hash;
      loader(hash);
    }
    var new_title = document.title;
    if (new_title.charAt() == '#') {
        document.title = title;
    } else {
        title = new_title;
    }
  }, 100);

  // pre-load menu images
  for(var cache = [], i = 0; i < 29; i++) {
    var f = '/images/navi/productsdetail-navi' + ('0' + i).slice(-2) + '.png';
    cache.unshift(new Image());
    cache[0].src = f;
  }
};

$(main);


function opwin_webmember(){
  wopen("","addictionWebmember",780,700);
}

// google analytics
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-25407273-1']);
_gaq.push(['_trackPageview']);
(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();



