'use strict';

var go_hide = function(obj){
  $('#' + obj).empty().slideUp();
  $('div.lightbox').hide();
};
    
/* satay Class */
var SATAY = function(){

  var done = false;
  var video_wh = {
    'youtube': {'w': 425, 'h': 344},
    'yahoo': {'w': 512, 'h': 322},
    'vimeo': {'w': 400, 'h': 267},
    'google': {'w': 400, 'h': 326}
  };
  
  var check_uri = function(url){
    var ex = /^[(ht|f)tp(s?)\:\/\/]{1}\S/;
    return (!ex.test(url) ? false : true);
  };
    
  var check_cal = function(v){
    var re = /^\d+$/;
    return (!re.test(v) ? false : true);
  };
    
  var satay_param = function(n, v){
    return '&lt;param name="' + n + '" value="' + v + '" /&gt;';
  };
  
  var pattern = function(s){
    var str = '';
    switch (s){
      case 'youtube': str = /^http\:\/\/.+\/watch\?v=(.{11})($|\&)/; break;
      case 'yahoo': str = /^http\:\/\/.+\/watch\/(.{1,10})\/(.{1,10})($|\&)/; break;
      case 'google': str = /^http\:\/\/.+\/videoplay\?docid=(.{1,19})($|\&)/; break;
      case 'vimeo': str = /^http\:\/\/.+\/(.{1,10})($|\&)/; break;
    }
    return str;
  };
  
  var template = function(s, idx1, idx2){
    var host, ext = '';
    switch (s){
      case 'youtube':
        host = 'http://www.youtube.com/v/' + idx1 + '&amp;amp;hl=zh_TW&amp;amp;fs=1&amp;hd=1';
        break;
      case 'yahoo':
        host = 'http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.30';
        ext  = '&lt;param name="flashVars" value="id=' + idx2 + '&amp;amp;vid=' + idx1 + '&amp;amp;lang=en-us&amp;amp;intl=us&amp;amp;embed=1" />';
        break;
      case 'vimeo':
        host  = 'http://vimeo.com/moogaloop.swf?clip_id=' + idx1 + '&amp;amp;server=vimeo.com&amp;amp;show_title=1&amp;amp;show_byline=1&amp;amp;show_portrait=0&amp;amp;color=&amp;amp;fullscreen=1';
        break;
      case 'google':
        host  = 'http://video.google.com/googleplayer.swf?docid=' + idx1 + '&amp;amp;hl=zh-TW&amp;amp;fs=true';
        break;
    }

    var w       = check_cal( $('#width').val() ) ? $('#width').val() : 0;
    var h       = check_cal( $('#height').val()) ? $('#height').val() : 0;
    var o_menu  = $('#menu').is(':checked');
    var o_trans = $('#trans').is(':checked');
    var o_fulls = $('#fulls').is(':checked');
    var header  = '&lt;object type="application/x-shockwave-flash" data="' + host + '" width="' + w + '" height="' + h + '"&gt;';
    var str     = '&lt;param name="movie" value="' + host + '" /&gt;&lt;param name="allowscriptaccess" value="always" />';
    var footer  = '&lt;/object&gt;';

    str += o_menu ? satay_param('menu', o_menu) : '';
    str += o_trans ? satay_param('wmode', 'transparent') : '';
    str += o_fulls ? satay_param('allowfullscreen', 'true') : '';
    return (header + str + ext + footer);
  };
  
  var resume_html = function(str){
    var re = /&lt;/;
    result = str.replace(/&lt;/g, '<');
    result = result.replace(/&gt;/g, '>');
    result = result.replace(/&quot;/g, '"');
    return result;
  };
  
  return {

    go_transfer: function(){

      var result  = $('#result');
      var source  = $('input[type=radio]:checked').val();
      var url     = $('#url');
      var re      = pattern(source);
      try{
        
        if(check_uri(url.val())){
          var idx     = re.exec(url.val())[1];
          var idx2    = re.exec(url.val())[2];
          //result.html(template(source, idx, idx2));
          result.val( resume_html(template(source, idx, idx2)) );
          done = true;
        }
        else {
          alert( '請輸入正確的影片網址' );
        }
      }
      catch(err){
        alert( '網址格式與選取的網站不符' );
      }
    },

    get_wh: function(s){
      var width = $('#width'), height = $('#height'), trans = $('#trans'), url = $('#url');
      width.val( video_wh[s].w );
      height.val( video_wh[s].h );
      $('#' + s).attr('checked', true);
      this.url_tips(s);
      url.select();
      if(s === 'yahoo'){
        trans.attr({'checked':false, 'disabled':true});
      }
      else {
        trans.removeAttr('disabled');
      }
    },

    go_player: function(){
      var code = $('#result').val();
      var btn = '<div class="close"><a href="#" onclick="go_hide(\'player\');">關閉預覽</a></div>';
      var s = $('input[type=radio]:checked').val();
      var w = video_wh[s].w, h = video_wh[s].h;
      var win = $(window);
      if(done){
        code = code.replace(/&gt;/g, '>');
        code = code.replace(/&lt;/g, '<');
        code = code.replace(/&amp;/g, '&');
        $('div.lightbox').show();
        $('#player').css({'top':win.height()/3-h, 'left':win.width()/2-w, 'width':w, 'height':h+30, 'margin-top':h/2 + 'px', 'margin-left':w/2 + 'px'})
          .slideDown(1000)
          .animate({opacity:1.0}, 500, function(){$(this).html(code + btn);});
      }
    },

    url_tips: function(s){
      var url;
      switch (s){
        case 'youtube': url = 'http://tw.youtube.com/watch?v=rMe1BcJty6Q'; break;
        case 'yahoo': url = 'http://video.yahoo.com/watch/147377/769558'; break;
        case 'vimeo': url = 'http://www.vimeo.com/902069'; break;
        case 'google': url = 'http://video.google.com/videoplay?docid=6150320548187842685&hl=zh-TW'; break;
      }
      $('span.url_tips').html( 'Example: ' + url );
    }
  };
};

/* Google AJAX Libraries API */
google.load('jquery', '1');
google.setOnLoadCallback(function() {

  var satay = new SATAY();
  satay.url_tips( $('input[type=radio]:checked').val() );

  var objs = {
    transfer: $('#transfer'),
    text: $('input[type=text]'),
    url: $('#url'),
    radio: $('input[type=radio]'),
    fieldset: $('fieldset'),
    lightbox: $('div.lightbox'),
    panel: $('#panel_player'),
    win: $(window),
    result: $('#result')
  };
  
  objs.result.click(function(){ $(this).select(); });
  
  objs.transfer.click(function(){ satay.go_transfer(); return false; });

  objs.text.focus(function(){
    var obj = $(this); obj.css({'background':'#fffac8', 'border':'1px solid #000'});
  })
  .blur(function(){
    var obj = $(this); obj.css({'background':'#fff', 'border':'1px solid #aaa'});
  });

  objs.url.click(function(){
    var obj = $(this); obj.val('');
  })
  .blur(function(){
    var obj = $(this); obj.val($.trim(obj.val()));
  });
  
  objs.text.eq(0).trigger('focus');
  objs.radio.click(function(){ satay.get_wh($(this).attr('id')); });

  if(!$.support.noCloneEvent){
    objs.fieldset.after('<div class="spacer">&nbsp;</div>');
    objs.lightbox.css({'height': objs.win.height()});
  }

  objs.lightbox.css({'opacity':0.5}).click(function(){ satay.go_hide('player'); });
  objs.panel.click(function(){ satay.go_player(); });
  objs.transfer.hover(function(){
    var obj = $(this); obj.css('padding', '4px 4px 0 0');
  }, function(){
      var obj = $(this); obj.css('padding', 0);
  });
  
});

