(function () {
  /* Client-side access to querystring name=value pairs
     Version 1.3
     28 May 2008

     License (Simplified BSD):
     http://adamv.com/dev/javascript/qslicense.txt
  */

  function Querystring(qs) { // optionally pass a querystring to parse
    this.params = {};

    if (qs == null) qs = location.search.substring(1, location.search.length);
    if (qs.length == 0) return;
  
    // Turn <plus> back to <space>
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&'); // parse out name/value pairs separated via &

    // split out each name=value pair
    for (var i = 0; i < args.length; i++) {
      var pair = args[i].split('=');
      var name = decodeURIComponent(pair[0]);
    
      var value = (pair.length==2)
	? decodeURIComponent(pair[1])
	: name;
    
      this.params[name] = value;
    }
  }

  Querystring.prototype.get = function(key, default_) {
    var value = this.params[key];
    return (value != null) ? value : default_;
  }
 
  Querystring.prototype.contains = function(key) {
    var value = this.params[key];
    return (value != null);
  }
	
  // main
  if(typeof extVideoConfig == 'object'){
    var c = extVideoConfig;
    
    if(! c.type && ! c.vid){
      /* youtube */
      if(extVideoConfig.url.match(/http:\/\/[^\.]+\.youtube\.com\/watch\?(.*)/)){
	var qs = new Querystring(RegExp.$1);
	if(qs.get('v')){
	  c.type = 1;
	  c.vid  = qs.get('v');
	}
      }
      /* nicovideo */
      if(extVideoConfig.url.match(/http:\/\/www\.nicovideo\.jp\/watch\/([^\/\?]+)/)){
	if(RegExp.$1){
	  c.type = 2;
	  c.vid  = RegExp.$1;
	}
      }
    }

    /*
     *  Youtube
     */
    if(c.type == 1){
      url = 'http://www.youtube.com/v/' + c.vid + '&hl=ja&fs=1';

      var html = [ '<object width="', c.width, '" height="', c.height, '">',
		   '<param name="movie" value="', url, '"></param>',
		   '<param name="allowFullScreen" value="true"></param>',
		   '<param name="wmode" value="transparent"></param>',
		   '<embed src="', url, '" type="application/x-shockwave-flash" allowfullscreen="true" wmode="transparent" width="', c.width, '" height="', c.height, '"></embed></object>'
      ];
      document.write(html.join(''));
    }

    /*
     *  nicovideo
     */
    if(c.type == 2){
      var html = [ '<script type="text/javascript" src="http://ext.nicovideo.jp/thumb_watch/', c.vid,
		   '?w=', c.width,
		   '&h=', c.height,
		   '&n=&tr=1&cb="></script>'
      ];
      document.write(html.join(''));
    }

    if(c.type && c.vid){
      var log_url = 'http://blog.sakura.ne.jp/pages/tools/external_video_log?vid=' + encodeURIComponent(c.vid) + '&type=' + encodeURIComponent(c.type) + '&url=' + encodeURIComponent(document.location.href) + '&__time=' + (new Date()).getTime();
      document.write('<img src="' + log_url + '" border="0" width="0" height="0" />');
    }
  }
})();


