$(function() {
 
  var isLarge = $('html').hasClass('large');

  var DEFAULT_URL = 'http://blog.honeyee.com/jtakahashi/'
    , GYAKUSOU_URL = 'http://inside.nike.com/blogs/nikerunning_news-ja_JP/2011/10/13/-gyakusou-fall-holiday-2011-1015-/'
    /* 
    , MENS_NEWS_RESOURCE = 'data/mens_news.json'
    , WOMENS_NEWS_RESOURCE = 'data/womens_news.json'
    , MENS_NEWS_LARGE_RESOURCE = 'data/mens_news_large.json'
    , WOMENS_NEWS_LARGE_RESOURCE = 'data/womens_news_large.json'
    , MENS_SONG_RESOURCE = 'data/mens_song.json'
    , WOMENS_SONG_RESOURCE = 'data/womens_song.json'
    */
    , MENS_NEWS_RESOURCE = '/api/?post_type=mensnews&feed=json'
    , WOMENS_NEWS_RESOURCE = '/api/?post_type=womensnews&feed=json'
    , MENS_NEWS_LARGE_RESOURCE = '/api/?post_type=mensnewsl&feed=json'
    , WOMENS_NEWS_LARGE_RESOURCE = '/api/?post_type=womensnewsl&feed=json'
    , MENS_SONG_RESOURCE = '/api/?post_type=menssong&feed=json'
    , WOMENS_SONG_RESOURCE = '/api/?post_type=womenssong&feed=json'
   
    , MENS_COLLECTION_RESOURCE = 'data/mens_collection.json'
    , WOMENS_COLLECTION_RESOURCE = 'data/womens_collection.json'
    , MENS_SPECIAL_RESOURCE = 'data/mens_special.json'
    , MENS_COLLECTION_LARGE_RESOURCE = 'data/mens_collection_large.json'
    , WOMENS_COLLECTION_LARGE_RESOURCE = 'data/womens_collection_large.json'
    , MENS_SPECIAL_LARGE_RESOURCE = 'data/mens_special_large.json'
    , STORE_RESOURCE = 'data/store.json'
    , FEATURED_RESOURCE = 'data/featured.json'
    , FEATURED_LARGE_RESOURCE = 'data/featured_large.json';

  var URL_LIST = [
    'http://www.amazon.co.jp',
    'http://wikipedia.org',
    'http://myspace.com',
    'http://msn.com',
    'http://foursquare.com',
    'http://vimeo.com/',
    'http://www.baidu.jp/'
  ];

  var mensNews = new undercover.DataSource(isLarge ? MENS_NEWS_LARGE_RESOURCE : MENS_NEWS_RESOURCE)
    , womensNews = new undercover.DataSource(isLarge ? WOMENS_NEWS_LARGE_RESOURCE : WOMENS_NEWS_RESOURCE)
    , mensCollection = new undercover.DataSource(isLarge ? MENS_COLLECTION_LARGE_RESOURCE : MENS_COLLECTION_RESOURCE)
    , mensSpecial = new undercover.DataSource(isLarge ? MENS_SPECIAL_LARGE_RESOURCE : MENS_SPECIAL_RESOURCE)
    , womensCollection = new undercover.DataSource(isLarge ? WOMENS_COLLECTION_LARGE_RESOURCE : WOMENS_COLLECTION_RESOURCE)
    , featured = new undercover.DataSource(isLarge ? FEATURED_LARGE_RESOURCE : FEATURED_RESOURCE)
    , mensSong = new undercover.DataSource(MENS_SONG_RESOURCE)
    , womensSong = new undercover.DataSource(WOMENS_SONG_RESOURCE);

  var welcomeBlink = new undercover.Blinker('#mensWelcomeTop', function(elem) { elem.toggleClass('welcome'); }, 200)
    , initialUrl = URL_LIST[Math.floor(Math.random() * URL_LIST.length)];

  var $window = $(window)
    , $boxes = $('#wrapper .box');

  var manager = new Utakata('#wrapper')
    , nametake = $('#wrapper').nametake({enablePreloader: false, changeHash: false});

  var changeBackgroundTo = function(url) {
    var $bg = $('#bg:visible');
    if ($bg.length > 0 && $bg.attr('src') !== url) $bg.attr('src', url);
  };

  if (isLarge) {
    $('img:not(.fix)').each(function(i, elem) {
      if (elem.src.match(/\.(jpg|png|gif)$/)) {
        elem.src = elem.src.replace('/images/', '/large/images/');
      }
    });
  }

  nametake.on('initialize', function() {
    $('#chara1').css('right', '-130px').animate({right:'70px'}, 2000);
    $('#chara2').css('right', '-330px').animate({right:'-110px'}, 2000);
    this.moveTo('/entrance');
  });

  nametake.of('/*', function(scene) {
    scene
      .start(function(next) {
        $(scene.element)
          .find('.box').filter(':visible').each(function(i, box) {
            setTimeout(function() { manager.getBox(box.id).close(); }, i * 100);
          });
        if (scene.id === '/womens') $(scene.element).find('.overlay').css('display', 'none');
        next();
      })
      .end(function(next) {
        $(scene.element)
          .find('.box').filter(":not(.hide)[data-utakata-tags*='" + scene.id.slice(1) + "Top']").each(function(i, box) {
            setTimeout(function() { manager.getBox(box.id).open(); }, i * 100 + 200);
          });
        next();

        if (scene.id == '/womens') {
          $('#chara1').css('display', 'none');
          $('#chara2').css('display', 'none');
          $(scene.element).find('.overlay').css('display', 'block');
          $('.apple').css('display', 'block');
          manager.emit('tagchange', 'womensTop');
        } else {
          $('#chara1').css('display', 'block');
          $('#chara2').css('display', 'block');
          $('.apple').css('display', 'none');
          manager.emit('tagchange', 'mensTop');
        }
      });
  });
  
  manager.on('tagchange', function(tagName) {
    $.each(manager.getBoxes(function(box) { return /Navigation$/.test(box.id); }), function(i, box) {
      box.element.find('li').each(function() {
        // all items (except stream) are active on top tag
        if (tagName == 'womensTop' || tagName == 'mensTop' || this.className.split(' ').indexOf(tagName) > -1) {
          if(!(this.className.split(' ').indexOf('mensStream') > -1 || this.className.split(' ').indexOf('womensStream') > -1))
            $(this).addClass('active');
        } else {
          $(this).removeClass('active');
        }
      });
    });
  });


  manager.of(/News$/, function(box) {
    var $articles = box.element.find('.articles');
    var news = box.id === 'mensNews' ? mensNews : womensNews
      , loader = news.load(10);
    
    box
      .on('initialize', function() {
        var that = this
          , renderer = new undercover.Renderer('#newsTemplate', $articles);

        loader
          .done(function() {
            that.success();
          })
          .fail(function() {
            that.error();
          });

        $articles.live('datachange.news', function() {
          renderer
            .render({ articles: news.getItem() })
            .done(function(tmpl) {
              var $prev = tmpl.find('.prev')
                , $next = tmpl.find('.next');
              (news.hasPrev() ? undercover.utils.activate : undercover.utils.deactivate).call(null, $prev);
              (news.hasNext() ? undercover.utils.activate : undercover.utils.deactivate).call(null, $next);
              $articles.scrollable({visibleHeight: $articles.height()});
            });
        });

        this.element.find('.anchor').live('click', function() {
          $.data($articles.get(0), 'api').scrollTo(0);
        });

        this.element.find('.pager a:has(.prev)').live('click', function() {
          news.prev();
          $articles.trigger('datachange.news');
        });
      
        this.element.find('.pager a:has(.next)').live('click', function() {
          news.next();
          $articles.trigger('datachange.news');
        });      
      })
      .on('open', function() {
        var that = this;
        $.when(loader).done(function() {
          news.goTo(1);
          $articles.trigger('datachange.news');
        });
      });
    //同じデータを共有しているので中に書く...
    if (box.id === 'mensNews') {
      manager.of('mensNews1Top', function(box) {
        box.on('initialize', function() {
          var that = this
            , renderer = new undercover.Renderer('#newsTopTemplate', box.element.find('.newsTop'));
          $.when(loader)
            .done(function() {
              that.success();
              renderer.render(news.getAll()[0]);
            })
            .fail(function() {
              that.error();
            });
        });
      });
      manager.of('mensNews2Top', function(box) {
        box.on('initialize', function() {
          var that = this
            , renderer = new undercover.Renderer('#newsTopTemplate', box.element.find('.newsTop'));
          $.when(loader)
            .done(function() {
              that.success();
              renderer.render(news.getAll()[1]);
            })
            .fail(function() {
              that.error();
            });
        });
      });
    }
    if (box.id === 'womensNews') {
      manager.of('womensNewsTop', function(box) {
        box.on('initialize', function() {
          var that = this
            , renderer = new undercover.Renderer('#womensNewsTopTemplate', box.element.find('.womensNewsTop'));
          $.when(loader)
            .done(function() {
              that.success();
              renderer.render(news.getAll()[0]);
            })
            .fail(function() {
              that.error();
            });
        });
      });
    }

  });
  
  manager.of('mensGyakusouTop', function(box) {
    box
      .on('initialize', function() {
        this.element.find('a').live('click', function(e) {
          e.preventDefault();
          changeBackgroundTo(GYAKUSOU_URL);
        });
      });
  });
  
  manager.of(/Collection$/, function(box) {
    var $list = box.element.find('.list')
      , $detail = box.element.find('.detail')
      , $prev = box.element.find('.detail .prev')
      , $next = box.element.find('.detail .next');

    var collection = box.id === 'mensCollection' ? mensCollection : womensCollection
      , loader = collection.load(1);
    var maxNumber = 0;

    box
      .on('initialize', function() {
        var that = this
          , collectionRenderer = new undercover.Renderer('#collectionTemplate', $list)
          , descriptionRenderer = new undercover.Renderer('#collectionDescriptionTemplate', this.children[0].element);

        loader
          .pipe(function() {
            that.success();
            var data = collection.getAll();
            for(var i = 0; i < data.length; i++)
              if(parseInt(data[i].number) > maxNumber) maxNumber = parseInt(data[i].number);
            return collectionRenderer.render(collection.getAll());
          })
          .fail(function() {
            that.error();
          });

        $list.live('mouseleave', function() {
          that.element.find('dl dd').stop(true, true).fadeIn();
        });

        $prev.live('click', function() {
          collection.prev();
          $detail.trigger('datachange.collection');
        });

        $next.live('click', function() {
          collection.next();
          $detail.trigger('datachange.collection');
        });

        $list.live('datachange.collection', function() {
          $list.stop(true, true).fadeOut();
          $.each(that.children, function(i, box) {
            box.open();
          }); 
        });

        $detail.live('datachange.collection', function() {
          var $img = $detail.find('p img');
          var data = collection.getItem()[0];          
          collection.hasPrev() ? $prev.show() : $prev.hide();
          collection.hasNext() ? $next.show() : $next.hide(); 
          $detail.show();
          $img.attr('src', data.imageUrl);
          descriptionRenderer
            .render({
              max: maxNumber,
              number: data.number,
              description: data.description
            });
        });
        
        $list.find('dl')
          .live('mouseenter', function() {
            var that = this;
            $list.find('dl').each(function() {
              if (that === this) {
                $(this).find('dd').stop(true, true).fadeIn();
              } else {
                $(this).find('dd').stop(true, true).fadeOut();
              }
            });
          })
          .live('click', function() {
            collection.goTo($list.find('dl').index(this) + 1);
            $list.trigger('datachange.collection');
            $detail.trigger('datachange.collection');
          });
      })
      .on('open', function() {
        $detail.hide();
        $list.show();
        $.when(loader)
          .done(function() {
            $list.scrollable({visibleHeight: $list.height()});
          });
      });
  });
  
  manager.of(/CollectionDescription$/, function(box) {
    box
      .on('initialize', function() {
        var that = this;
        this.element.find('.backToList').live('click', function() {
          var $parent = that.parents[0].element;
          that.close();
          $parent.find('.list').stop(true, true).fadeIn();
          $parent.find('.detail').stop(true, true).fadeOut();
        });
      });
  });

  manager.of('mensSpecial', function(box) {
    var $list = box.element.find('.list');

    var collection = mensSpecial
      , loader = collection.load(1);

    box
      .on('initialize', function() {
        var that = this
          , collectionRenderer = new undercover.Renderer('#collectionTemplate', $list);

        loader
          .pipe(function() {
            that.success();
            var data = collection.getAll();
            return collectionRenderer.render(collection.getAll());
          })
          .fail(function() {
            that.error();
          });

        $list.live('mouseleave', function() {
          that.element.find('dl dd').stop(true, true).fadeIn();
        });

        $list.live('datachange.collection', function() {
          var detail = that.children[0];
          var $image = $(new Image());
          $image
            .bind('load', function() {
              detail.element.find('.image').empty()
                .animate({ width: $image.get(0).width, height: $image.get(0).height }, 200)
                .append($image.hide().fadeIn());
            })
            .attr('src', collection.getItem()[0].imageUrl);
          detail.open();
        });
        
        $list.find('dl')
          .live('mouseenter', function() {
            var that = this;
            $list.find('dl').each(function() {
              if (that === this) {
                $(this).find('dd').stop(true, true).fadeIn();
              } else {
                $(this).find('dd').stop(true, true).fadeOut();
              }
            });
          })
          .live('click', function() {
            collection.goTo($list.find('dl').index(this) + 1);
            $list.trigger('datachange.collection');
            $('#mensSpecialDetail').css('zIndex', manager.getMaxDepth(box));
          });
      })
      .on('open', function() {
        $list.show();
        $.when(loader)
          .done(function() {
            $list.scrollable({visibleHeight: $list.height()});
          });
      });
  });

  manager.of('mensSpecialDetail', function(box) {
    box.on('close', function() {
      box.element.find('.image').empty().css({ width: 'auto', height: 'auto' });
    });
  });

    
  manager.of(/Store$/, function(box) {
    var $column = box.element.find('.column')
      , $detail = box.element.find('.detail');

    var store = new undercover.StoreSource(STORE_RESOURCE)
      , loader = store.load(0);

    box
      .on('initialize', function() {
        var that = this
          , renderer = new undercover.Renderer('#storeDetailTemplate', $detail)
          , numOfColumns = this.element.find('.column').length
          , prefix = 'menuItem';
        
        loader
          .pipe(function() {
            that.success();
            $column.filter(':lt(3)').each(function(i, elem) {
              //ここは画像もなく単純なのでRendererを経由しない
              $('#storeCategoryTemplate').tmpl(store.getNodeList(i)).appendTo(elem);             
            });
            return renderer
              .render(store.getNodeList(3))
              .done(function(tmpl) {
                if (box.id !== 'mensStore') tmpl.find('.gmap').hide();
              });
          })
          .fail(function() {
            that.error();
          });

        this.element.find('.gmap a').live('click', function() {
          that.children[0].open();
        });

        this.element.find('.item').live('datachange.store', function(e, id) {
          var $this = $(this);
          var menuId = this.getAttribute('data-treemenu-id')
            , nthItem;
          if (menuId === prefix || new RegExp(menuId + '([^0-9]|$)').test(prefix + id)) {
            nthItem = id.split('-')[depthOf(menuId)];            
            $this.find('li').each(function(i, elem) {
              if (i + 1 === parseInt(nthItem, 10)) {
                $(this).addClass('select');
              } else {
                $(this).removeClass('select');                  
              }
            });
            $this.stop(true, true).fadeIn();
          } else {
            $this.stop(true, true).fadeOut();
          }
        });

        var parseId = function(id) {
          return id.split(prefix)[1];
        };

        var depthOf = function(id) {
          if (id === prefix) {
            return 0;
          } else {
            return id.replace(/[^-]/g, '').length + 1;
          }
        };

        var firstStoreOf = function(id) {
          var i = numOfColumns - depthOf(id)
            , storeId = parseId(id);
          while (i > 1) {
            storeId += '-1';
            i--;
          }
          return store.getStore(storeId);
        };

        this.element.find('.item li a').live('click', function(e, reserveBg) {
          var $item = $(this).parents('.item')
            , $gmap = that.children[0].element.find('.mapFrame');
          
          var i = $item.find('a').index($(this))
            , id = $item.attr('data-treemenu-id')
            , depth = depthOf(id)
            , targetId = id + (depth === 0 ? '' : '-') + (i + 1);
          that.element.find('.item').trigger('datachange.store', firstStoreOf(targetId).itemId);
          changeBackgroundTo(firstStoreOf(targetId).streetView);
          if ($gmap.is(':visible')) $gmap.attr('src', firstStoreOf(targetId).locationMap);
          $.data(that.children[0].element.get(0), 'gmapUrl', firstStoreOf(targetId).locationMap);
          $(that.children[0].element).find('h2').text(firstStoreOf(targetId).name);
          $(that.children[0].element).find('h3').text(firstStoreOf(targetId).name);
        });
      })
      .on('open', function() {
        var that = this;
        this.element
          .find('.item').hide()
          .find('li').removeClass('select');
        $.when(loader)
          .done(function() {
            $.each(store.getNodeList(3), function(i, data) {
              var $menuItem;
              if (data.selectDefault) {
                that.element
                  .find(".store .item[data-treemenu-id='menuItem" + data.itemId.slice(0, data.itemId.lastIndexOf('-'))  + "']")
                  .find('li:eq(' + (data.itemId.slice(data.itemId.lastIndexOf('-') + 1) - 1) + ') a')
                  .trigger('click');
              }
            });
          });
      })
      .on('close', function() {
        changeBackgroundTo(initialUrl);
      });
  });

  manager.of('mensMap', function(box) {
    box.on('close', function() {
      this.element.find('.mapFrame').attr('src', '');
    });
  });

  manager.of('womensFeatureTop', function(box) {
    var $products = box.element.find('.products');
    var loader = featured.load(1)
      , renderer = new undercover.Renderer('#womensFeatureTopTemplate', box.element.find('.products'));

    box.on('initialize', function() {
      var $prev = box.element.find('.prev')
        , $next = box.element.find('.next');
      
      var that = this;

      loader
        .done(function() {
          that.success();
        })
        .fail(function() {
          that.error();
        });
      
      this.element.find('.pager a:has(.prev)').live('click', function() {
        featured.prev();
        $products.trigger('datachange.featured');
      });

      this.element.find('.pager a:has(.next)').live('click', function() {
        featured.next();
        $products.trigger('datachange.featured');
      });
      
      $products.live('datachange.featured', function() {
        (featured.hasPrev() ? undercover.utils.activate : undercover.utils.deactivate).call(null, $prev);
        (featured.hasNext() ? undercover.utils.activate : undercover.utils.deactivate).call(null, $next);
        renderer.render(featured.getItem());
      });
    });

    box.on('open', function() {
      $.when(loader)
        .done(function() {
          featured.goTo(1);
          box.element.find('.products').trigger('datachange.featured');
        });
    });
  });

  
  manager.of(/^womensFeature0[0-9]$/, function(box) {
    var $photo = box.element.find('.photo a');
    
    var loader = featured.load(1)
      , renderer = new undercover.Renderer('#womensFeatureTemplate', box.element.find('.products'));

    box.on('initialize', function() {
      var that = this;

      loader
        .done(function() {
          that.success();
          featured.goTo(box.id.charAt(box.id.length - 1));
          if (featured.getItem().length === 0) box.element.remove();
          renderer.render(featured.getItem()[0]);
        })
        .fail(function() {
          that.error();
        });
      
      $photo.live('click', function() {
        featured.goTo(box.id.charAt(box.id.length - 1));
        $.each(manager.getBoxes(function(box) { return box.id.match(/^womensFeature0[0-9]$/); }), function(i, box) {
          box.close();
        });
        manager.getBox('womensFeatureDetail').open();
      });
    });

    box.on('open', function() {
      //拡大画像表示時にもう一度Featueメニューをクリックすると拡大画像が残ってしまうので無理矢理閉じる
      manager.getBox('womensFeatureDetail').close();      
    });
  });

  manager.of('womensFeatureDetail', function(box) {
    var $products = box.element.find('.products')
      , $back = box.element.find('.back a'); 

    var loader = featured.load(1)
      , renderer = new undercover.Renderer('#womensFeatureDetailTemplate', box.element.find('.products'));

    box.on('initialize', function() {
      var $prev = box.element.find('.prev')
        , $next = box.element.find('.next');
      
      var that = this;

      loader
        .done(function() {
          that.success();
        })
        .fail(function() {
          that.error();
        });
      
      this.element.find('.pager a:has(.prev)').live('click', function() {
        featured.prev();
        $products.trigger('datachange.featured');
      });

      this.element.find('.pager a:has(.next)').live('click', function() {
        featured.next();
        $products.trigger('datachange.featured');
      });

      $back.live('click', function() {
        $.each(manager.getBoxes(function(box) { return box.id.match(/^womensFeature0[0-9]$/); }), function(i, box) {
          box.open();
        });        
        box.close();
      });
      
      $products.live('datachange.featured', function() {
        (featured.hasPrev() ? undercover.utils.activate : undercover.utils.deactivate).call(null, $prev);
        (featured.hasNext() ? undercover.utils.activate : undercover.utils.deactivate).call(null, $next);
        renderer.render(featured.getItem()[0]);
      });
    });

    box.on('open', function() {
      $.when(loader)
        .done(function() {          
          box.element.find('.products').trigger('datachange.featured');
        });
    });
  });

  
  //明滅処理
  manager.of('mensWelcomeTop', function(box) {
    box
      .on('open', function() {
        welcomeBlink.start();
      })
      .on('close', function() {
        welcomeBlink.stop();
      });
  });
  
  manager.of(/mensTodayTop/, function(box) {
    var song = mensSong
      , loader = song.load(1)
      , renderer = new undercover.Renderer('#mensTodayTemplate', box.element.find('.todayTop'));

    box.on('initialize', function() {
      var that = this;
      loader
        .done(function() {
          that.success();
        })
        .fail(function() {
          that.error();
        });
    });

    box.on('open', function() {
      $.when(loader)
      .done(function() {
        renderer.render(song.getAll()[0]);
      });
    });
  });

  manager.of(/womensTodayTop/, function(box) {
    var song = womensSong
      , loader = song.load(1)
      , renderer = new undercover.Renderer('#womensTodayTemplate', box.element.find('.todayTop'));

    box.on('initialize', function() {
      var that = this;
      loader
        .done(function() {
          that.success();
        })
        .fail(function() {
          that.error();
        });
    });

    box.on('open', function() {
      $.when(loader)
      .done(function() {
        renderer.render(song.getAll()[0]);
      });
    });
  });

  //WOMENSのロールオーバー
  manager.of('womensNavigation', function(box) {
    box
      .on('initialize', function() {
        var that = this;
        this.element.find('a img').css({opacity: 1})
          .live('mouseenter', function() {
		    $(this).animate({opacity: 0}, {duration: 250, easing: 'linear', queue: false});
          })
          .live('mouseleave', function() {
		    $(this).animate({opacity: 1}, {duration: 250, easing: 'linear', queue: false});
          });
      });
  });

  //全てのboxに共通の処理
  manager.of(/.*/, function(box) {
    box
      .on('initialize', function() {
        var that = this;
        this.element
          .bind('mousedown', function() {
            that.element.css('zIndex', manager.getMaxDepth(box));
          })
          .draggable({
            distance: 5,
            refreshPositions: true,
            cancel: '.close',
            start: function() {
              $(nametake.currentScene.element).find('.overlay').show();
            },
            stop: function() {
              if (nametake.currentScene !== '/womens') that.element.find('.overlay').hide();
            }
          });
      })
      .on('open', function() {
        var $scrollable = box.element.find('.scrollable');
        var that = this
          , pos = $.data(box.element.get(0), 'initialPos'); 
        if (pos) box.element.css(pos);
        box.element
          .css('zIndex', manager.getMaxDepth(box))
          .stop(true, true).fadeIn(function() {
            if (!$.data(box.element.get(0), 'initialPos')) {
              $.data(box.element.get(0), 'initialPos', box.element.position());
            }
            box.element.find('.mapFrame').attr('src', $.data(that.element.get(0), 'gmapUrl'));
          });
      })
      .on('close', function() {
        box.element.stop(true, true).fadeOut(function() {
          var $content = box.element.find('.simpleScrollContent > *');
          box.element.find('.scrollable').empty().append($content);
          box.element.find('.outer').remove().appendTo(box.element);
        });
      })
      .on('success', function() {
        this.element.find('.error').hide();
      })
      .on('error', function() {
        this.element.find('.error').empty().text('ERROR');
      });
  });

  $('.box a').live('click', function(e) {
    var tagName = this.href.split('#')[1];
    if (tagName && !/^(#|%21).*/.test(tagName)) {
      e.preventDefault();
      manager.switchTo(tagName);
    }
  });
  
  changeBackgroundTo(initialUrl);

  // login box
  $('#logo a.loginBtn, #opMovie a.loginBtn').live('click', function(e) {
    e.preventDefault();
    manager.getBox('login').open();
    manager.getBox('signUp').close();
    manager.getBox('done').close();
    $('#login input').focus();
  });
  $('#logo a.registerBtn, #opMovie a.registerBtn').live('click', function(e) {
    e.preventDefault();
    manager.getBox('login').close();
    manager.getBox('signUp').open();
    manager.getBox('done').close();
  });

  $('#login .login a, #opMovie .login a').live('click', function(e) {
    var password = $('#password').val();
    if(password != 'noise' && password != 'undercover')
    {
      window.alert('パスワードが違います');
      return;
    }
 
    var male = $("#check-01").attr("class");// checked or deselect
    if(male=="checked"){
      nametake.moveTo('/mens');
    }else{
      nametake.moveTo('/womens');
    }

  });

  $('#login .password').live('click', function() {
    $(this).find('input').focus();
  });

  $('#signUp .signUp a').live('click', function(e) {
    e.preventDefault();
    var mailAddres = $('#mailAddress').val();

    if (!mailAddres.match(/^([a-z0-9_]|\-|\.|\+)+@(([a-z0-9_]|\-)+\.)+[a-z]{2,6}$/i)) {
        alert("正しいメールアドレスを入力してください。");
    }else{
        var male = $("#check-01").attr("class");// checked or deselect
        if(male=="checked"){
            var sex = 1 ;
        }else{
            var sex = 0 ;
        }
        var data = {mailAddres: mailAddres, sex: sex};
        $.ajax({
            type: "POST",
            url: location.href + "/php/register.php",
            data: data,
            success: function(msg) {
              manager.getBox('signUp').close();
              manager.getBox('done').open();
              //alert(msg);
            }
        });
    }
  });

  $('#signUp .mail').live('click', function() {
    $(this).find('span').hide();
    $(this).find('input').focus();
  });
  
  
  // apple loop
  for(var i = 0; i < 3; i++)
  {
    var $apple = $('.apple').clone();
    $('#womens').append($apple);
//    $apple.css('display', 'block');
    $apple.css('position', 'absolute');
    $apple.offset({top: Math.random() * $(window).height(), left: Math.random() * $(window).width()});
    $apple.find('img').css('width', Math.floor(Math.random() * 50 + 50) + '%');
  }

  setInterval(function() {
    if($('#womensNavigation').css('display') != 'none') {
      $apple = $('.apple');
      $apple.animate({'top': '+=3px'}, 0);
      $apple.each(function() {
        var offset = $(this).offset();
        if(offset.top > $(window).height()) {
          offset.top = - $(this).height() - Math.random() * $(window).height() * 0.5;
          offset.left = Math.random() * $(window).width();
          $(this).offset(offset);
          $(this).find('img').css('width', Math.floor(Math.random() * 50 + 50) + '%');
        }
      });
    }
  }, 50);
  
});

