/*
  初期化
*/
if(typeof(Yumenosora) == 'undefined'){
  var Yumenosora = {}
}
Yumenosora.Design = {
  /*
    セレクトボックス
  */
  SelectBox: Class.create({
    initialize: function(src){
      //中身の構築
      var container = new Element('div', {
        className: 'common-design-selectbox-container'
      });
      
      var displayBox = new Element('div', {className: 'clearfix'});
      container.appendChild(displayBox);
      
      var display = new Element('div', {className: 'display'});
      displayBox.appendChild(display);
      
      var button = new Element('button', {type: 'button'}).update('▽');
      displayBox.appendChild(button);
      
      var dropdown = new Element('ul', {
        className: 'common-design-selectbox-dropdown',
        style: 'display:none'
      });
      
      var options = src.getElementsByTagName('option');
      $A(options).each(function(option){
        var element = new Element('li');
        element.writeAttribute('data-value', option.value);
        element.update(option.innerHTML);
        if(option.selected){
          element.addClassName('selected');
          display.update(option.innerHTML);
        }
        
        dropdown.appendChild(element);
      });
      container.appendChild(dropdown);
      src.insert({after: container});
      this.dropdown = dropdown;
      this.container = container;
      this.display = display;
      this.src = src;
      this.src.hide();
      
      //イベントハンドラの設定
      var self = this;
      display.observe('click', function(){
        self.open();
      });
      button.observe('click', function(){
        self.open();
      });
      
      var click = function(){
        var value = this.readAttribute('data-value');
        var label = this.innerHTML;
        self.click(value, label);
      }
      $A(dropdown.getElementsByTagName('li')).each(function(li){
        li.observe('click', click);
      });
    },
    
    open: function(){
      this.dropdown.slideDown({duration: 0.2});
      var overlay = new Element('div', {
        className: 'common-design-selectbox-overlay'
      });
      this.container.insert({after: overlay});
      this.overlay = overlay;
      var self = this;
      overlay.observe('click', function(){
        self.close();
      });
    },
    
    close: function(){
      this.dropdown.slideUp({duration: 0.2});
      this.overlay.remove();
    },
    
    click: function(value, label){
      this.src.value = value;
      this.display.update(label);
      this.src.fire('select:change');
      this.close();
    }
  }),
  
  /*
    モーダルダイアログ
  */
  Dialog: Class.create({
    initialize: function(message, okbutton, cancelbutton, inputbox){
      var self = this;
      
      var overlay = new Element('div', {
        className: 'common-design-dialog-overlay',
        style: 'display: none'
      });
      $$('body')[0].appendChild(overlay);
      overlay.appear({duration: 0.2, to: 0.5});
      new Yumenosora.Layouter.Position({
        target: overlay,
        top: 0,
        left: 0
      });
      this.overlay = overlay;
      
      var container = new Element('div', {
        className: 'common-design-dialog',
        style: 'display:none'
      });
      this.container = container;
      
      var display = new Element('div', {
        className: 'display'
      }).update(message);
      container.appendChild(display);
      
      if(inputbox != null){
        var input = new Element('input', {
          type: 'text',
          value: inputbox
        });
        container.appendChild(input);
        this.input = input;
        new Yumenosora.Design.InputBox(input);
      }
      
      var buttons = new Element('div', {className: 'buttons'});
      container.appendChild(buttons);
      if(cancelbutton != null){
        var button = new Element('button', {
          className: 'cancel'
        }).update(cancelbutton);
        
        button.observe('click', function(){
          self.overlay.fade({
            duration: 0.2,
            afterFinish: function(){
              self.overlay.remove();
            }
          });
          
          self.container.fade({
            duration: 0.2,
            afterFinish: function(){
              self.container.remove();
            }
          });
        })
        buttons.appendChild(button);
      }
      
      var button = new Element('button', {
        className: 'ok'
      }).update(okbutton);
      button.observe('click', function(){
        //入力値
        var value = null;
        if(self.input != null){
          this.value = self.input.value;
        }
        
        button.fire('dialog:ok');
        
        self.overlay.fade({
          duration: 0.2,
          afterFinish: function(){
            self.overlay.remove();
          }
        });
        
        self.container.fade({
          duration: 0.2,
          afterFinish: function(){
            self.container.remove();
          }
        });
      });
      this.okbutton = button;
      
      buttons.appendChild(button);
      
      $$('body')[0].appendChild(container);
      
      //位置調整
      this.setPosition();
      
      container.appear({duration: 0.2});
    },
    
    observe: function(eventName, _function){
      this.okbutton.observe(eventName, _function);
    },
    
    setPosition: function(){
      //位置調整
      var screenWidth = document.viewport.getWidth();
      var screenHeight = document.viewport.getHeight();
      var dialogWidth = this.container.getWidth();
      var dialogHeight = this.container.getHeight();
      var left = (screenWidth - dialogWidth) / 2;
      var top = (screenHeight - dialogHeight) / 2;
      if(top.toString() == 'NaN'){
        top = 0;
      }
      if(left.toString() == 'NaN'){
        left = 0;
      }
      
      new Yumenosora.Layouter.Position({
        target: this.container,
        top: top,
        left: left
      });
    }
  }),
  
  InputBox: Class.create({
    initialize: function(src){
      var self = this;
      
      var c = new Element('div', {className: 'inputbox-container'});
      src.insert({after: c});
      c.appendChild(src);
      this.container = c;
      
      src.observe('focus', function(){
        this.parentNode.addClassName('focus');
      });
      
      src.observe('blur', function(){
        this.parentNode.removeClassName('focus');
      });
    }
  }),
  
  /*
    通知バー
  */
  Notify: Class.create({
    initialize: function(message){
      var bar = new Element('div', {
        className: 'common-design-notify',
        style: 'display:none'
      });
      $$('body')[0].appendChild(bar);
      bar.update(message);
      bar.appear({
        duration: 0.2,
        afterFinish: function(){
          new PeriodicalExecuter(function(pe){
            pe.stop();
            bar.fade({
              duration: 0.2,
              afterFinish: function(){
                bar.remove();
              }
            });
          }, 3);
        }
      });
    }
  }),
  
  /*
    リンクボタン
  */
  LinkButton: Class.create({
    initialize: function(src){
      var button = new Element('button', {
        className: src.className,
        "data-href": src.href,
        id: src.id + '-button'
      }).update(src.innerHTML);
      
      button.observe('click', function(){
        location.href = this.readAttribute('data-href');
      });
      
      src.hide();
      src.insert({after: button});
    }
  })
}

/*
  検索ボックス
*/
Yumenosora.Design.SearchBox = Class.create(Yumenosora.Design.InputBox, {
  initialize: function($super, src){
    $super(src);
    this.container.addClassName('search');
  }
});

/*
  カスタムダイアログ
*/
Yumenosora.Design.CustomDialog = Class.create(Yumenosora.Design.Dialog, {
  initialize: function(container, overlay){
    this.container = container;
    this.setPosition();
    
    container.appear({duration: 0.2});
    overlay.appear({duration: 0.2, to: 0.5});
    new Yumenosora.Layouter.Position({
      target: overlay,
      top: 0,
      left: 0
    });
  }
});

Yumenosora.Layouter = {
  /*
    幅レイアウタ
  */
  Width: Class.create({
    initialize: function(config){
      var self = this;
      
      this.config = config;
      //this.update();
      new PeriodicalExecuter(function(e){
        self.update();
      }, 1);
    },
    
    update: function(){
      if(typeof(this.config.condition) == 'undefined' || 
        this.config.condition() == true){
        
        if(typeof(this.config.minusWidth) == 'undefined'){
          var minus = 0;
          this.config.minusElements.each(function(element){
            var layout = element.getLayout();
            minus += layout.get('margin-left') +
              layout.get('border-left') +
              layout.get('padding-left') +
              layout.get('width') +
              layout.get('padding-right') +
              layout.get('border-right') +
              layout.get('margin-right');
          });
          
          var width = this.config.parent.getWidth() - minus;
        }else{
          var width = this.config.parent.getWidth() - this.config.minusWidth;
        }
        
        var target = this.config.target;
        var layout = target.getLayout();
        width = width - 
          layout.get('border-left') -
          layout.get('padding-left') -
          layout.get('padding-right') -
          layout.get('border-right') - 1;
        
        target.setStyle({
          width: width + 'px'
        });
      
      }else{
        this.config.target.setStyle({
          width: null
        });
        return;
      }
    }
  }),

  /*
    高さ合わせレイアウタ
  */
  HeightSync: Class.create({
    initialize: function(config){
      var self = this;
      this.config = config;
      this.update();
      new PeriodicalExecuter(function(e){
        self.update();
      }, 1);
    }, 
    
    update: function(){
      //実行条件
      if(this.config.condition != null && this.config.condition() == false){
        this.config.target.setStyle({
          height: null
        });
        
      }else{
        this.config.target.setStyle({
          height: this.config.src.getHeight() + 'px'
        });
      }
    }
  }),
  
  /*
    高さ揃えレイアウタ
  */
  HeightAdjuster: Class.create({
    initialize: function(config){
      var self = this;
      this.config = config;
      //this.update();
      new PeriodicalExecuter(function(e){
        self.update();
      }, 1);
    }, 
    
    update: function(){
      try{
        if(typeof(this.config.targets) == 'string'){
          var targets = $$(this.config.targets);
        }else{
          var targets = this.config.targets;
        }
        
        //実行条件
        if(this.config.condition != null && this.config.condition() == false){
          targets.each(function(target){
            target.setStyle({
              minHeight: null
            })
          });
          
        }else{
          //最大の高さを検出
          var height = 0;
          targets.each(function(target){
            var temp = target.getHeight();
            if(height < temp){
              height = temp;
            }
          });
          
          //高さセット
          targets.each(function(target){
            var layout = target.getLayout();
            var border = layout.get('border-top') + 
              layout.get('border-bottom');
            var padding = 
              layout.get('padding-top') + layout.get('padding-bottom');
            
            var minHeight = height - border - padding + 'px';
            target.setStyle({
              minHeight: minHeight
            })
          });
        }
      }catch(e){
        //do nothing
      }
    }
  }),
  
  Position: Class.create({
    initialize: function(params){
      if(Yumenosora.Utils.Platform.iOSDetect()){
        //position: fixedが使用できないのでタイマーを起動する
        this.params = params;
        this.prevOffset = [-1, 0];
        this.update();
        var self = this;
        this.timer = new PeriodicalExecuter(function(pe){
          self.update();
        }, 1);
        
      }else{
        //通常
        params.target.setStyle({
          position: 'fixed',
          top: params.top + 'px',
          left: params.left + 'px'
        });
      }
    },
    
    update: function(){
      var target = this.params.target;
      if(target.parentNode == null){
        this.timer.stop();
        
      }else{
        var offset = document.viewport.getScrollOffsets();
        
        var prevOffset = this.prevOffset;
        if(prevOffset[0] != offset[0] || prevOffset[1] != offset[1]){
          this.prevOffset = offset;
          target.setStyle({
            position: 'absolute',
            top: this.params.top + offset[1] + 'px',
            left: this.params.left + offset[0] + 'px'
          });
        }
      }
    }
  })
}

Yumenosora.Utils = {
  Platform: {
    iOSDetect: function (){
      if(navigator.userAgent.indexOf('iPhone') > -1 || 
        navigator.userAgent.indexOf('iPad') > -1 || 
        navigator.userAgent.indexOf('iPod') > -1){
        
        return true;
      }
      
      return false;
    }
  }
}

