if (typeof(String.prototype.trim) == 'undefined') {
  String.prototype.trim = function() {
  	return this.replace(/^\s+|\s+$/g,"");
  }
}
var $_j = jQuery.noConflict();

//var theclose = null;
var _isIE = /MSIE \d+/.test(navigator.userAgent) && navigator.platform == "Win32";

var vp_EmbedSwapper = {
  find_top: function(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
      do {
        curtop += obj.offsetTop;
      } while (obj = obj.offsetParent);
    }
    return curtop;
  },
  replace_embed: function(embd) {
    var rplc;
    if(_isIE) {
      var html = embd.outerHTML;
      
      if (html.match(/wmode\s*=\s*('|")opaque('|")/i) || html.match(/wmode\s*=\s*('|")transparent('|")/i)) {
        return;
      }
      
      if(html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i)) {
        rplc = html.replace(/wmode\s*=\s*('|")window('|")/i,"wmode='opaque'");
      } else {
        rplc = html.replace(/<embed\s/i,"<embed wmode='opaque' ");
      }
      
      embd.insertAdjacentHTML('beforeBegin',rplc);
      embd.parentNode.removeChild(embd);
    } else {
      rplc = embd.cloneNode(true);
      if(!rplc.getAttribute('wmode') || rplc.getAttribute('wmode').toLowerCase() == 'window') {
        rplc.setAttribute('wmode','opaque');
        embd.parentNode.replaceChild(rplc,embd);
      }
    }
  },
  run: function(top, bottom) {
    if (navigator.platform != "Win32") return;
    
    var embds = document.getElementsByTagName('embed');
    for(i = 0; i < embds.length; i++)  {
      embd = embds[i];
      
      embd_top = vp_EmbedSwapper.find_top(embd);
      embd_bottom = embd_top + embd.offsetHeight;
            
      if ((embd_top > top && embd_top < bottom) || (embd_bottom > top && embd_bottom < bottom)) {
        vp_EmbedSwapper.replace_embed(embd);
      }
    }
  }
}


// Config the widescreen player like this:
//   _vodpod_config = {host: 'http://vodpod.rails:3000', group_id: 1004, show_ads: false};

function CinematicWidget() {}

CinematicWidget.prototype = {
  button: null,
  small_button: null,
  overlay: null,
  group_id:'',
  show_ads:false,
  domains: ['youtube.com','dailymotion.com','myspace.com','google.com','blip.tv','vimeo.com','revver.com','veoh.com','megavideo.com','sapo.pt','hulu.com','metacafe.com','brightcove.com','teachertube.com','onsmash.com','yimg.com','imeem.com','slideshare.net','comedycentral.com','gametrailers.com','slide.com','ytimg.com','msn.com','viddler.com','photobucket.com','mtvnservices.com','vodpod.com','brightcove.tv','ning.com','worldstarhiphop.com','blogger.com','nbc.com','ifilm.com','kewego.com','godtube.com','go.com','liveleak.com','break.com','lequipe.fr','collegehumor.com','flickr.com','d1g.com','mavenapps.net','deezer.com','asterpix.com','tu.tv','livevideo.com','cbs.com','planetnetopia.com','truveo.com','alice.it','24kadra.com','wordpress.com','bbc.co.uk','youku.com','ustream.tv','feedburner.com','checkmycity.com','videoegg.com','eurosport.fr','tn.com.ar','sevenload.com','justin.tv','vidoosh.tv','sciencestage.com','funnyordie.com','rutube.ru','ontheairtv.com','wildscreen.tv','vladtv.com','trilulilu.ro','wat.tv','myvideo.de','fliggo.com','mediablog-brest.net','kidstube.com','redlasso.com','thedailyshow.com','globo.com','facebook.com','grou.ps','reuters.com','stage6.com','current.com','fbcdn.net','swissinfo.ch','overstream.net','mtv.com','videolog.tv','forbezdvd.com','animefreak.tv','youtube-nocookie.com','traileraddict.com','ordienetworks.com','clipsyndicate.com','dimewars.com','clamshare.com','aolcdn.com','tudou.com','crunchyroll.com','streetfire.net','disclose.tv','vidzshare.net','ted.com','theonion.com','jiggystudio.com','movieweb.com','ign.com','animeshippuuden.com','clearspring.com','speedera.net','kyte.tv','qik.com','5min.com','aol.com','llnwd.net','mail.ru','multiply.com','2mdn.net','scribd.com','archive.org','divshare.com','indianfeelingstv.com','realitatea.net','seesmic.com','videojug.com','goal4replay.net','yahoo.com','fcnantes.com','fora.tv','gamekyo.com','gamevideos.com','luso.tv','splashcast.net','paltalk.com','uol.com.br','jibjab.com','motionbox.com','amazonaws.com','220.ro','fearlessmusic.com','mogulus.com','pitchfork.tv','g4tv.com','image.com.com','eatlime.com','onetruemedia.com','rockyou.com','jumpcut.com','anunciotube.com','bcast.co.nz','goleft.tv','screencast.com','rtp.pt','gorillanation.com','1up.com','guba.com'],
  host: 'http://widgets.vodpod.com',
    
  init: function(doc) {
  	if (typeof(_vodpod_config) != 'undefined') {
  		this.host = _vodpod_config.host || this.host;
  		if (_vodpod_config.group_id) {
  		  this.group_id = _vodpod_config.group_id;
  		}
  		if (_vodpod_config.show_ads == false && _vodpod_config.group_id) {
  			this.show_ads = false;
  		}
  	}

    this.make_button(doc);
    // Find all embeds on the page that look like videos and decorate with the popup button
    var cw = this;
    $_j('embed,object').each(function() {
    	if (this.tagName != 'OBJECT' || this.getElementsByTagName('embed').size == 0 ){
    		// skip OBJECT tags with embeds inside them
	    	var em_src = cinematic_widget.get_embed_domain(this);
	    	var m = em_src.match(/http\:\/\/(.*?)\//);
	    	var domlist = cinematic_widget.domains;
	    	if (m) {
	    		var domain = m[1];
	    		for (var i = 0; i < domlist.length; i++ ){
	    			if (domain.indexOf(domlist[i]) >= 0) {
	    				// This embed src is on our whitelist, so decorate it
				    	cw.append_widescreen_button(this);
	    			}
	    		}
	    	}
    	}
    });
    
  },
  
  get_embed_domain: function(elt) {
  	if (elt.tagName == 'OBJECT') {
  		// Drill down to the 'movie' param
			var ps = elt.getElementsByTagName('param');
			for (var i = 0; i < ps.length; i++ ){
				if (ps[i].name == 'movie') {
					return elt.data + ps[i].value;
				}
			}  		
  	}	else {
  		return elt.src;
  	}
  },
  
  append_widescreen_button: function(elt, sep, button_elt, button_proto) {
    elt.style.marginBottom = '0px';
    if (!sep) {
      sep = document.createElement("BR");
    }
    var next_el = elt; //elt.parentNode.insertBefore(sep, elt.nextSibling);
    var new_button = (button_proto ? $_j(button_proto).clone()[0] : $_j(this.button).clone()[0]);
    new_button.onclick = this.make_button_callback((button_elt ? button_elt : elt), elt.parentNode);
    elt.parentNode.insertBefore(new_button, next_el.nextSibling);
    var embed_bottom = $_j(elt).offset().top + $_j(elt).height();
    var embed_width = $_j(elt).width();
    var button_top = $_j(new_button).offset().top;
    $_j(new_button).css({'margin-top': (embed_bottom - button_top) + 'px', 'width' : (embed_width -4)+ 'px'});
  },
  
  make_button_callback: function(embed_element, embed_parent) {
    var local_this = this;
    return(function() {
        local_this.load_video_action(embed_element, embed_parent);
        return false;
      });
  },
  
  make_button: function(doc) {
    // Make all of these !important !!!
  	var css_code = '.vp_wsbutton {border:0 !important;-webkit-border-bottom-left-radius:5px !important;-webkit-border-bottom-right-radius:5px !important;-moz-border-radius-bottomleft:3px !important;-moz-border-radius-bottomright:3px !important;background-color:#2F2F2F !important;text-align:right !important;padding:2px 4px 0 0 !important;margin:0 !important}' +
  								 '.vp_wsbutton a {border: 0 !important;text-decoration:none !important;}' +
  	                            '.vp_wsclick {cursor:pointer !important;float:right !important;background:url(http://assetscdn.vodpod.com/images/widget/wsbutton.gif) no-repeat top right !important;width:90% !important;height:20px !important}.vp_wsclick:hover {background-position: bottom right !important}' +
  	                            '.vp_wsclose {cursor:pointer !important;background:url(http://assetscdn.vodpod.com/images/widget/wsclose.gif) no-repeat top left !important;width:83px !important;height:20px !important;border:0 !important;text-decoration:none !important}.vp_wsclose:hover {background-position: bottom left !important;text-decoration:none !important}';
  	if  (jQuery.browser.msie) {
  		// DISABLED: This doesn't really seem to be working. Add our rounded corner behavior sheet
  		//document.createStyleSheet(this.host + '/stylesheets/border-radius.htc');
  		// crazy IE method for adding a style tag
	    var styleSheetObj = document.createStyleSheet();
	
	    var styleObj = styleSheetObj.owningElement || styleSheetObj.ownerNode;
	    styleObj.setAttribute("type", "text/css");
	    styleObj.id = 'vodpod_widescreen_widget';
	    
	    ruleArray = css_code.split("}");
	
	    for (var i = 0; i < ruleArray.length - 1; i++) {
	      var currentRule = ruleArray[i].trim();
	      var nameValueArray = currentRule.split("{");
	      var name = nameValueArray[0].trim();
	      var value = nameValueArray[1].trim();
	      
	      if (value != "") {
	        styleSheetObj.addRule(name,value);
	      }
	    }
  	} else {
  	  $_j('head').append('<style>' + css_code + '</style>');
  	}
  	this.button = $_j('<div class="vp_wsbutton" style="height:24px !important;"><a class="vp_wsclick" href="#" title="play video widescreen">&nbsp;</a></div>');
  },

  load_video_action: function(embed_element, embed_parent) {
    this.load_video(embed_element, embed_parent);
    this.load_overlay();
  },
  
  load_overlay: function() {
    var overlay = document.createElement("DIV");
    $_j(overlay).css({display: 'block', position: 'fixed', 'background-image': 'url(http://assetscdn.vodpod.com/images/lightbox-overlay.png)',
    									width: '100%', height: '100%', left: 0, top: 0, zIndex: '1600000', cursor: 'wait'});
    									
    document.body.appendChild(overlay);
    
    overlay.style.height = $_j(document).height();
    this.overlay = overlay;
  },
  
  remove_overlay: function() {
    if (this.overlay) {
      this.overlay.parentNode.removeChild(this.overlay)
      this.overlay = null;
    }
  },
  
  find_title: function(elt) {
    if (!elt || elt == document.body) {
      return '';
    }
    var i;
    var headings = $_j(elt).find('h3:first').text();
    if (headings.length > 0) {
      return headings;
    }
    headings = $_j(elt).find('h2:first').text();
    if (headings.length > 0) {
      return headings;
    }
    headings = $_j(elt).find('h1:first').text();
    if (headings.length > 0) {
      return headings;
    }
    return this.find_title(elt.parentNode);
  },
  
  // I stole all this code from phil - thanks phil!
  load_video: function (embed_element, embed_parent) {
    var title = this.find_title(embed_parent);
    
    var vodpod_id = '';
    var flashsrc = '';
    if (typeof(embed_element) == "string") {
      vodpod_id = embed_element;
    } else if (embed_element.tagName == 'EMBED') {
      flashsrc = embed_element.src + '?';
      if (embed_element.attributes['flashvars']) {
        flashsrc += embed_element.attributes['flashvars'].nodeValue;
      }
      if (match = embed_element.src.match(/http:\/\/widgets\.vodpod\.com.*?((ExternalVideo|Groupvideo|Video)\.\d+)/i)) {
        vodpod_id = match[1];
      }
    } else if (embed_element.tagName == 'OBJECT') {
      var ps = embed_element.getElementsByTagName("PARAM");
      var movie = embed_element.data;
      var flashvars = '';
      for (var i = 0; i < ps.length; i++ ){
        if (ps[i].name.match(/flashvars/i)) {
          flashvars = ps[i].value;
        }
      }
      flashsrc = movie + '?' + flashvars;
    }
    
    var container = document.createElement('div');
    var iframe = document.createElement('iframe');
    var close_img = $_j('<a class="vp_wsclose" title="close">&nbsp;</a>', document)[0];

		// Determine the popup dimensions based on viewport size and aspect
    var doc_width = document.documentElement.clientWidth * 0.8;
    var doc_height = document.documentElement.clientHeight * 0.9;
		var chrome_height = (43 + 118 + 30);

		var video_h = (doc_height - chrome_height);
		var video_w = doc_width;
		var wide_aspect = 16.0/9.0;
		var allowable_aspect = 2.0;
		var narrow_aspect = 4.0/3.0;
	
		if ((video_w / video_h) >= allowable_aspect) {
			// screen is wide enough for 16x9, so just letterbox width for sizing
			video_w = (video_h * allowable_aspect);
			doc_width = video_w;
		} else if ((video_w / video_h) > wide_aspect) {
			// screen is wide enough for 16x9, so just letterbox width for sizing
			video_w = (video_h * wide_aspect);
			doc_width = video_w;
		} else if (video_w > 600) {
			// we can fit a 16x9 player, but we'll letterbox the height to do it
			video_h = (video_w / wide_aspect);
			doc_height = video_h + chrome_height;
		} else {
			// Use 4x3 aspect based on the available height
			video_w = (video_h * narrow_aspect);
			if (video_w > doc_width) {
				// whoops! too big. go by width
				video_w = doc_width;
				video_h = video_w / narrow_aspect;
			}
		}

		title = title.replace(/[^a-zA-Z0-9 ]/g,'');    
    var url = this.host + '/javascripts/cinematic_popup/' + vodpod_id + '?flashsrc=' + encodeURIComponent(flashsrc) + '&width=' + (doc_width-15) + '&height=' + doc_height +
    	'&video_w=' + video_w + '&video_h=' + video_h + '&group_id=' + this.group_id + '&ads=' + this.show_ads + '&title=' + encodeURIComponent(title)
    if (Math.random() >= 0.5) {
      url += '&ad=user';
    }
    iframe.src = url;
  
    var scrollTop = 0;
  
    if (document.body.scrollTop) {
      // Some browsers (WebKit) do this the web-standards way.
      scrollTop = document.body.scrollTop;
    } else {
      // And some just mimic IE 6 (everyone else).
      scrollTop = document.documentElement.scrollTop;
    }
    
    var top = Math.max(((document.documentElement.clientHeight / 2) + (scrollTop)), 292);
    
    var ie6 = /MSIE 6/.test(navigator.userAgent) && navigator.platform == "Win32";
    
    $_j(iframe).attr({'frameBorder':0, 'allowTransparency':!ie6, 'scrolling':'no'}).
    	css({width: '100%', height: (doc_height+10) + 'px', 'padding-bottom': '10px', overflow:'hidden', 'border':0});
    if (ie6) {
    	$_j(iframe).css({backgroundColor:'#666'});
    }
    container.id = 'vodpod_widget_popup';
    container.style.width = video_w + 'px';
    container.style.height = (doc_height+10) + 'px';
    container.style.marginTop = '-' + (doc_height/2) + 'px';
    container.style.marginLeft = '-' + (video_w / 2) + 'px';
    container.style.position = 'absolute';
    container.style.left = '50%';
    container.style.zIndex = '1600001';
    container.style.top = top + 'px';
    
    $_j(close_img).css({position: 'absolute', top: '15px', right: '20px'});
    
    vp_EmbedSwapper.run(top - ((doc_height+10)/2), top + ((doc_height+10)/2));
    
    close_img.onclick = function(this_var) {
      var local_this = this_var;
      return (function() {
        local_this.close_video();
      });
    }(this);
    
    // if (/MSIE (6|7)/.test(navigator.userAgent)) {
    //   // We can't attach to the iframe.
    //   setTimeout(function() {
    //     container.appendChild(close_img);
    //   }, 1000);
    // } else  {
    //   iframe.onload = function() {
    //     container.appendChild(close_img);
    //   }
    // }
    
    setTimeout(function() {
      container.appendChild(close_img);
    }, 1000);
    
    container.appendChild(iframe);
    
    document.body.appendChild(container);
  },
  
  close_video: function() {
    var el = document.getElementById('vodpod_widget_popup');
    if (el) {
      el.parentNode.removeChild(el);
      this.remove_overlay();
    }
  }
}
var cinematic_widget = new CinematicWidget();
$_j(document).ready(function(){
  cinematic_widget.init(document);
});

