/*
	 
iTransmogrify!

by: Joe Maller 
	joe@joemaller.com
	
Project: http://itransmogrify.googlecode.com/


The following code will be injected into whatever page you're viewing,
automatically detecting and converting many embedded Flash links into 
clickable image links which open in the Safari or the iPhone YouTube player.

Please don't paste this code directly into a page or bookmark. Using the
bookmarklet will automatically pull the most recent stable version of
the code from the Google Code repository.


// javascript:if%28typeof%28iTransmogrify%29%3D%3D%27undefined%27%29%7Bvar%20s%3Ddocument.createElement%28%27script%27%29%3Bs.src%3D%27http%3A%2F%2Fitransmogrify.googlecode.com%2Ffiles%2FiTransmogrify.js%3Fq%3D%27%2B%28new%20Date%29.getTime%28%29%3Bdocument.getElementsByTagName%28%27head%27%29%5B0%5D.appendChild%28s%29%7Dvoid%280%29
if(typeof(iTransmogrify)=='undefined'){
var s=document.createElement('script');
s.src='http://itransmogrify.googlecode.com/files/iTransmogrify.js?q='+(new Date).getTime();
document.getElementsByTagName('head')[0].appendChild(s)
}void(0)

*/


// gdata is a placeholder to workaround a Google feed bug: http://code.google.com/p/gdata-issues/issues/detail?id=295

gdata = {
	io: {
		handleScriptLoaded:	function(data) {
			iTransmogrify.YTJSONhandler(data); // send raw data back to the main object. This is a workaround placeholder, treat it like one.
		}
	}
};


iTransmogrify = {
	jQueryURL: 'http://jqueryjs.googlecode.com/files/jquery-1.2.2.min.js',	// grab JQuery from Google Code
	jQueryVersion: '1.2.2', 
	joesInfoURL: 'http://itransmogrify.googlecode.com/',
	imageBaseURL: 'http://itransmogrify.googlecode.com/svn/trunk/images/',	// grab interface images from Google Code SVN

	YTregex: /(?:youtube.com\/v\/|youtube.com\/watch\?v=)([^ .?=&]{11})/, // returns YTids from http://www.youtube.com/v/TOpn32Gg88A and http://www.youtube.com/watch?v=TOpn32Gg88A urls
	YTinternalRegex: /(?:video_id=|watch\?v=)([^ .?=&]{11})/, // regex for extracting YTid from YouTube internal pages like bios, channels, etc
	mp3regex: /=((?:http|\/)[^&]*\.mp3)/,	// extracts full-path URLs ending in .mp3 from query strings used frequently in param flashvars
    DMregex: /http:\/\/www.dailymotion.com\/swf\/([\S]+)/, // grab DailyMotion url IDs from swf sources
	// imageBaseURL: 'http://joes-mbp.local:9009/images/',	// use local images
        
	init: function() {
		if (typeof jQuery == "undefined" || jQuery.prototype.jquery < this.jQueryVersion){	// jQuery is not loaded on the page yet or is an older version
			var thisParent = this;
			var s=document.createElement('script');
			var loaded = function() {
			    jQuery.noConflict();
			    thisParent.getObjectAndEmbeds();
		    };
			s.src=this.jQueryURL;
			s.onload = loaded;  // onload handler supported by Safari and Firefox
			s.onreadystatechange = function() { if (this.readyState == 'complete') { loaded() } }; // 'onload' handler for IE
			document.getElementsByTagName('head')[0].appendChild(s);
		} else {
			this.getObjectAndEmbeds()
		}
	},
	
	getObjectAndEmbeds: function(iframe) {
		// function returns an array of objects like {type:'type', jquery object, YTid/url}
		// supported types: youtube, mp3
		var YouTubeItems, mp3Tags;
		var thisParent = this;
        var foundObjects = [];

        if (iframe) var context = iframe.contents();


		// Standard YouTube items:
        YouTubeItems = jQuery("embed[src*='youtube.com']", context); // get standard YouTube embeds and UFO inserted Webkit bare-embeds
        YouTubeItems = YouTubeItems.add(jQuery("object[data*='youtube.com']", context)); // get Mozilla UFO bare objects
		
		
		// Viper Video Quicktags:  
        // http://www.viper007bond.com/wordpress-plugins/vipers-video-quicktags/
        // http://wordpress.org/extend/plugins/vipers-video-quicktags/
        jQuery('.vvqyoutube p', context).each( function() {
            var YTid;
            if ( YTid = thisParent.YTregex.exec( jQuery(this).html() ) ) {
                jQuery(this).css( {'width':425, "height": 350} );
                foundObjects.push( {
                    type: 'youtube',
                    jq: jQuery(this), 
                    YTid: YTid[1]
                })
            }
        })


        // YouTube originated pages:
        if ( window.location.toString().match( /http:\/\/(\w*\.)?youtube.com\// ) ) {
    
            // Grab embeds from YouTube bio pages
            YouTubeItems = YouTubeItems.add(jQuery('.profileEmbedVideo object param[value*="video_id"]', context)); 

            // if playerDiv exists, we're on a functioning page so go replace playerDiv's contents
            jQuery('#playerDiv', context).each( function() {    
                jQuery(this).empty().append('<div style="width:480px; height:396px;">iTransmogrifying</div>');   // set up a blank element for receiving our graphics
 
                foundObjects.push( {
                    type:'youtube',
                    jq: jQuery('#playerDiv div'),
                    YTid: thisParent.YTinternalRegex.exec( window.location.toString() )[1]
                })
            })
        }


 		YouTubeItems.each(function() {
 		    jQuery(this).children()
            foundObjects.push( {
                type: 'youtube',
                jq: function(item) {
                    if (!context)
                        return (jQuery(item).parent().is('object')) ? jQuery(item).parent() : jQuery(item);
                    }(this),
                YTid: thisParent.getYTid(this)
            });
        });	
          
           
    	// collect mp3 items:
		mp3Tags = jQuery("param[value*='.mp3']", context).filter( function() { return this.name.toLowerCase() == "flashvars"; });    // players using FlashVars
        mp3Tags = mp3Tags.add(jQuery("embed[flashvars*='.mp3']", context));
        mp3Tags = mp3Tags.add(jQuery("param[value*='.mp3']", context).filter( function() { return this.value.indexOf('mp3_file') > -1; }));  // for kink.fm
        
		mp3Tags.each(function() {
    		var mp3url;
		    if (mp3url = thisParent.getMP3url(this)) {
			    foundObjects.push( {
								type: 'mp3', 
                                jq: function(item) { 
                                        // figure out which DOM object to replace
                                        if (iframe && iframe.attr('id').indexOf('iTransmogrify_') == 0)   // this is a created iFrame
                                            return iframe;
                                            
                                        if( jQuery(item).parent().is('object') ) 
                                            return jQuery(item).parent();
                                            
                                        return jQuery(item);
                                    }(this),
								url: mp3url
								});
	        }
		});
        
        
        this.getSideLoadLinks(context)      // convert SideLoad playback links
        this.getDailyMotionLinks(context)      // convert DailyMotion links          
        this.getKinkFmLinks(context);      // convert kink.fm links in place

		// send results to convertObjectsToLinks to route to appropriate functions:
		this.convertObjectsToLinks(foundObjects);
        this.cleanup(foundObjects);
        
        // grab any remaining object/embed tags and convert them
        jQuery('object').each(function(){ thisParent.replaceUnsupported( jQuery(this) ) })
        jQuery('embed').each(function(){ thisParent.replaceUnsupported( jQuery(this) ) })
        
        // load the bookmarklet for every frame on the page:
        if(!iframe)
            this.loadInFrames();
	},
	
	
	loadInFrames: function() {
		var thisParent = this;
	    
	    // add iFrame to kink.fm pages:
	    // >>> $('a img[src*="play_button.gif"]').eq(0).parent().replaceWith('<iframe src="http://www.kink.fm/topic/play_window.php?audioId=1226580" height="126" name="iTransmogrify_1226580" id="iTransmogrify_1226580" />')
        if (iframes = jQuery('iframe')) {
            for (x = 0; x < iframes.length; x++) {
               try { this.getObjectAndEmbeds(iframes.eq(x)) }   // try prevents errors trying to read contents of frames pointing to different domains
               catch (err) { /* console.log(err) */ }
            }
        }
	},
	
	
	getDailyMotionLinks: function(context) {
        var thisParent = this;
        var interFrame;
        dailyMotionItems = jQuery("embed[src*='dailymotion.com/swf']", context); // get standard YouTube embeds and UFO inserted Webkit bare-embeds
        // dailyMotionItems = dailyMotionItems.add(jQuery("object[data*='dailymotion.com']", context)); // get Mozilla UFO bare objects
       
        dailyMotionItems.each(function() {
                      thisParent.convertObjectsToLinks( [ {
                          type: "dailymotion",
                          jq: jQuery(this).parent(),
                          DMid: thisParent.getDMid(this)
                      }]);
        thisParent.getDMtitles(thisParent.getDMid(this));
        });
	},
	
	
	getDMtitles: function(DMid) {
	   var thisParent = this;
	   var DMTitleURL = 'http://pipes.yahoo.com/joemaller/dmtitles?_render=json&DMid=' + DMid + '&_callback=?';
	   
	    jQuery.getJSON( DMTitleURL + '', function(json){
            var title = [];
            jQuery.each( json.value.items, function(item, i){ title.push (i.content) })
            thisParent.swapTitle(jQuery('#' + thisParent.nameCleaner(DMid) + ' .YTtitle'), title.join(' - '));
        });
	},	


    getSideLoadLinks: function(context) {
        var thisParent = this;
        // rather than doing all sorts of ninja sleector hackery, we're just going to replace their function. Hizzah!

        if (typeof(flashProxy) == 'undefined')  return false    // bail out if there are no sideload links
        flashProxy.call = function(blah, mp3url, mp3Title) {
            return false;
        }
        
        // javascript:flashProxy.call('loadExternalUrl','http://promo.beggars.com/us/mp3/blonderedhead_23.mp3','Blonde Redhead - 23');
        // we still need to convert the links so they're visible on iPhone
        
        // the stack idea is from http://fmarcia.info/jquery/stack/
        // referenced here: http://groups.google.com/group/jquery-en/browse_thread/thread/456709277ec26679/68dcabe65083212c?lnk=gst&q=each+delay#68dcabe65083212c
        
        var stack = {
			'delay': 50,
			'actions': [],
			'run': function() {
				if (stack.actions.length) {
					stack.actions.shift()();
					setTimeout(stack.run, stack.delay);
				}
			}
		};
		
        
        jQuery('a[href*=flashProxy]').each(function(){
            
            var mp3Parts = (/'\s*,\s*'(.*)'\s*,\s*'(.*)'\)/).exec(this.href);
            var newRow = jQuery(this).parent().parent().after('<tr height="36"><td colspan="99" ><p/></td></tr>').next().find('p')
            var button = [ {
                type: "mp3",
                jq: newRow,
                url: mp3Parts[1],
                title: unescape(mp3Parts[2])
            }];
            
            stack.actions.push(function(){
                thisParent.convertObjectsToLinks( button );
            })
        })
        stack.run();
    },
    
	
	getKinkFmLinks: function(context) {
   		var thisParent = this;
        var buttons = jQuery('a img[src*="play_button.gif"]', context).parent();
        var kinkRegex = /, ?(\d+)\)/;   // extract kink id from javascript links

        buttons.each( function() {

            if ( kinkPageID = kinkRegex.exec( jQuery(this).attr('href') ) )
                 kinkPageID = kinkPageID[1];

            thisParent.convertObjectsToLinks( [ {
                type: "mp3",
                jq: jQuery(this),
                url:kinkPageID
            }]);

            jQuery('#' + thisParent.nameCleaner(kinkPageID)).find('.YTtitle').html('Click to fetch mp3 address');
            jQuery('#' + thisParent.nameCleaner(kinkPageID)).click( function() {
    
                var kinkSource, kinkTitle;
                currentItem = this.id;

                thisParent.swapTitle(jQuery('#' + currentItem).find('.YTtitle'), 'fetching address...');   // Change title to "fetching..."

                var interFrame = jQuery('<iframe src="http://www.kink.fm/topic/play_window.php?audioId='+(this.id.substring(3))+'" width="25" height="25" style="position: absolute; width:25px; height: 25px; left: 1000px" name="iTransmogrify_' + currentItem + '" id="iTransmogrify_' + currentItem + '" />')
                interFrame.load(function() {
                    if ( kinkSource = thisParent.mp3regex.exec(jQuery('#iTransmogrify_' + currentItem).contents().find('embed').attr('src')) )
                         kinkSource = kinkSource[1];
            
                    if ( kinkTitle = (/ - (.*)$/).exec(jQuery('#iTransmogrify_' + currentItem).contents().find('title').text()) )
                         kinkTitle = kinkTitle[1];
 
                     jQuery('#iTransmogrify_' + currentItem).remove();
                     thisParent.swapTitle(jQuery('#' + currentItem).find('.YTtitle'), kinkTitle);   // swap out the title
                     jQuery('#' + currentItem).find('.YTlink').attr('href', kinkSource);    // point href of main link to the mp3
                     jQuery('#' + currentItem).unbind('click')      // remove previous click handler
                 })

                jQuery(this).before(interFrame)

                return false;
            })
        })
	},
	
	convertObjectsToLinks: function(foundObjects) {
		var thisParent = this;
		// this expects an array of objects from getObjectEmbeds, it sends each type to the appropriate function
		jQuery(foundObjects).each(function(){
			if (this.type=='youtube') thisParent.replaceLinks(this); 
			if (this.type=='mp3') thisParent.replaceLinks(this);
            if (this.type=='dailymotion') thisParent.replaceLinks(this);
		})
	},

	cleanup: function(foundObjects) {
			var thisParent = this;
			jQuery(foundObjects).each(function(){
                if (this.type == 'youtube') thisParent.getYTTitles(this.YTid);
                if (this.type == 'mp3') thisParent.getMP3titles(this.url);
			})
	},
		
	getYTTitles: function(YTid) {
		var thisParent = this;
		var gdataURL = "http://gdata.youtube.com/feeds/videos/" + YTid + "?alt=json-in-script";
		// can't use JQuery to insert these scripts because of a bug in Google's GData handling 
		// of single-item YouTube feeds, if there's a callback specified then Google spits back 
		// a bad result more info here: http://code.google.com/p/gdata-issues/issues/detail?id=295
		
		var s = document.createElement('script');
		s.src = gdataURL;
		s.id='script' + YTid; 	// for cleanup later on, also used to prevent double-inserted titles
		document.getElementsByTagName('head')[0].appendChild(s); // Gdata will callback to insertYTTitles() after loading the script
		
		// build a fake error handler
		// this will call the insertYTTitles after 2 seconds. The timer clears 
		// in the JSON handler so it will only call on bad script loads
		this['timer' + YTid ] =  setTimeout(function(){ thisParent.insertYTTitles(YTid) }, 4000);	// this is our fake error handler
	},
	
	
	
	YTJSONhandler: function(data) {
		if (YTid = this.YTregex.exec(data.entry.link[1].href)) {
			this[YTid[1]] = data.entry;	// store YT JSON info under the unique ID of the movie
			clearTimeout(this['timer' + YTid[1]])	// clear the timeout (the fake an error handler)
			this.insertYTTitles(YTid[1]);
		}
	},
	
	insertYTTitles: function(YTid) {
		if (!this[YTid]) {
			// movie info failed to load, no JSON data loaded
			var YTtitle = 'Video not found';
			var YTtime = '--:--';
		} else {
			if (this[YTid] && jQuery('#script' + YTid).length) {
				// JSON data loaded and script still exists
				var YTtitle = this[YTid].title.$t
				var YTtime = this[YTid].media$group.yt$duration.seconds;
				YTtime = parseInt(YTtime/60) + ':' + ((YTtime%60 < 10) ? '0' + YTtime%60 : YTtime%60);
			}
		}

        YTtitle = YTtitle + ' &nbsp; <span style="color:#888; font-family:Helvetica;">' + YTtime + '</span>';
		jQuery('#script' + YTid).remove(); // remove this specific JSON script

        this.swapTitle(jQuery('#' + this.nameCleaner(YTid) + ' .YTtitle'), YTtitle)
	},
	
	swapTitle: function(jq, title) {
	    if (title.length < 1) return false;
	    setTimeout(function(){
	        jq.animate({textIndent:"-" + jQuery(this).width() +"px"}, 300, function() {jQuery(this).html(title)}).animate({textIndent: 0}, 500)
		}, 250);
	},
    
	nameCleaner: function(oldName) {
	    // scrubs a string to make it usable as an id/class name
	    return 'iT_' + unescape(oldName).replace(/\W/g, "_");
	},
	
	
	getMP3titles: function(mp3url) {
        this.swapTitle(
            jQuery('#' + this.nameCleaner(mp3url.split('/').pop()) +' .YTtitle'), 
            unescape(mp3url.split('/').pop())
        )
	},
	
	
	getYTid: function(YTobject) {
		var YTid;
		if (YTid = this.YTregex.exec( YTobject.src )) return YTid[1];
		if (YTid = this.YTregex.exec( YTobject.data )) return YTid[1];
		if (YTid = this.YTinternalRegex.exec( jQuery(YTobject ).attr('flashvars'))) return YTid[1];
		if (YTid = this.YTinternalRegex.exec( YTobject.value )) return YTid[1];
		return false;
	},
	
	getDMid: function(DMobject) {
	   var DMid;
	   if (DMid = this.DMregex.exec( DMobject.src )) return DMid[1]
	},
	
	
	getMP3url: function(mp3object) {
		var mp3url;
        var urlCleaner = function(u) {
            if (u.indexOf('http://') == -1) {
                return window.location.protocol + '//' + window.location.hostname + u
            } else {
                return u;
            }
        }	

		if (mp3url = this.mp3regex.exec( mp3object.value) ) return urlCleaner( mp3url[1] );
		if (mp3url = this.mp3regex.exec( jQuery(mp3object).attr('flashvars')) ) return urlCleaner( mp3url[1] );   // for UFO inserted bare embeds
		return false;
	},
	
	
	getSizes: function(YT) {
	    // assign sizing values for YouTube rectangles
	    // sets the values into known properties of the passed YT object

        if (typeof(YT.w) == "undefined" ||  typeof(YT.h) == "undefined"){
            YT.w = YT.jq.width()
            YT.h = YT.jq.height()
        };

		YT.img.w = YT.w;
		YT.img.h = YT.h;

        if (YT.type == "youtube" || YT.type == "dailymotion") {
		    YT.img.h -= YT.bar.h;
		    
    		// 0.84 is the default proportion of the YouTube player when the width is <= 400 (400x300 + 36px for the controller)
    		if (YT.w < 400 || YT.h < 336) {
    			// controller will be less than 36px tall
    			if (YT.h/YT.w < 0.84) { 
    				YT.img.w = Math.round(YT.h/0.84);
    				YT.img.h = Math.round(YT.img.w * 0.75);
    			} else {
    				YT.img.h = Math.round(YT.w * 0.75);
    			}
    			YT.bar.h = Math.round(YT.img.w * 0.84 - YT.img.w * 0.75);
			
    		} else { 
    			// width greater than 400, controller will be 36px tall
    			if (YT.h/YT.w < (YT.w * 0.75 + 36)/YT.w) { 
    				YT.img.w = Math.round(YT.img.h/0.75);
    			} else {
                    YT.img.h = Math.round(YT.img.w * 0.75);
    			}	
    		}
    		
    		// these variables simplify output positioning
    		YT.img.left = ((YT.w - YT.img.w)/2); 
            YT.img.top = Math.ceil((YT.h - YT.img.h - YT.bar.h)/2);
            YT.bar.top = YT.img.top + YT.img.h;

        } else {
            if (YT.h < 36) YT.h = YT.img.h = 36;
            if (YT.w < YT.h * 3) YT.w = YT.img.w = YT.h * 3;
            
            YT.img.left = 0;
            YT.img.top = 0;
            YT.bar.top = 0;
        }
	},

	
	replaceLinks: function(YTitem) {			
		var YT = { img: {}, bar: {} };
		YT.type = YTitem.type
		YT.jq = YTitem.jq
		YT.title = YTitem.title
		
		YT.bar.h = 36; // default size, scales down if height is less than 36 (YT.img.w * 0.75 + 36)
		
		if (YT.type == "youtube") { 
		    YT.id = YTitem.YTid;
    		YT.url = 'http://www.youtube.com/watch?v=' + YT.id;
    		YT.img.url = 'http://img.youtube.com/vi/' + YT.id + '/0.jpg';
    		if ( window.location.toString().match( /http:\/\/(\w*\.)?youtube.com\// ) ) 
    		    YT.url = 'http://www.google.com/url?q=' + escape( YT.url );    // redirect to escape iPhone-YouTube jail 
    		    
    		YT.w = YT.jq.attr('width');
    		YT.h = YT.jq.attr('height');
	    }
	    if (YT.type == "dailymotion") {
	        YT.id = YTitem.DMid;
    		YT.url = 'http://iphone.dailymotion.com/video/' + YT.id;
    		YT.img.url = 'http://www.dailymotion.com/thumbnail/320x240/video/' + YT.id ;

    		YT.w = YT.jq.attr('width');
            // YT.h = YT.jq.attr('height');
    		
            // YT.w = 400
		    YT.h = YT.w * 0.75 + 36;
	    }
		if (YT.type == "mp3") {
		    YT.id = YTitem.url.split('/').pop();		    
		    YT.url = YTitem.url;
		    YT.w = YT.jq.parent().width();
    		YT.h = YT.jq.parent().height();
		}
        
        this.getSizes(YT);

		YT.div = '<div class="YTblock" id="' + this.nameCleaner(YT.id) + '" style="\
                    									 	     width: ' + YT.w +'px; \
                    										     height: ' + YT.h + 'px; \
                    										     display: inline-block;	\
                    										     position: relative; \
                    										     margin: 0;	\
                    										     padding: 0 0 0 0; \
                    										     text-align: center; \
                    										     line-height: 0;">';
														
		YT.link = '<a class="YTlink" href="' + YT.url + '" target="_new" style="\
                		                                                        background: transparent; \
                		                                                        text-decoration: none;">';
		
		YT.button = '<div class="YTbutton" style="\
												position: absolute; \
												width: ' + YT.img.w + 'px; \
												height: ' + YT.img.h + 'px; \
												left: ' + YT.img.left + 'px; \
												top:' + YT.img.top + 'px; \
												margin: 0; \
												padding: 0; \
												background: transparent url(' + this.imageBaseURL + 'play.png) no-repeat center center; " />';
												
		YT.img.tag = '<img src="' + YT.img.url + '" style="\
												position: absolute; \
												top: ' + YT.img.top + 'px; \
												left: ' + YT.img.left + 'px; \
												width: ' + YT.img.w + 'px; \
												height: ' + YT.img.h + 'px; \
												border:none; \
												margin: 0; \
												padding: 0;" />';
																					
		YTbottom = '<img class="YTbottom" src="' + this.imageBaseURL + 'bar.png" style="\
												position: absolute; \
												top: ' + YT.bar.top + 'px; \
												left: ' + YT.img.left + 'px; \
												height: ' + YT.bar.h + 'px; \
												width:' + YT.img.w + 'px; \
												border: none; \
												padding: 0; \
												margin: 0; \
												background: transparent;"/>';
												
		YTtitlediv = '<div class="YTtitle" style="\
												position: absolute; \
												left: ' + YT.img.left + 'px; \
												top: ' + YT.bar.top + 'px; \
												width: ' + (YT.img.w - YT.bar.h/2) + 'px; \
												padding: ' + Math.floor(YT.bar.h/4) + 'px; \
												margin: 0; \
												font: ' + (YT.bar.h * 0.5) + 'px helvetica; \
												text-align: left;  \
												line-height: ' + (YT.bar.h * 0.5) + 'px; \
												color: #ddd; \
												white-space: nowrap; \
												overflow: hidden;';
												
		if (YT.type == 'mp3') YTtitlediv += 'background: transparent url(' + this.imageBaseURL + 'music.png) no-repeat left center;\
		                                      width: ' + (YT.img.w - YT.bar.h/2 - 32) + 'px; \
		                                      padding-left: 32px;'									
		YTtitlediv += '">';

        if (YT.title) { 
            YTtitlediv += YT.title; 
        } else {
            if (YT.type == 'youtube')       YTtitlediv += 'Open in YouTube Viewer';
            if (YT.type == 'dailymotion')   YTtitlediv += 'View on DailyMotion';
            if (YT.type == 'mp3')           YTtitlediv += 'Listen to MP3';
        }
        
        YTtitlediv += '</div>';
												
		YTinfoLink = '<img src="' + this.imageBaseURL + 'fade.png" style="\
				                                position: absolute; \
												top: ' + YT.bar.top + 'px; \
												left: ' + (YT.img.left + YT.img.w - YT.bar.h * 2) + 'px; \
												height: ' + YT.bar.h + 'px; \
												width: ' + (YT.bar.h * 2) + 'px; \
												border: none; \
												padding: 0; \
												margin: 0; \
												background: transparent;" />\
		              <a class="YTinfoLink" href="' + this.joesInfoURL + '" target="_blank" style="\
												position: absolute; \
												top: ' + YT.bar.top + 'px; \
												text-decoration: none; \
												left: ' + (YT.img.left + YT.img.w - YT.bar.h) + 'px; \
												background: transparent; \
												border: none; \
    											padding: 0; \
												margin: 0; \
	                                            text-decoration: none;"> \
				      <img src="' + this.imageBaseURL + 'info.png" style="\
												width:' + YT.bar.h + 'px; \
												border: none; \
												background: transparent; \
												max-width: none; \
												margin:0; \
												padding:0;" /></a>';


        if (YT.type == 'youtube') 
            YT.newHTML = jQuery(YT.div + YT.link + YT.img.tag + YT.button + YTbottom + YTtitlediv + "</a>" + YTinfoLink + "</div>");
        if (YT.type == 'dailymotion') 
            YT.newHTML = jQuery(YT.div + YT.link + YT.img.tag + YT.button + YTbottom + YTtitlediv + "</a>" + YTinfoLink + "</div>");
        if (YT.type == 'mp3')    		
            YT.newHTML = jQuery(YT.div + YT.link + YTbottom + YTtitlediv + "</a>" + YTinfoLink + "</div>");
        YTitem.jq.replaceWith(YT.newHTML);
	},
	
	replaceUnsupported: function(jQ) {			
        var w, h, knownText, unsupportedText;
	    
	    w = jQ.width();
	    h = (jQ.height() < jQ.find('embed').height()) ? jQ.find('embed').height() : jQ.height()
	    
        if ( knownText = ( /motionbox.com.*id%3D([^%]+)%/ ).exec( jQ.attr('src') ) ) unsupportedText = '<strong><a href="http://www.motionbox.com/video/player/' + knownText[1] + '" target="_new">MotionBox video page</a></strong><br /> Motion Box does not yet offer iPod/iPhone compatible videos';
        if ( ( knownText = ( /viddler_([^_]+)_(.*)/ ).exec( jQ.attr('name') ) ) ||
             ( knownText = ( /viddler_([^_]+)_(.*)/ ).exec( jQ.attr('id') ) ) ) unsupportedText = '<strong><a href="http://www.viddler.com/explore/' + knownText[1] + '/videos/' + knownText[2] + '" target="_new">Viddler video page</a></strong><br /> Viddler does not yet offer iPod/iPhone compatible videos';
        if ( knownText = ( /vimeo.com\/.*clip_id=([0-9]+)&/).exec( jQ.attr('data') ) ) unsupportedText = '<strong><a href="http://www.vimeo.com/' + knownText[1] + '" target="_new">Vimeo video page</a></strong><br /> Vimeo does not yet offer iPod/iPhone compatible videos';
          
        if ( unsupportedText)
            jQ.replaceWith('<div style="background:#ccc; width:' + w + 'px; height:' + h + 'px; position: relative; font-family: Helvetica; font-size: 18pt; line-height: 1.5em; text-align: center;">'
                + '<div style="position: absolute; top: 33%; width: 90%; padding: 0 5%">'
                + unsupportedText
	            + '</div>'
	            + '</div>');
    }
}

iTransmogrify.init();

