/* ------------------------------------------------------------ */
/*                                                              */
/*                         global param                         */
/*                                                              */
/* ------------------------------------------------------------ */

var _loc      = location.pathname;
var _path = _loc.substring(0,_loc.lastIndexOf('/')+1);
var _lv1path = _path.split('/')[1];
var _lv2path = _path.split('/')[2];
var _lv3path = _path.split('/')[3];
var _pwd  = _path.split('/')[_path.split('/').length-2];
var _html = _loc.substring(_loc.lastIndexOf('/')+1);
var _pageID = '';

/* for backward comatible */
var _pathName = _loc.substring(0,_loc.lastIndexOf('/')+1);
var _fileName = _loc.substring(_loc.lastIndexOf('/')+1);
var _hpath     = (location.pathname.substr(location.pathname.length-1,1)=='/') ? (location.pathname+'index.html'):location.pathname;

var _swfAry   = new Array();
var isIE  = !$.support.opacity;
var isIE6 = isIE && !window.XMLHttpRequest;
var isIE7 = isIE && window.XMLHttpRequest && ((!document.documentMode)||(document.documentMode && document.documentMode == '7'))
var $j = jQuery.noConflict();





/* ------------------------------------------------------------ */
/*                                                              */
/*                       import libraries                       */
/*                                                              */
/* ------------------------------------------------------------ */

document.write('<script type="text/javascript" src="/tvtop/_common/js/lib/jquery.easing.js"></script>');
document.write('<script type="text/javascript" src="/tvtop/_common/js/lib/jquery.jcarousellite.min.js"></script>');
document.write('<script type="text/javascript" src="/tvtop/_common/js/lib/jquery.mousewheel.min.js"></script>');
document.write('<script type="text/javascript" src="/tvtop/_common/js/lib/jquery.blend-min.js"></script>');
document.write('<script type="text/javascript" src="/tvtop/_common/js/lib/jquery.flatheights.js"></script>');

// PNGFIX --------------------------------------------------------
if(isIE6) {
  document.write('<style type="text/css">.transparent, .head, .body, .heading, .extra a, .more a, .carousel_prev, .carousel_next, #chrome, #ad-super, #ad-rect, #logo-site a, #logo-site span, #nav-main, .footer_logo a { behavior:url(/tvtop/_common/js/lib/iepngfix/iepngfix.htc) }</style>');
  document.write('<script type="text/javascript" src="/tvtop/_common/js/lib/iepngfix/iepngfix_tilebg.js"></script>');
  try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {}  // ie6 background-image reload issue
}





/* ------------------------------------------------------------ */
/*                                                              */
/*                      jQuery initialize                       */
/*                                                              */
/* ------------------------------------------------------------ */

$j(function($){
  // _pageID ------------------------------------------------------------
  _pageID = $('body').attr('id');

  // ajax driven pages ------------------------------------------------------------
  if(_pageID=='home') {
    getTickerlist();
    getToppageinfolist();
    getNowonairlist(1);
  }

  // current menu -------------------------------------------
  $('#nav-main li#nm-' + _pathName.split('/')[1] + ' a').addClass('on');

  // breadcrumbs ------------------------------------------------------------
  $('body[id!="home"] #breadcrumbs').breadcrumbs();

  // [ Utility ] : img hover : toggle -------------------------------------------
  $('.imghover').imghover();
  $('.imgtoggle').imgtoggle();

  // [ Utility ] : .first,.last --------------------------------------------------------
  $('li:first-child, dt:first-child, dd:nth-child(2), div > .column:first').addClass('first');
  $('li:last-child, dt:last-child, dd:nth-child(2), div > .column:last').addClass('last');
  $('#content ul,#content ol,.stripe,.item').each(function(i) {
    $('>li:even,>tbody>tr:even',this).addClass('even');
    $('>li:odd,>tbody>tr:odd',this).addClass('odd');
  });

  // [ Utility ] : dl.column ------------------------------------------------------------
  $('dl.column,dl.columnR').each(function(i) {
    var dtWidth = [];
    $(this).children('dt').each(function(j) {
      dtWidth.push($(this).width()+5);
    });
    var max = Math.max.apply(null,dtWidth);
    $(this).children('dt').width(max);
    var marginLR = ($(this).hasClass('columnR')) ? 'marginRight' : 'marginLeft';
    $(this).children('dd').css(marginLR,max+10);
  });

  // [ Utility ] : window -----------------------------------------------------
  $('a.blank, area.blank, a.pdf').click(function(e){ e.preventDefault(); window.open(this.href, '_blank','scrollbars=yes,resizable=yes,status=yes,directories=yes,menubar=yes,toolbar=yes'); return false; });
  $('.close a, a.close').click(function(e){ e.preventDefault(); window.close(); return false; });
  $('a.popup').click(function(e){ e.preventDefault(); window.open(this.href, 'popup','scrollbars=yes,resizable=no,status=no,directories=no,menubar=no,toolbar=no,width=800,height=650'); return false; });
  $('a.popup_s').click(function(e){ e.preventDefault(); window.open(this.href, 'popup_s','scrollbars=yes,resizable=no,status=no,directories=no,menubar=no,toolbar=no,width=500,height=450'); return false; });
  $('a.popup_s2').click(function(e){ e.preventDefault(); window.open(this.href, 'popup_s2','scrollbars=yes,resizable=no,status=no,directories=no,menubar=no,toolbar=no,width=500,height=335'); return false; });

  // hover : blend effect -------------------------------------------
  $(".list-button li a").blend({speed:350,opacity:1});

  // gotop smooth scroll ------------------------------------------------------------
  $('p a[href*="#"]').click(function() {
    var targ = $(this).attr('href').split('#')[1];
    $('#'+targ).doScroll();
    return false;
  });

  // tabs --------------------------------------------------------
  $('.tab').tabs();

  // .module .body transparent x padding issue for ie6 ------------------------------------------------------------
  if (isIE6) $('.body').wrapInner("<div class='inner clearfix'></div>");

  // flatheights ------------------------------------------------------------
  $(window).load(function() {
    $('#mod-present ol').each(function(i) {
      $(this).children('li').flatHeights();
    });
    $('table.border tr th > span.autoheight').each(function(i) {
      $(this).height($(this).parent().height()-2);
    });
  });

  // Banner
  if(_pageID=='home') $.fn.setBanners();
});





/* ------------------------------------------------------------ */
/*                                                              */
/*                      Data Loader Class                       */
/*                ファイルの一括ダウンロードクラス                */
/*                                                              */
/* ------------------------------------------------------------ */
var iiLoader_class = function(){
  this.load = function (files, cb_sucsess, cb_error) {
    //  files      :ターゲットファイル配列
    // cb_sucsess    :コールバック（取得したデータを配列で返す）
    // cb_error      :エラーコールバック
    
    load_file(files, cb_sucsess, cb_error, new Array());
  }
  var load_file = function (files, cb_sucsess, cb_error, ret) {
    if (files.length<1) {
      cb_sucsess(ret);
      return;
    }
    $j.ajax({
      url: files[0],
      type: 'GET',
      dataType: 'xml',
      success: function (data) {
        ret.push(data);
        files.shift();
        load_file(files, cb_sucsess, cb_error, ret);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown){
        cb_error(ret, XMLHttpRequest, textStatus, errorThrown);
      }
    });
  }
};





/* ------------------------------------------------------------ */
/*                                                              */
/*                         setBanners                           */
/*                                                              */
/* ------------------------------------------------------------ */
(function($){
  var nowObj = {};
  var now;
  $.ajax({
    url: '/jsp/nowtime.jsp',
    cache: false,
    dataType: 'xml',
    timeout: 30000,
    error: function() {
    },
    success: function(xml) {
      nowObj.date = $(xml).find('now now_date').text();
      nowObj.time = $(xml).find('now now_time').text();
      now = parseInt(nowObj.date,10) * 10000 + Math.floor(parseInt(nowObj.time,10)/100);
    }
  });
  $.fn.setBanners = function() {
    // iiLoader ------------------------------------------------------------
    var bannerLoader = new iiLoader_class();
    bannerLoader.load(
      [ '/tvtop/_common/banner/left/data.xml',
        '/tvtop/_common/banner/right/data.xml'
      ],
      function(data){
        for (var i=0; i<data.length; i++) {
          setBannerData(data[i],i);
        };
      }
    );
  }
  var setBannerData = function(ajaxXML,i) {
    type = (i==0) ? 'left':'right';
    var bannerlist = '';
    var imgPath = $(ajaxXML).find('config').attr('path');
    $(ajaxXML).find('item[pid='+_pageID+']').each(function(j) {
      var heightCls = ($(this).attr('height') == '60') ? ' class="h60"' : ''; 
      if (parseInt($(this).attr('sdate'),10)<=now || location.hostname=='dev.disneychannel.jp') {
        if ($(this).attr('url')=='') {
          bannerlist += '<li' + heightCls + '><img src="'+imgPath+$(this).attr('img')+'" alt="'+$(this).attr('alt')+'" /></li>';
        } else {
          bannerlist += '<li' + heightCls + '><a href="'+$(this).attr('url')+'" target="'+$(this).attr('trg')+'" name="jupiter_tv_'+type+'-banner-'+$(this).attr('cid')+'" type="custom" onclick="cto.tracklink(this)"><img src="'+imgPath+$(this).attr('img')+'" alt="'+$(this).attr('alt')+'" /></a></li>';
        }
      }
    });
    if (bannerlist=='') return null;
    bannerlist = '<ul class="list-banner">'+bannerlist+'</ul>';
    switch (type) {
      case 'left':  $('#sidebar').append(bannerlist); break;
      case 'right': $('#sidebar2').append(bannerlist); break;
    }
  }
})(jQuery);





/* ------------------------------------------------------------ */
/*                                                              */
/*                        breadcrumbs                           */
/*                                                              */
/* ------------------------------------------------------------ */
(function($){
  $.fn.breadcrumbs = function() {
    if($(this).html()!='') return null;
    var lv1label={'tvtop':'テレビ','disneych':'ディズニー・チャンネル'};
    var lv2label={'contact':'お問い合わせ'};
    var lv1 = ((typeof lv1label[_lv1path]=='undefined') ? _lv1path.toUpperCase():lv1label[_lv1path]);
    var lv2 = ((typeof lv2label[_lv2path]=='undefined') ? '':lv2label[_lv2path]);
    var crumbs = '';
    if (lv1 != '') crumbs += '<li><a href="/'+_lv1path+'/" title="'+lv1+'">'+lv1+'</a>&gt;</li>';
    if (lv2 != '' && (_lv3path != '' || (_html !='index.html' && _html != ''))) crumbs += '<li><a href="/'+_lv1path+'/'+_lv2path+'/">'+ lv2 +'</a>&gt;</li>';
    crumbs += ( '<li class="here"><span>' + $('title').html().split('|')[0] + '</span></li>');
    $(this).prepend('<ol>'+crumbs+'</ol>');
  }
})(jQuery);





/* ------------------------------------------------------------ */
/*                                                              */
/*                     ticker / carousel                        */
/*                                                              */
/* ------------------------------------------------------------ */
(function($){
  $.fn.startTicker = function() {
    $(this).jCarouselLite({
      mouseWheel: 1,
      hoverPause: true,
      auto: 5000,
      speed: 500,
      easing: 'easeOutExpo',
      circular: 1,
      visible: 1
    });
  }
  $.fn.startCarousel = function(id,itemLength) {
    var carouselNavPath = '#mod-'+id+' .head .extra';
    var carouselNavLast = '';
    $(carouselNavPath).append('<a class="carousel_prev">&lt;</a><a class="carousel_next">&gt;</a>');
    var btnPrevPath  = '#mod-'+id+' .carousel_prev';
    var btnNextPath  = '#mod-'+id+' .carousel_next';
    var btnGoAry = new Array();
    for (var i=1;i<=(itemLength);i++) {
      btnGoAry.push('#mod-'+id+' a.item'+i);
    }
    for (var j=1;j<=((itemLength + $('#mod-'+id+' .carousel li.nobg').size()) / 5);j++) {
      carouselNavLast = 'item'+((j-1)*5+1);
      $(carouselNavPath+' a.carousel_next').before('<a class="'+carouselNavLast+'">'+j+'</a>');
    }
    if (itemLength<=5) {
      $(carouselNavPath).empty();
      $('#mod-'+id+' a.carousel_next, #mod-'+id+' a.carousel_prev').addClass('disabled2');
    } else {
      $(carouselNavPath+' a.item1').addClass('on');
      $(btnPrevPath).addClass(carouselNavLast);
      $(btnNextPath).addClass('item1');
    }

    $(this).jCarouselLite({
      mouseWheel: 1,
      speed: 300,
      circular: false,
      visible: 5,
      scroll: 5,
      btnPrev: btnPrevPath,
      btnNext: btnNextPath,
      btnGo: btnGoAry,
      afterEnd: function(obj) {
        $(carouselNavPath+' a').removeClass('on');
        $(carouselNavPath+' a.'+obj.attr('class')).not('.carousel_prev,.carousel_next').addClass('on');
        $(btnPrevPath).removeClass(carouselNavLast);
        $(btnNextPath).removeClass('item1');
        if (obj.index()<1) $(btnPrevPath).addClass(carouselNavLast);
        if ((itemLength-obj.index())<=5) $(btnNextPath).addClass('item1');
      }
    });
  }
})(jQuery);





/* ------------------------------------------------------------ */
/*                                                              */
/*                           tabs                               */
/*                                                              */
/* ------------------------------------------------------------ */
document.write('<style type="text/css">.tabbody-wrapper { display:none; overflow:hidden; }</style>');
(function($){
  $.fn.tabs = function() {
    return this.each(function() {
      var node = $(this);
      var defaultTab = 0;
      node.find('.tabbody').hide();
      node.find('.tabbody:eq('+defaultTab+')').show();
      node.find('.tabbody-wrapper').show();
      node.find('.tabnav li:eq('+defaultTab+')').addClass('on');
      node.find('.tabnav li a').click(function() {
        if (!$(this).parent('li').is('.on')) {
          var re = /([_\-\w]+$)/i;
          var target = $('#' + re.exec(this.href)[1]);
          if (target.size() > 0) {
            node.find('.tabbody:visible').hide();
            target.show();
            node.find('.tabnav li.on').removeClass('on');
            $(this).parent('li').addClass('on');
            switch (target.selector) {
              case '#tab-dc': getNowonairlist(1); break;
              case '#tab-xd': getNowonairlist(4); break;
            }
          }
        }
        return false;
      });
    });
  }
})(jQuery);





/* ------------------------------------------------------------ */
/*                                                              */
/*                          doScroll                            */
/*                                                              */
/* ------------------------------------------------------------ */
(function($){
  $.fn.extend({
    doScroll: function() {
      $('html,body').animate({scrollTop: $(this).offset().top}, 500);
    }
  });
})(jQuery);





/* ------------------------------------------------------------ */
/*                                                              */
/*                      on air alert message                    */
/*                                                              */
/* ------------------------------------------------------------ */
$j(function($){
  if($('body#home').size()) {
    $.ajax({
      url: '/jsp/onair_status.jsp',
      type: 'GET',
      async: true,
      cache: false,
      dataType: 'xml',
      timeout: 1000,
      error: function(){
      },
      success: function(xml){
        msg = new Array();
        $(xml).find('channel_lst channel').each(function() {
          if ($(this).find('status').text()=='1') {
            switch ($(this).attr('channel_id')) {
              case '1': msg.push('<li><a href="/alert/disneychannel.html">現在、ディズニー・チャンネルにおいて放送障害が発生しております。</a></li>'); break;
              case '4': msg.push('<li><a href="/alert/disneyxd.html">現在、ディズニーXDにおいて放送障害が発生しております。</a></li>'); break;
            }
          }
        });
        if (msg.length) {
          $('body').css({'backgroundPosition':'50% 30px'}).prepend('<div id="alert" style="height: 30px;"><ul style="line-height: 14px;">'+msg.join('')+'</ul></div>');
        }
      }
    });
  }
});





/* ------------------------------------------------------------ */
/*                                                              */
/*                       image switcher                         */
/*            [ filename.ext <-> filename_on.ext ]              */
/*                                                              */
/* ------------------------------------------------------------ */
(function($){
  $.fn.extend({
    imghover: function() {
      return this.each(function() {
        var node = $(this);
        if (!node.is('img')&&!node.is(':image')){
          node.find('img,:image').imghover();
          return;
        }
        node.hover(function() {
          node.addClass('hover');
          if (!node.hasClass('on')) $.fn.imgOn(node);
        },function() {
          node.removeClass('hover');
          if (!node.hasClass('on')) $.fn.imgOff(node);
        });
      });
    },
    imgtoggle: function() {
      return this.each(function() {
        var node = $(this);
        if (!node.is('img')&&!node.is(':image')){
          node.find('img,:image').imgtoggle();
          return;
        }
        node.click(function() {
          if (node.hasClass('on')) {
            $.fn.imgOff(node);
          } else {
            if (!node.hasClass('hover')) $.fn.imgOn(node);
          }
          node.toggleClass('on');
        });
      });
    },
    imgOn: function(node) {
      if(node.attr('src').match(/^(.+)_on(\.[a-z]+)$/)) return;
      if(isIE6 && node.context.style.filter) {
        node.context.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+node.context.style.filter.split('"')[1].replace(/^(.+)(\.[a-z]+)$/,'$1_on$2')+'",sizingMethod="scale")';
      } else {
        node.attr('src',node.attr('src').replace(/^(.+)(\.[a-z]+)$/,'$1_on$2'));
      }
    },
    imgOff: function(node) {
      if(isIE6 && node.context.style.filter) {
        node.context.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+node.context.style.filter.split('"')[1].replace(/^(.+)_on(\.[a-z]+)$/,'$1$2')+'",sizingMethod="scale")';
      } else {
        node.attr('src',node.attr('src').replace(/^(.+)_on(\.[a-z]+)$/,'$1$2'));
      }
    }
  });
})(jQuery);





/* ------------------------------------------------------------ */
/*                                                              */
/*                      Flash  -  SWFObject                     */
/*                                                              */
/* ------------------------------------------------------------ */
// <div id="swf1Holder"></div>
// <script type="text/javascript">_swf({type:'promo'});</script>
// <script type="text/javascript">_swf({w:'940',h:'210',id:'swf2',swf:'./_common/swf/feature.swf',param:'_v=Fp&flag=1',bgcolor:'#990000'});</script>

function _swf(obj) {
  if (typeof obj == 'undefined') return null;
  if (_swfAry.toString().indexOf(obj.type)>-1) return null;

  var expressInstall = './_common/swf/expressInstall.swf';
  var flvars = {};
  var params = {};
  var attrib = {};

  switch (obj.type) {
    default:
      prm    = obj;
      if (prm.param) { var pAry=prm.param.split('&'); for (var i=0;i<pAry.length;i++) {var a=pAry[i].split('='); flvars[a[0]] = a[1];} };
      params = {bgcolor:obj.bgcolor,scale:obj.scale,salign:obj.salign,wmode:obj.wmode};
  }
  if (typeof prm == 'undefined') return null;

  /* --- [4] swf version --- */
  prm.v = (obj.v) ? obj.v : '9.0.28';
  if(!swfobject.hasFlashPlayerVersion(prm.v)){
  }

  /* --- [6] flvars --- */
  flvars._p = _pathName;
  if (location.search) { var sAry=location.search.substr(1).split('&'); for (var i=0;i<sAry.length;i++) {var a=sAry[i].split('='); flvars[a[0]] = a[1];} };

  /* --- [7] params --- */
  params.bgcolor = (params.bgcolor) ? params.bgcolor : '#ffffff';
  params.scale   = (params.scale)   ? params.scale :   'noScale';
  params.salign  = (params.salign)  ? params.salign :  'TL';
  params.wmode   = (params.wmode)   ? params.wmode :  'transparent';
  params.allowFullScreen = 'true';

  /* --- [8] attrib --- */
  attrib.id = prm.id;

  swfobject.embedSWF(prm.swf, prm.id+'Holder', prm.w, prm.h, prm.v, expressInstall, flvars, params, attrib);
}

