/**
 * 「うつくしい世界」期TOPページ用
 * Auth: Kawatsure Takaharu
 * Date: 2011/11/13
 */

/**
 *
 */
var BWSnow = function(output, snowNum, snowImgPath){
  //this.initialze.apply(this, arguments);
  this.initialize(output, snowNum, snowImgPath);
};
BWSnow.prototype = {

  output: null,
  snowNum: null,
  snowImgPath: null,

  screenWidth: 800,
  screenHeight: 600,

  snowIdPrefix: 'snow',
  snowImgPath: './image/snow02.gif',

  initialize: function(_output, _snowNum, _snowImgPath) {
    if(!_output)
      _output = '#background';

    if(!_snowNum)
      _snowNum = 30;

    if(!_snowImgPath)
      _snowImgPath = './image/snow02.gif';

    this.output = _output;
    this.snowNum = _snowNum;
    this.showImgPath = _snowImgPath;

    this.screenWidth = getBrowserWidth() - 10;

    var closureDummy = this;
    $(window).resize(function() {
                       closureDummy.screenWidth = getBrowserWidth();
                     });

    this.generate();

    var x = this.x;
    var y = this.y;
    var v = this.v;

    var name = '#' + this.snowIdPrefix;
    var num = this.snowNum;

    var tH = this.screenHeight - 10;
    var tW = this.screenWidth;

    setInterval(function(){
                  var i;
                  for(i = 0; i < num; ++i){
                    y[i] -= v[i];
                      //if(y[i] > tH){
                    if(y[i] < 0) {
                      y[i] = tH + 10;
                      x[i] = Math.floor(Math.random() * tW);
                      $(name + i).css('left', x[i]).show();
                    }
                    $(name + i).css('top', y[i]);
                  }
                }, 50);
  },

  generate : function() {
    var name = this.snowIdPrefix;
    var num = this.snowNum;

    var imgHead = '<img class="snow" id="' + name;
    var imgFoot = '" src="' + this.snowImgPath + '">';

    var width = this.screenWidth;
    var height = this.screenHeight;

    var output = this.output;

    var x = new Array(num);
    var y = new Array(num);
    var v = new Array(num);
    for(var i = 0; i < num; ++i){
      x[i] = Math.floor(Math.random() * width);
      y[i] = Math.floor(Math.random() * height);
      v[i] = Math.floor(Math.random() * 5) + 3;

      $(imgHead + i + imgFoot)
        .css('top', y[i])
        .css('left', x[i])
        .appendTo($(output));
    }

    this.x = x;
    this.y = y;
    this.v = v;
  }

};

function getBrowserWidth() {
  if(window.innerWidth) { return window.innerWidth; }
  else if(document.documentElement && document.documentElement.clientWidth != 0 ) { return document.documentElement.clientWidth; }
  else if ( document.body ) { return document.body.clientWidth; }

  return 0;
}

$(function(){
    var snow = new BWSnow('#body', 70, null);
  });

