var $ = function(id){
    return document.getElementById(id);
  },

  allPics = [

    /* 美女类别 */
    {ename: 'ty', cname: '唐嫣', summary: '女神啊，因仙剑三中紫萱一角走红', flag: 'female'},
    {ename: 'bbh', cname: '白百何', summary: '鬼马类型，经常以调皮的角色上镜', flag: 'female'},
    {ename: 'meinv1', cname: '绿色小清新', summary: '绿色养眼哦，双重的', flag: 'female'},
    {ename: 'meinv2', cname: '蓝色情调', summary: '倚门待约会的姑娘，拼好跟你约会哦', flag: 'female'},
    {ename: 'xbmy', cname: '榎本美优', summary: '恬静，气质型美女', flag: 'female'},
    {ename: 'tgyly', cname: '桐谷尤莉亚', summary: '被称为十年难得一见的极上美女', flag: 'female'},
    {ename: 'xzmly', cname: '小泽玛利亚', summary: '特有的异国情调、美貌和可爱的微笑', flag: 'female'},
    {ename: 'qbw', cname: '桥本舞', summary: '一个美丽的声优', flag: 'female'},
    {ename: 'gtmx', cname: '工藤美香', summary: '回眸一笑百媚生', flag: 'female'},
    {ename: 'sdzq', cname: '松岛真琴', summary: '柔软白皙的皮肤晶莹剔透', flag: 'female'},
    {ename: 'nal', cname: '南爱梨', summary: '', flag: 'female'},
    {ename: 'ymqm1', cname: '冴木琴美', summary: '', flag: 'female'},
    {ename: 'ymqm2', cname: '冴木琴美', summary: '', flag: 'female'},

    /* 其他类别 */
    {ename: 'luffy', cname: '路飞', summary: '动漫海贼王的主角', flag: 'other'},
    {ename: 'girl', cname: '听着音乐的小姑娘', summary: '画得不错哦', flag: 'other'},
    {ename: 'waly', cname: '机器人总动员', summary: '一部关于机器人的爱情故事的电影', flag: 'other'},
    {ename: 'book_room', cname: '小姑娘在看书', summary: '书中自有黄金屋', flag: 'other'},
    {ename: 'bird', cname: '绿色童话', summary: '开心的鸟儿', flag: 'other'}
  ],

  win = window,
  storage = win.localStorage,

/* 3个界面 */
  indexLayer = $('index'),
  optionsLayer = $('option'),
  playLayer = $('play'),

/* 主页界面 index */
  newGame = $('newGame'),
  continueGame = $('continueGame'),

/* 选项界面 option */
  tabsLayer = $('tabsLayer'),
  tabs = tabsLayer.getElementsByClassName('tab'),

  imageLayer = $('imageLayer'),
  layer1 = $('imageLayer1'),
  layer2 = $('imageLayer2'),

  optionBack = $('optionBack'),
  activeImgLayer = layer1.style.display != 'none' ? layer1 : layer2,
  itemNodes = [],

/* 游戏界面 play */
  finish = $('finish'),
  score = $('score'),
  highsetScore = $('highsetScore'),

  finishReload = $('finishReload'),
  finishOption = $('finishOption'),
  finishNums = $('finishNums'),
  bestScore = $('bestScore'),

/* 其他界面 */

  inHandle = false,
  mask = $('mask'),

  sys;

var app = {

  location: 'index',

  baseOptions: {
    containerId: 'spellArea',
    allPics: allPics,

    events: {

      onMove: function(){

      },

      onReload: function(){

      },

      onFinish: function(){

        var imgEname = app.getImgNameFromPath(sys.imgPath),
          newHigherScore, finishNum;

        newHigherScore = win.parseInt(storage.getItem('score_'+imgEname));

        if(!newHigherScore || sys.score > newHigherScore){
          storage.setItem('score_'+imgEname, sys.score);
          bestScore.innerHTML = sys.score;
        }

        highsetScore.innerHTML = storage.getItem('score_'+imgEname);

        finishNum = win.parseInt(storage.getItem('count_'+imgEname));
        finishNum = win.isNaN(finishNum) ? 1 : finishNum + 1;

        storage.setItem('count_'+imgEname, finishNum);
        finishNums.innerHTML = finishNum;

        score.innerHTML = sys.score;
        storage.setItem('data_hasLastGame', '0');

        app.mask(finish.style.display = 'block');

      }

    }
  },

  onDeviceReady: function(){//设备已连接

    //document.addEventListener("resume", app.onResume, false);

    app.loadLocalPics();

    /* 检查是否有未完成的游戏 */
    app.checkLastGame();

    /* 遮罩下的点击无效 */
    mask.onclick = function(e){
      e.preventDefault();
      return false;
    }

    /* 绑定事件 */
    /* 主页事件 */
    SYSHelp.addEventListener(continueGame, 'click', app.startGame);
    SYSHelp.addEventListener(newGame, 'click', app.toOption);

    /* 选项事件 */
    SYSHelp.addEventListener(optionsLayer, 'click', app.optionSet);

    SYSHelp.addEventListener(optionBack, 'click', app.onBackKeyDown);

    /* 游戏事件 */
    SYSHelp.addEventListener(finishReload, 'click', function(){
      sys && sys.reload();
      app.mask(finish.style.display = 'none');
    });

    SYSHelp.addEventListener(finishOption, 'click', function(){
      app.toInterface('option');
      app.mask(finish.style.display = 'none');
    });

  },

  onResume: function(){
    if(storage.getItem('sys_music') == 'on'){
      app.oMedia = new Media(app.bgMusic, app.bgMusicEnd);
      app.oMedia.play();
    }
  },

  getPicPathByEname: function(ename){
    return './pictures/' + ename + '/thumb.jpg';
  },

  loadLocalPics: function(){

    var pic, tmpItem, parentLayer, i = 0, len = app.baseOptions.allPics.length,
      tmpNode = $('tmpNode'), img = tmpNode.getElementsByClassName('itemImg')[0];

    for(;i<len;i++){
      pic = app.baseOptions.allPics[i];

      /* 给对应类型的拼图选择层界面 */
      if(pic.flag == 'female'){
        parentLayer = layer1;
      }else{
        parentLayer = layer2;
      }

      /* 创建拼图选择创建层 */
      tmpItem = document.createElement('div');
      parentLayer.appendChild(tmpItem);
      tmpItem.className = 'item icons';

      /* 写入拼图信息 */
      tmpNode.getElementsByClassName('name')[0].innerHTML = pic.cname;
      tmpNode.getElementsByClassName('summary')[0].innerHTML = pic.summary;
      img.src = app.getPicPathByEname(pic.ename);
      img.name = pic.ename;

      tmpItem.innerHTML = tmpNode.innerHTML;
      itemNodes.push(tmpItem);
    }
  },

  toIndex: function(){

    optionBack.style.display = finish.style.display = 'none';

    app.toInterface(app.location = 'index');

    if(sys && !sys.finish){
      sys.stopRunTime();
      continueGame.style.display = 'block';
    }else{
      continueGame.style.display = 'none';
    }

  },

  toInterface: function(showLayer){

    var interfaces = {
      index: indexLayer,
      option: optionsLayer,
      play: playLayer
    }, result, key;

    for(key in interfaces){
      result = 'none';

      if(showLayer == key){
        result = 'block';
      }

      interfaces[key].style.display = result;
    };

  },

  toOption: function(){

    app.toInterface(app.location = 'option');

    optionBack.style.display = 'block';
    finish.style.display = 'none';
  },

  mask: function(type){

    if(type){
      mask.style.display = type;
      return;
    }

    if(mask.style.display == 'none'){

      mask.style.display = 'block';
    }else{
      mask.style.display = 'none';
    }
  },

  checkLastGame: function(){

    if(storage.getItem('data_hasLastGame') == '1'){//假如上次退出后有未完成的游戏

      continueGame.style.display = 'block';
      app.loadLastGameData();

    }
  },

  storageTheGame: function(){//保存当前游戏数据
    if(sys && !sys.finish){
      storage.setItem('data_hasLastGame', '1');
      storage.setItem('data_lastImgPath', sys.imgPath);
      storage.setItem('data_lastCellNum', sys.cellNum);
      storage.setItem('data_lastEmptyCellIndex', sys.emptyCellIndex);

      storage.setItem('data_lastSteps', win.parseInt(sys.recordStepsNode.innerHTML));
      storage.setItem('data_lastDate', win.parseInt(sys.recordDateNode.innerHTML));
      storage.setItem('data_lastScore', sys.score);
      storage.setItem('data_lastHtml', win.encodeURIComponent(sys.containerNode.innerHTML));
      storage.setItem('data_lastRightSortPic', sys.rightSortPic);
      storage.setItem('data_lastFinishCurrentNum', sys.finishCurrentNum);
    }
  },

  getImgNameFromPath: function(imgPath){
    return imgPath.slice(imgPath.lastIndexOf('/')+1);
  },

  loadLastGameData: function(){//加载上次游戏的数据

    var options = {
        imgPath: storage.getItem('data_lastImgPath'),
        cellNum: storage.getItem('data_lastCellNum'),
        emptyCellIndex: storage.getItem('data_lastEmptyCellIndex'),
        score: storage.getItem('data_lastScore'),
        rightSortPic: storage.getItem('data_lastRightSortPic').split(','),
        finishCurrentNum: storage.getItem('data_lastFinishCurrentNum'),
        isContinue: true,

        continueData: {
          steps: storage.getItem('data_lastSteps'),
          date: storage.getItem('data_lastDate'),
          html: win.decodeURIComponent(storage.getItem('data_lastHtml'))
        }
      },

      imgEname = app.getImgNameFromPath(options.imgPath),
      finishCounts, highestScore;

    finishCounts = win.parseInt(storage.getItem('count_'+imgEname));
    finishNums.innerHTML = finishCounts ? finishCounts : 0;

    highestScore = win.parseInt(storage.getItem('score_'+imgEname));
    bestScore.innerHTML = highestScore ? highestScore : 0;

    SYSHelp.mergeObject(app.baseOptions, options);
    sys = SYS.createSYS(options);
  },

  startGame: function(set){
    var options;

    optionBack.style.display = 'block';
    app.toInterface(app.location = 'play');

    // 继续游戏
    if(!set.imgPath && sys){
      sys.startRunTime();
      return;
    };

    options = {
      sys: sys,
      containerWidth: 240,
      cellNum: set.cellNum || 9,
      imgPath: set.imgPath || './pictures/' + app.baseOptions.allPics[0].ename
    };

    SYSHelp.mergeObject(app.baseOptions, options);
    sys = SYS.createSYS(options);
  },

  optionSet: function(e){

    var node = e.target,
      tabIndex, imageLayers,
      imgEname,
      itemNode,
      i, flag, len = tabs.length;

    if(node.classList.contains('tab')){
      flag = 'tab';

    }else if(node.classList.contains('btnSelect')){
      flag = 'play';

    }else{
      return;
    }

    switch (flag){
      case 'tab' ://选择拼图类型
        if(!node.classList.contains('active')){

          for(i=0;i<len;i++){
            tabs[i].classList.remove('active');
          }
          node.classList.add('active');

          tabIndex = SYSHelp.getIndex(node, tabs);
          imageLayers = imageLayer.getElementsByClassName('imageWrapper');

          for(i=0,len=imageLayers.length;i<len;i++){

            if(i == tabIndex){
              imageLayers[i].classList.remove('hide');
              activeImgLayer = imageLayers[i];
            }else{
              imageLayers[i].classList.add('hide');
            }
          }
        }

        break;
      case 'play':

        app.confirmSelectPic(node.parentNode.parentNode);

        itemNode = activeImgLayer.getElementsByClassName('confirmThePic');

        if(itemNode.length == 0){

          alert('请选择拼图的对象！');
        }else{
          var set, finishCounts, highestScore;

          itemNode = itemNode[0];
          imgEname = itemNode.getElementsByClassName('itemImg')[0].name;

          set = {
            cellNum: 9,
            imgPath: './pictures/' + imgEname
          };

          finishCounts = win.parseInt(storage.getItem('count_'+imgEname));
          finishNums.innerHTML = finishCounts ? finishCounts : 0;

          highestScore = win.parseInt(storage.getItem('score_'+imgEname));
          bestScore.innerHTML = highestScore ? highestScore : 0;

          app.startGame(set);
        }
        break;
    }
  },

  confirmSelectPic: function(itemNode){
    if(!itemNode.classList.contains('confirmThePic')){

      for(i=0,len=itemNodes.length;i<len;i++){
        itemNodes[i].classList.remove('confirmThePic');
      }

      itemNode.classList.add('confirmThePic');
    }
  },

  onBackKeyDown: function(){
    app.mask('none');

    switch(app.location){
      case 'index':
        break;
      case 'play':

        sys.stopRunTime();
        app.toInterface(app.location = 'option');
        break;
      case 'option':
        app.toIndex();
        break;
    }
  },

  closePanel: function(node){
    app.mask(node.parentNode.style.display = 'none');
  }

};

app.onDeviceReady();