var APUtil = {
  url:{
    favoriteVideo:'/favorite/video',
    favoriteChannel:'/favorite/folder',
    favoriteFolder:'/favorite/folder',
    channelOwners:'/channel/owners'
  },
  noImageUrl: '/images/v4_0_1/sprite/noimage.jpg',
  getFaviconUrl: function(domain){
    return 'http://services.woopie.jp/api/favicon/'+domain+'/favicon.gif';
  },
  formatDate: function(d) {
    d = new Date(d);
    var year = d.getFullYear();
    var month = parseInt(d.getMonth()) + 1;
    var day = d.getDate();
    return year + '/' + month + '/' + day;
  }
};
var APUser = {
  userType:{
    No: 0,
    Taste: 1,
    Login: 2,
    Logout: 3
  },
  getUserType: function(){
    try{
      if($.cookie('WP_UInfo').match(/t=([0-3])/)){
        return parseInt(RegExp.$1);
      }
      return this.userType.No;
    }catch(e){
      return this.userType.No;
    }
  },
  isVerified: function(){
    try{
    if(parseInt($.cookie('WP_UVrf'))==1) return true;
    return false;
    }catch(e){
      return false;
    }
  },
  verifyAndRedirect: function(url,title){
    if( this.getUserType() != this.userType.Login || !this.isVerified() ){
      location.href='/verify_age?next_url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title);
      return true;
    }
    return false;
  }
};
var HashProperty ={
  fragment: '!',
  separator: '_',
  operator: '/',
  data:{},
  getData: function(){
    return this.data;
  },
  set: function(name,value){
    this.data[name]=value;
  },
  get: function(name){
    try{
      return this.data[name];
    }catch(e){return '';}
  },
  del: function(name){
    try{
      var newData = {};
      for(var i in this.data){
        if(i != name){
          newData[i]=this.data[i];
        }
      }
      this.data = newData;
    }catch(e){}
  },
  reset: function() {
    this.data = {};
  },
  readHash: function (hash){
    var hash = hash || location.hash;
    var params = hash.split( this.separator );
    this.data = {};
    for ( var i= 0; i<params.length; i++ ){
      if(params[i] != this.fragment){
        param = params[i].split(this.operator);
        if(param.length == 2){
          this.data[param[0]]=param[1];
        }
      }
    }
  },
  getHash: function (){
    var hash = '';
    if (!($.isEmptyObject(this.data))) {
      hash += this.fragment;
      for(var i in this.data){
        hash += this.separator + i + this.operator + this.data[i];
      }
    }
    return hash;
  },
  setHash: function(hash){
    this.readHash(hash);
  },
  toArrayString: function (){
    var ret = "{";
    var count=0;
    for(var i in this.data){
      if(count!=0){
        ret +=',';
      }
      ret += "'"+ i + "':'" + this.data[i]+ "'";
      count++;
    }
    ret +="}";
    return ret;
  },
  reflect: function() {
    location.hash = this.getHash();
  }
};
// checkbox
var CheckManager = {
  prefix: 'cm-',
  regexDef: '([\-0-9a-zA-Z]*)',
  list:[],
  clear: function(){
    CheckManager.list = [];
  },
  add: function(id){
    var listStr = CheckManager.list.join(',');
    var regObj = new RegExp(id);
    if( !listStr.match(regObj) ){
      CheckManager.list.push(id);
    }
  },
  iniset: function(){
            var reg = new RegExp('^'+CheckManager.prefix+CheckManager.regexDef);
            var checkall = CheckManager.list.join(',');
            $(':checkbox').each(function(){
              if( $(this).attr('id').match(reg) ){
                var id = RegExp.$1 ;
                if( checkall.match(id) ){
                  $(this).attr('checked',true);
                }
                $(this).change(function(){
                  if( $(this).attr('id').match(reg) ){
                    var id = RegExp.$1 ;
                    if($(this).attr("checked") == true){
                      CheckManager.add( id );
                    }else{
                      var newList = [];
                      for( var i in CheckManager.list ){
                        if( id != CheckManager.list[i] && typeof(CheckManager.list[i]) === 'string'){
                          newList.push(CheckManager.list[i]);
                        }
                      }
                      CheckManager.clear();
                      CheckManager.list = newList;
                    }
                  }
                });
              }
            });
  },
  checkAll: function(){
    var reg = new RegExp('^'+CheckManager.prefix+CheckManager.regexDef);
    $(':checkbox').each(function(){
      if( $(this).attr('id').match(reg) ){
        CheckManager.add( RegExp.$1 );
        $(this).attr("checked", true);
      }
    });
  },
  cancelAll: function(){
    var reg = new RegExp('^'+CheckManager.prefix+CheckManager.regexDef);
    CheckManager.list=[];
    $(':checkbox').each(function(){
      if( $(this).attr('id').match(reg) ){
        $(this).attr("checked", false);
      }
    });
  },
  isEmpty: function() {
    var _self = this;
    return _self.list.length > 0 ? false : true;
  }
};

var Category ={
  ids:[{id:0,nameShow:'すべて',nameUrl:'all'},
  {id:1,nameShow:'ニュース・時事',nameUrl:'news'},
  {id:2,nameShow:'スポーツ',nameUrl:'sports'},
  {id:3,nameShow:'映画・ドラマ',nameUrl:'movie'},
  {id:4,nameShow:'音楽',nameUrl:'music'},
  {id:5,nameShow:'アニメ・ゲーム',nameUrl:'anime'},
  {id:6,nameShow:'エンタメ・お笑い',nameUrl:'comedy'},
  {id:7,nameShow:'動物・ペット',nameUrl:'animal'},
  {id:8,nameShow:'グラビア・有名人',nameUrl:'gravure'},
  {id:9,nameShow:'旅行・イベント',nameUrl:'travel'},
  {id:10,nameShow:'人・その他',nameUrl:'others'},
  {id:11,nameShow:'アダルト',nameUrl:'adult'},
  ],
  titleId:'',
  categoryListId:'category-navigation',
  childrenTag:'li',
  selectClass:'select',
  changeList: function(categoryId){
    var i = 0;
    $('#'+this.categoryListId + ' '+this.childrenTag ).each(function(){
      if( i == categoryId ){
        jQuery(this).addClass(Category.selectClass);
      }else{
        if(jQuery(this).hasClass(Category.selectClass)) jQuery(this).removeClass(Category.selectClass);
      }
      i++;
    });
    if(this.titleId.length>0){$('#'+this.titleId).html(this.ids[categoryId]['nameShow'])}
  },
  changeShow: function(categoryId){
    var _this = this;
    HashProperty.set('page',1);
    if(categoryId == 0){
      HashProperty.del('category');
    }else{
      HashProperty.set('category',categoryId);
    }
    $(_this).attr('href', '#'+HashProperty.getHash());
  },
  getNameById: function(categoryId){
    var id = parseInt(categoryId );
    if( ( id ) && id < 12){
      return Category.ids[id];
    }
    return '--';
  }
};

var Users = {
//function(){this.uids = [];};
//Users.prototype = {
  size: 170,
  url: 'http://data.woopieapi.com/pfuser/users/',
  uids: [],
  callback: function(data){},
  imgPrefix: 'user-img-',
  nicknamePrefix: 'user-nickname-',
  noImageUrl: '/images/v4_0_1/sprite/human.jpg',
  images:{},
  error: function(responseText, textStatus, XMLHttpRequest) {
    if( textStatus == 'timeout' ){
       alert('timeout');
    }else{
       alert('error');
    }
  },
  getUserIds: function(baseId){
    var _self = this;
    var reg = RegExp(_self.imgPrefix+'(.+)');
    _self.uids=[];
    $('#'+baseId).find('img').each(function(){
      if( $(this).attr('id').match(reg) ){
        _self.uids.push( RegExp.$1 );
      }
    });
  },
  setImages: function(data){
    try{
      var _self = this;
      for(var i in _self.uids){
       // var imgUrl = _self.noImageUrl;
        if(typeof data.content[_self.uids[i]] != 'undefined' && data.content[_self.uids[i]].hasOwnProperty('thumbnail') && data.content[_self.uids[i]].thumbnail.length > 0){
          var imgUrl = data.content[_self.uids[i]].thumbnail;
          if( data.content[_self.uids[i]].thumbnail.match(/^\/human/)){
            imgUrl = 'http://www.woopie.jp/accounts/images/usercenter'+data.content[_self.uids[i]].thumbnail;
          }
          var image = new Image();
          $(image).load(function(){
            var maxSize = _self.size;
            if( typeof $('#'+$(this).attr('uid')).parent().css('width') !== 'undefined' &&
              $('#'+$(this).attr('uid')).parent().css('width').match(/([0-9]*)/) ){
              maxSize = RegExp.$1;
            }
            var width = $(this).attr('width');
            var height = $(this).attr('height');
            var maxLength = height;
            var marginTop = 0;
            if(height<width){
              maxLength = width;
            }
            width = parseInt((width/maxLength * maxSize));
            height = parseInt((height/maxLength * maxSize));
            marginTop = parseInt((maxSize-height)/2); 
            $('#'+$(this).attr('uid')).attr('src',$(this).attr('src'));
            $('#'+$(this).attr('uid')).css('width',width);
            $('#'+$(this).attr('uid')).css('height',height);
            if(marginTop>0) $('#'+$(this).attr('uid')).css('margin-top',marginTop);
          }).attr('uid',_self.imgPrefix+_self.uids[i]).attr('src',imgUrl);
        }
      }
    }catch(e){
      throw e;
    }
  },
  setImagesByClassName: function(data){
    try{
      var _self = this;
      for(var i in _self.uids){
       // var imgUrl = _self.noImageUrl;
        if(typeof data.content[_self.uids[i]] != 'undefined' && data.content[_self.uids[i]].hasOwnProperty('thumbnail') && data.content[_self.uids[i]].thumbnail.length > 0){
          var imgUrl = data.content[_self.uids[i]].thumbnail;
          if( data.content[_self.uids[i]].thumbnail.match(/^\/human/)){
            imgUrl = 'http://www.woopie.jp/accounts/images/usercenter'+data.content[_self.uids[i]].thumbnail;
          }
          var image = new Image();
          $(image).load(function(){
            var maxSize = _self.size;
            if( typeof $('.'+$(this).attr('uid')).parent().css('width') !== 'undefined' &&
              $('.'+$(this).attr('uid')).parent().css('width').match(/([0-9]*)/) ){
              maxSize = RegExp.$1;
            }
            var width = $(this).attr('width');
            var height = $(this).attr('height');
            var maxLength = height;
            var marginTop = 0;
            if(height<width){
              maxLength = width;
            }
            width = parseInt((width/maxLength * maxSize));
            height = parseInt((height/maxLength * maxSize));
            marginTop = parseInt((maxSize-height)/2); 
            $('.'+$(this).attr('uid')).attr('src',$(this).attr('src'));
            $('.'+$(this).attr('uid')).css('width',width);
            $('.'+$(this).attr('uid')).css('height',height);
            if(marginTop>0) $('.'+$(this).attr('uid')).css('margin-top',marginTop);
          }).attr('uid',_self.imgPrefix+_self.uids[i]).attr('src',imgUrl);
        }
      }
    }catch(e){
      throw e;
    }
  },
  resizeImage: function(imageId){
    var maxSize = 170;
    if( $('#'+imageId).parent().css('width').match(/([0-9]*)/) ){
      maxSize = RegExp.$1;
    }
    var width=maxSize;
    var height=maxSize;
    var bigEdge = width;
    var img = new Image();
    if( typeof $('#'+imageId).attr('naturalWidth') !== 'undefined' ){
      width = $('#'+imageId).attr('naturalWidth');
      height = $('#'+imageId).attr('naturalHeight');
    }else if (typeof $('#'+imageId).attr('runtimeStyle') !== 'undefined'){
      var run = $('#'+imageId).attr('runtimeStyle');
      run.width  = "auto";
      run.height = "auto";
      width= $('#'+imageId).attr('width');
      height= $('#'+imageId).attr('height');
      run.width  = "";
      run.height = "";
    }
    if( width > height){
      bigEdge = width;
    }else{
      bigEdge = height;
    }
    width = parseInt((width/bigEdge) * maxSize);
    height = parseInt((height/bigEdge) * maxSize);
    $('#'+imageId).css('width',width);
    $('#'+imageId).css('height',height);
    if(height != maxSize){
      $('#'+imageId).css('margin-top',parseInt((maxSize-height)/2));
    }
  },
	resizeImages: function(selector) {
    var maxSize = 170;
		var o = $(selector);
		o.each(function() {
			o = $(this);
			if( o.parent().css('width').match(/([0-9]*)/) ){
			maxSize = RegExp.$1;
			}
			var width=maxSize;
			var height=maxSize;
			var bigEdge = width;
			var img = new Image();
			if( typeof o.attr('naturalWidth') !== 'undefined' ){
			width = o.attr('naturalWidth');
			height = o.attr('naturalHeight');
			}else if (typeof o.attr('runtimeStyle') !== 'undefined'){
			var run = o.attr('runtimeStyle');
			run.width  = "auto";
			run.height = "auto";
			width= o.attr('width');
			height= o.attr('height');
			run.width  = "";
			run.height = "";
			}
			if( width > height){
				bigEdge = width;
			}else{
				bigEdge = height;
			}
			width = parseInt((width/bigEdge) * maxSize);
			height = parseInt((height/bigEdge) * maxSize);
			o.css('width',width);
			o.css('height',height);
			if(height != maxSize){
				o.css('margin-top',parseInt((maxSize-height)/2));
			}
		});
	},
  getImages: function (uids, size){
    try{
      var _self = this;
      if(typeof uids === 'string'){
        _self.getUserIds(uids);
      }else{
        if( uids && uids.length>0 ) _self.uids = uids;
      }
      if(typeof size === 'number' && parseInt(size)) _self.size = parseInt(size);
      _self.callback=_self.setImages;
      _self.get(_self.uids);
    }catch(e){ throw e;}
  },
  getProfiles: function(uids, callback) {
    try {
      var _self = this;
      callback = callback || function(){};
      if(typeof uids === 'string'){
        _self.getUserIds(uids);
      }else{
        if( uids && uids.length>0 ) _self.uids = uids;
      }
      if(typeof size === 'number' && parseInt(size)) _self.size = parseInt(size);
      _self.callback= function(data) {
        _self.setImages(data);
        $.each(data.content, function(i, val) {
          callback(val);
        });
      }
      _self.get(_self.uids);
    } catch(e) {}
  },
  getProfilesByClassName: function(uids, callback) {
    try {
      var _self = this;
      callback = callback || function(){};
      if(typeof uids === 'string'){
        _self.getUserIds(uids);
      }else{
        if( uids && uids.length>0 ) _self.uids = uids;
      }
      if(typeof size === 'number' && parseInt(size)) _self.size = parseInt(size);
      _self.callback= function(data) {
        _self.setImagesByClassName(data);
        $.each(data.content, function(i, val) {
          callback(val);
        });
      }
      _self.get(_self.uids);
    } catch(e) {}
  },

  get: function( uids ){
    try{
    var _self = this;
		var url = _self.url + uids.join(',');
    $.ajax({
      type: "GET",
      url: url,
      data: {'alt':'jsonp'},
      dataType: "jsonp",
      cache: false,
      success: function(data) {
        _self.callback(data);
      },
      error: function(responseText, textStatus, XMLHttpRequest) {
        _self.error(responseText, textStatus, XMLHttpRequest);
      }
    });
    }catch(e){ throw e;}
  },
  callback: function(){}
};
var UsersObj = function(){};
UsersObj.prototype = Users;

var APEmoji = {
  convert: function (str){
    return str.replace(/\[EMOJI:([A-F0-9]{4})\]/g, function() {
      return '<img src="http://data.woopieapi.com/emoji/' + RegExp.$1 +  '.gif" class="emoji" />';
    });
  }
};

var MessageBox = function() {

  var boxTpl = {
    normal: '<div class="layer-parts-area box-position" style="display:none;"><div class="layer-parts-container"><a class="close" href="javascript:void(0);">閉じる</a><div class="box-body"><div class="information"><p class="error"></p></div></div></div></div>',
    small: '<div class="layer-parts-area-small box-position" style="display:none;"><div class="head"></div><div class="body"><div class="layer-parts-area-small-container"><a class="close" href="javascript:void(0);">閉じる</a><div class="box-body"><div class="information"><p></p></div></div></div></div><div class="bottom"></div></div>'
  };

  var overlaidTpl = '<div class="gray-bg" style="opacity: 0.5; zoom: 1; filter: alpha(opacity=80); -ms-filter: \"alpha(opacity=50)\";display:none;"></div>';

  return function(options) {
    options = options || {};
    var size = options.size || 'small';
    if (size == 'normal') {
      var overlaid = options.overlaid === false ? false : true;
      var autohide = options.autohide === true ? true : false;
    } else {
      var overlaid = options.overlaid === true ? true : false;
      var autohide = options.autohide === false ? false : true;
    }
    var autohideTime = options.autohideTime || 5000;
    if (overlaid) {
      var overlaidObj = $(overlaidTpl);
    }

    var boxObj = $(boxTpl[size]);

    //set events
    boxObj.find('.close').click(function() {
      boxObj.triggerHandler('close');
    });
    boxObj.bind('close', function(evt) {
      hide();
    });
    //priaavate function
    var hide = function() {
      boxObj.hide(100, function() {
        if (overlaid) {
          hideOverlay();
        }
      });
    };
    var setMessage = function(message) {
      if (message) { 
        boxObj.find('.information > p').html(message);
      }
    };
    var setPosition = function(position) {
      position = position || {};
      
      var width = boxObj.width();
      var height = boxObj.height();
      var wx = $(window).scrollLeft() + ($(window).width() - boxObj.outerWidth()) / 2;
      if (wx < 0) wx = 0;
      var wy = $(window).scrollTop() + ($(window).height() - boxObj.outerHeight()) / 2;
      if (wy < 0) wy = 0;
      var left = position.left || wx;
      var top = position.top || wy;

      boxObj.css({
        'left': left,
        'top': top
      });
    };
    var setOverlaidSize = function(size) {
      size = size || {};

      var width = size.width || $(document).width();
      var height = size.height || $(document).height();

      var left = $(window).scrollLeft();
      var top = $(window).scrollTop();

      overlaidObj.css({
        'width': width,
        'height': height,
        'left': left,
        'top': top
      });
    };
    var showOverlay = function() {
      overlaidObj
        .appendTo('div.wrapper')
        .hide(100,
          function() {
            setOverlaidSize();
          }
        )
        .fadeIn(100);
    };
    var hideOverlay = function() {
      overlaidObj.fadeOut(100, function() {
        overlaidObj.remove();
      });
    };
    //export to public 
    return {
      //function
      show: function(options) {
        options = options || {};
        var message = options.message || "";
        var position = options.position || null;
        var onShown = options.onShown || function() {};
        setMessage(message);
        if (overlaidObj) {
          showOverlay();
        }
        boxObj
          .appendTo('div.wrapper')
          .hide(200, 
            function() {
            }
          ).show(100,
            function(){
              setPosition(position);
              onShown.apply(boxObj, arguments);
            }
          );
        if (autohide) {
          setTimeout(function() {
            hide();
          }, autohideTime);
        }
      },
      hide: function(options) {
        options = options || {};
        hide();
      },
      remove: function(options) {
        options = options || {};
        boxObj.remove();
      }
    };
  }
}();

var APItemSlider = function() {
  return function(options) {
    options || (options = {});
    var slideCount = 0;
    var eachItemCount = options.eachItemCount || 6;
    var maxItemCount = options.maxItemCount || 30;
    var maxSlideCount = Math.floor(maxItemCount / eachItemCount);
    maxSlideCount -= Math.round(maxItemCount % eachItemCount) > 0 ? 0 : 1;
    var sliderWidth = options.sliderWidth || 780;
    var duration = options.duration || 500;
    var prevBtn = options.prevBtn || 'sliderNaviPrev';
    var nextBtn = options.nextBtn || 'sliderNaviNext';
    var slider = options.slider || 'keywordThumbnail';
    var sliderObj = $('#' + slider);
 
    function draw() {

    }
    function slide(options) {
      options || (options = {});
      $('#' + prevBtn).click(function() {
        var left;
        if (0 < slideCount) {
          --slideCount;
          left = "-" + (slideCount * sliderWidth) + "px";
        } else {
          slideCount = maxSlideCount > 0 ? maxSlideCount : 0;
          left = "-" + (slideCount * sliderWidth) + "px";
        }
        sliderObj.animate({ 
          left: left
        }, duration );
        return false;
      });
      $('#' + nextBtn).click(function() {
        var left;
        if (maxSlideCount > slideCount) {
          ++slideCount;
          left = "-" + (slideCount * sliderWidth) + "px";
        } else {
          slideCount = 0;
          left = "0px";
        }
        sliderObj.animate({ 
          left: left
        }, duration );
        return false;
      });
    };

    return {
      draw: draw,
      slide: slide
    };
  };
}();

var APTimer = function() {
  return function(options) {
    options || (options = {});
    var defaultPeriod = options.defaultPeriod || 200;
    var timer;
    function schedule(task, period) {
      period || (period = defaultPeriod);
      timer = setInterval(function() {
        task.run();
      }, period);
    };

    function cancel() {
      if (timer) {
        clearInterval(timer);
      }
    }

    return {
      schedule: schedule,
      cancel: cancel
    };
  };
}();

var APTimerTask = function() {
  return function(options) {
    options || (options = {});
    var run = options.run || function() {};
    return {
      run: run
    };
  };
}();

