Tuesday, September 25, 2012

Google Translator Tooltip


// ==UserScript==
// @name           Google Translator Tooltip
// @namespace      meh
// @description    Translates selected text into a tooltip.
// @include        http://*
// @require     http://code.jquery.com/jquery-1.7.2.min.js
// @require     http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js
// ==/UserScript==
const HREF_NO = 'javascript:void(0)';
const MAX_Z = 2147483640;
var imgLookup;
var txtSel; // text selected
var currentURL;
var languagesGoogle;
var timerWindowResize;
var initialized = false;
var COLOR_BG1, COLOR_BG2, COLOR_TEXT, COLOR_LINK;
var colorschemes = [
 
 {name:'Default', bg1:'#FFFF77', bg2:'#FFFFAA', link:'#0000FF', text:'#333333'},
 {name:'Dark', bg1:'#333', bg2:'#555', link:'#ddd', text:'#eee'},
 
 // http://www.colorschemer.com/schemes/viewscheme.php?id=9456
 {name:'Dark green', bg1:'#284030', bg2:'#5D7350', link:'#FAFCB6', text:'#E2F0A8'},
 
 //http://www.colorschemer.com/schemes/viewscheme.php?id=315
 {name:'Dark blue', bg1:'#2D4358', bg2:'#3A5065', link:'#b5cce3', text:'#b5cce3'}, 
 
 //http://www.colorschemer.com/schemes/viewscheme.php?id=9603
 {name:'Dark red', bg1:'#751310', bg2:'#9C1B19', link:'#FAEFE0', text:'#FAEFE0'},//DEB990
 
 //http://www.colorschemer.com/schemes/viewscheme.php?id=158
 {name:'Light green', bg1:'#4F724F', bg2:'#649064', link:'#EDF8ED', text:'#EDF8ED'}, 
 
 //http://www.colorschemer.com/schemes/viewscheme.php?id=158
 {name:'Light blue', bg1:'#4D6680', bg2:'#647A90', link:'#EDF2F8', text:'#EDF2F8'}
]

//setup events
document.addEventListener('mouseup', showLookupIcon, false);
document.addEventListener('mousedown', mousedownCleaning, false);
window.addEventListener('resize', windowResizeHandler, false);

function mousedownCleaning(evt){

 var divDic = getId('divDic');
 var divLookup = getId('divLookup');
 
 if(divDic)
 {
  if(!clickedInsideID(evt.target,'divDic')){
   divDic.parentNode.removeChild(divDic);
  }
 } 
 
 if(divLookup)
  divLookup.parentNode.removeChild(divLookup);
}


function showLookupIcon(evt){
 
 if(evt.ctrlKey && evt.altKey && (!GM_getValue('ctrl') || !GM_getValue('alt')))
  return;
 //XOR http://www.howtocreate.co.uk/xor.html
 if(evt.ctrlKey ? !GM_getValue('ctrl') : GM_getValue('ctrl'))
  return;
 if(evt.altKey ? !GM_getValue('alt') : GM_getValue('alt'))
  return;  
 

 var divDic = getId('divDic');
 var divLookup = getId('divLookup');
 txtSel = getSelection(evt);
 
 //exit if no text is selected
 if(!txtSel || txtSel=="")
 {
  if(divDic)
  {
   if(!clickedInsideID(evt.target,'divDic')){
    divDic.parentNode.removeChild(divDic);
    deselect();
   }
  }
  if(divLookup)
   divLookup.parentNode.removeChild(divLookup);
  
  return;
 }


 //possible cleanup
 if(divDic)
 {
  if(!clickedInsideID(evt.target,'divDic')){
   divDic.parentNode.removeChild(divDic);
   deselect();
  }
  
  return;
 }

 
 //remove div if exists
 if(divLookup)
 {
  divLookup.parentNode.removeChild(divLookup);
 } 
 
 
 if(!initialized){
  initialized = true;
  images();
  if( GM_getValue('opt_youtube') == undefined ){
   GM_setValue('opt_youtube',true)
   GM_setValue('opt_youtube_auto',true)
   GM_setValue('opt_compare',true)
  }
 }
 css(true); 
 
 
 //div container
 divLookup = createElement('div', {id: 'divLookup', style: 'top:'+(evt.clientY+window.pageYOffset+10)+'px; left:'+(evt.clientX + window.pageXOffset + 10) + 'px;'});
 divLookup.appendChild(imgLookup.cloneNode(false));
 divLookup.addEventListener('mouseover', lookup, false);
 document.body.appendChild(divLookup); 
 if(GM_getValue('opt_shadow')==true)
  $(divLookup).addClass('classShadowww') 
 
 repositionNode($('#divLookup'));
}




function lookup(evt){

 var divResult = null;
 var divDic = getId('divDic');
 var divLookup = getId('divLookup');
 var top = divLookup.style.top;
 var left = divLookup.style.left;


 //no text selected
 if(!txtSel || txtSel==""){
  if(divDic = getId('divDic'))
   divDic.parentNode.removeChild(divDic);
  return;
 }
 
 
 //cleanup divs
 if(divDic = getId('divDic'))
 {
  divDic.parentNode.removeChild(divDic);
 } 
 divLookup.parentNode.removeChild(divLookup);
 
 
 //div container
 divDic = createElement('div', {id:'divDic'});
 divDic.style.top = top;
 divDic.style.left = left;
 divDic.addEventListener('mousedown', dragHandler, false);
 document.body.appendChild(divDic);
 if(GM_getValue('opt_shadow')==true)
  $(divDic).addClass('classShadowww')

 
 //div result
 divResult = createElement('div', {id:'divResult'}, null, 'Loading...');
 divDic.appendChild(divResult); 
 

 //options link
 divDic.appendChild(createElement('span', {id:'optionsLink', title:'options', href:HREF_NO}, 'click toggleOptions false', '>>'));

 //lookup
 if( txtSel.search(/^\s*https?:\/\//) > -1 ) 
 {
  divResult.innerHTML = '<a class="gootranslink" href="'+txtSel+'" target="_blank" >'+txtSel+'</a>';
  if(GM_getValue('opt_youtube') && isYoutubeLink(txtSel) )
   return;  
 }
 else if( txtSel.search(/^\s*\S+(\.\S+)+/) > -1 ) // site.dom
 {
  divResult.innerHTML = '<a class="gootranslink" href="http://'+txtSel+'" target="_blank" >'+txtSel+'</a>';
  if(GM_getValue('opt_youtube') && isYoutubeLink(txtSel) )
   return;
 }
 else 
 {
  var sl, tl, lang;
  sl = GM_getValue('from') ? GM_getValue('from') : "auto";
  tl = GM_getValue('to') ? GM_getValue('to') : "auto";
  lang = sl + "|" + tl;
  currentURL = "http://www.google.com/translate_t?text=" + txtSel + "&langpair=" + lang;
  GM_xmlhttpRequest({
   method: 'GET',
   url: currentURL,
   onload: function(resp) {
    try{
     extractResultFrames(resp);
    }catch(e){
     GM_log(e);
    }
   }
  }); 
 }
 
 repositionNode($('#divDic'));
 
 //store query as attribute
 getId('divDic').setAttribute('query', txtSel);
 
 //other searches
 divDic.appendChild(createElement('span',{id:'spanOtherSearches', title:'search other sites'},'mouseover otherSites false','+')); 
}

function quickLookup(){

 getId('divResult').innerHTML = 'Loading...'
 currentURL = "http://www.google.com/translate_t?text=" + $('#divDic').attr('query') + "&langpair=" + getId('optSelLangFrom').value + "|" + getId('optSelLangTo').value;
 
 GM_xmlhttpRequest({
  method: 'GET',
  url: currentURL,
  onload: function(resp) {
   try{
    extractResultFrames(resp);
   }catch(e){
    GM_log(e);
   }
  }
 }); 
}


function otherSites(evt){

 var ul, li, query = getId('divDic').getAttribute('query').replace(/\s+$/,'').replace(/^\s+/,'');

 var sites = [
 
  {name:'Google', href:'http://www.google.com/search?q='+query.replace(/\s+/g,'+')},
  
  {name:'Google Images', href:'http://www.google.com/images?q='+query.replace(/\s+/g,'+')},
  
  {name:'The Free Dictionary', href:'http://www.thefreedictionary.com/'+query.replace(/\s+/g,'+')},
  
  {name:'Urban Dictionary', href:'http://www.urbandictionary.com/define.php?term='+query.replace(/\s+/g,'+')},
  
  {name:'Linguee', href:'http://www.linguee.com/search?query='+query.replace(/\s+/g,'+')},
  
  {name:'Wikipedia', href:'http://www.wikipedia.org/w/index.php?title=Special%3ASearch&search='+query.replace(/\s+/g,'+')},
  
  {name:'IMDb', href:'http://www.imdb.com/find?s=all&q='+query.replace(/\s+/g,'+')},
  
  {name:'Youtube', href:'http://www.youtube.com/results?search_query='+query.replace(/\s+/g,'+')}

 ];
 
 getId('divDic').appendChild(createElement('br'));
 getId('divDic').appendChild(document.createTextNode('Search "'+(query.match(/^[\s\S]{15}/) ? query.match(/^[\s\S]{15}/)[0]+'...' : query.match(/^[\s\S]+/)[0] )+'" at:'));
 ul = getId('divDic').appendChild(createElement('ul'));
 
 for(var i=0; i<sites.length; i++){
  li = ul.appendChild(createElement('li'));
  li.appendChild(createElement('a', {class:'gootranslink', target:'_blank', href:sites[i].href}, null, sites[i].name));
 }
 
 evt.target.parentNode.removeChild(evt.target);
 
 repositionNode($('#divDic'));
}


function extractResultFrames(resp){ 

 //select body and remove some tags
 var html = resp.responseText.match(/\<body[^\>]*\>([\s\S]+)\<\/body\>/)[1];
 html = html.replace(/\<script[^\<]+\<\/script\>/ig, '');
 html = html.replace(/\<iframe[^\<]+\<\/iframe\>/ig, '');
 
 //append requested page as hidden iframe
 var iframe = document.body.appendChild(createElement('iframe', {style:'visibility:hidden;'})); 
 var divExtract = iframe.contentWindow.document.body.appendChild(createElement('div', {id:'divExtract'}, null, html));
 divExtract = document.importNode(divExtract, true);
 iframe.parentNode.removeChild(iframe);
 
 //adjust link(s)
 var arrs = getTag('a',divExtract);
 for(var i=0; i<arrs.length; i++){
  arrs[i].setAttribute('target','_blank');
  arrs[i].setAttribute('class','gootranslink');
 }
 
 //gather info
 var translation = trim( xp('.//span[@id="result_box"]', divExtract)[0].textContent );
 var dict = xp('.//div[@id="gt-res-dict"]', divExtract)[0];
 if(dict){
  try{
   dict.removeChild(getTag('h3',dict)[0]);
   dict = dict.innerHTML;
  }catch(e){
   dict = null;
  }
 } 
 
 //parse info
 getId('divResult').innerHTML = '<a class="gootranslink" href="'+currentURL+'" target="_blank">' 
  + translation 
  + '</a>'
  + '<div id="divCompareee" ' + (GM_getValue('opt_compare')==true ? '' : 'style="display:none;"') + '>' + $('#divDic').attr('query') + '</div>';
 if(dict)
 {
  getId('divResult').innerHTML += '<br><br><div id="dict">'+dict+'</div>';
 }
 
 repositionNode($('#divDic'));
}

function repositionNode(node){
 //reposition div if out of bounds
 var pos = node.offset();
 if(pos==null)
  return;
 var w = node.width();
 var h = node.height();
 if(pos.left + w > window.innerWidth+window.pageXOffset){
  node.css('left', window.innerWidth+window.pageXOffset - w - 25);
 }
 if(pos.top + h > window.innerHeight+window.pageYOffset){
  node.css('top', window.innerHeight+window.pageYOffset - h - 25);
 }
}

function repositionNodeFixed(node,pad){
 //reposition fixed node if out of window
 var pos = node.offset();
 if(pos==null)
  return;
 var w = node.width();
 var h = node.height();
 if(pos.left + w > window.innerWidth+window.pageXOffset){
  node.css('left', window.innerWidth- w - (pad?pad:25));
 }
 if(pos.top + h > window.innerHeight+window.pageYOffset){
  node.css('top', window.innerHeight - h - (pad?pad:25));
 }
}

function trim(str){
 return str.replace(/^\s+/,'').replace(/\s+$/,'');
}


function getSelection(evt){

 var txt = null;
 //get selected text
 if(evt && evt.target.nodeName=='TEXTAREA')
 {
   //var begin = evt.target.value.substr(0, evt.target.selectionStart); 
   txt = evt.target.value.substr(evt.target.selectionStart, evt.target.selectionEnd - evt.target.selectionStart); 
   //var end = evt.target.value.substr(evt.target.selectionEnd); 
   //myArea.value = begin + text1 + selection + text2 + end;   
 }
 else if (window.getSelection)
 {
  txt = window.getSelection();
 }
 else if (document.getSelection)
 {
  txt = document.getSelection();
 }
 else if (document.selection)
 {
  txt = document.selection.createRange().text;
 }
 
 try{
  return txt.toString();
 }catch(e){
  return txt;
 }
}

//http://stackoverflow.com/questions/6186844/clear-a-selection-in-firefox/6187098#6187098
function deselect(){
 try{ 
  window.getSelection().removeAllRanges()
 }catch(e){
  document.selection.empty()
 }
}


function isYoutubeLink(txt){
 var id, time=null;
 if(txt.search(/youtube\.com\/watch\?/) > -1)
  id = txt.match(/[\?\&]v\=([^\&]+)/)[1]
 else if(txt.search(/youtu.be\//) > -1)
  id = txt.match(/youtu.be\/([^\?]+)/)[1]
 else if(txt.search(/youtube\.com\/v\/[^\?]+/) > -1) //embed url
  id = txt.match(/youtube\.com\/v\/([^\?]+)/)[1]
 else
  return false;
 
 //if skip to timestamp
 try{ 
  time = txt.match(/[\?\&\#](t\=[^\&]+)/)[1];
 }catch(e){
  time = null;
 }
 if(time!=null){
  //convert to seconds for parameter "start"
  var h, m, s;
  try{ h = parseInt(time.match(/(\d+)h/)[1]); }catch(e){ h = 0; }
  try{ m = parseInt(time.match(/(\d+)m/)[1]); }catch(e){ m = 0; }
  try{ s = parseInt(time.match(/(\d+)s/)[1]); }catch(e){ s = 0; }
  time = s + (m*60) + (h*60*60);
 }else{
  //if embed url ( http://www.youtube.com/v/vIdEoIddD?fs=1&autoplay=1&start=34 )
  if(txt.search(/[\?\&]start\=\d+/) > -1)
   time = txt.match(/start\=(\d+)/)[1];
 }
  
 //clear selection
 deselect(); 
  
 //check if video is already opened
 if( $('.classDivYoutubeeee[ytvid="'+id+'"]').length > 0 ){
  var div = $('.classDivYoutubeeee[ytvid="'+id+'"]:first');
  if(div.hasClass('classYoutubeMinimizeddd')){
   toggleYoutubeSize({target: div.find('.classtoggleSize:first').get(0)})
  }
  div.effect('shake',{times:2})
  //remove lookup icon, div dict
  $('#divDic,#divLookup').remove()
  return true;
 }

 // create video div
 var auto = GM_getValue('opt_youtube')==true && GM_getValue('opt_youtube_auto')==true ? 1 : 0;
 var url = 'http://www.youtube.com/v/' + id + '?fs=1&autoplay=' + auto + ( time!=null ? '&start='+time : '');
 var pos = $('#divDic').offset();
 var div = $('<div>')
  .attr('ytvid',id)
  .addClass('classDivYoutubeeee')
  .css({backgroundColor:COLOR_BG1, position:'fixed', top:Math.abs(window.pageYOffset-pos.top), left:Math.abs(window.pageXOffset-pos.left), zIndex:MAX_Z, padding:'0px 26px', borderRadius:'5px'})
  .appendTo(document.body)
  .append(
   $('<span title="close">').css({float:'right', cursor:'pointer',color:COLOR_LINK, marginLeft:7}).append('\u24E7').click(function(evt){
    $(this).parents('.classDivYoutubeeee:first').remove();
   })
  )
  .append(
   $('<span class="classtoggleSize" title="toggle size">').css({float:'right', cursor:'pointer',color:COLOR_LINK, marginLeft:7}).append('\u21F2').click(toggleYoutubeSize)
  ) 
  .append('<br><object><param name="movie" value="'+url+'"</param><param name="allowFullScreen" value="true"></param><embed src="'+url+'"  type="application/x-shockwave-flash"  allowfullscreen="true"  width="425" height="344"></embed></object><br><br>')
  .draggable()
  
 //add shadow
 if(GM_getValue('opt_shadow')==true)
  div.addClass('classShadowww')
  
 //position
 repositionNodeFixed(div);
 
 //remove lookup icon, div dict
 $('#divDic,#divLookup').remove()

 return true;
}


function toggleYoutubeSize(evt){
 
 var div = $(evt.target).parents('.classDivYoutubeeee:first');
 var ytlink = div.find('a[href*="youtube.com"]');
 var pos = div.offset();

 if(!div.hasClass('classYoutubeMinimizeddd')){ // minimize
  
  ytlink.hide();
  div.addClass('classYoutubeMinimizeddd');
  
  //backup div position
  div.attr({prevlefttt: Math.abs(window.pageXOffset - pos.left), prevtoppp: Math.abs(window.pageYOffset - pos.top)})
  
  //resize div
  div.find('embed').attr({width:'212.5', height:'172'})
  
  //position div
  div.css({top:window.innerHeight-div.outerHeight()-7, left:window.innerWidth-div.outerWidth()-13})
  if($('.classYoutubeMinimizeddd').length > 1){//distribute minimized divs
   var len = $('.classYoutubeMinimizeddd').length;
   var top = div.offset().top;
   var left = div.offset().left;
   left -= (div.outerWidth()+7) * (len-1);
   if(left < 0){
    left = div.offset().left;
   }
   div.css({left:left})
  }
  
  //change icon to maximize
  evt.target.innerHTML = '\u21F1';
 
 }else{ // restore
 
  ytlink.show();
  div.removeClass('classYoutubeMinimizeddd');
  
  //restore div position
  div.css({top:div.attr('prevtoppp')+'px', left:div.attr('prevlefttt')+'px'})
  
  //restore div size
  div.find('embed').attr({width:'425', height:'344'})
  
  //set minimize icon
  evt.target.innerHTML = '\u21F2';
 }
}


function windowResizeHandler(evt){
 clearTimeout(timerWindowResize);
 timerWindowResize = setTimeout(windowResized,333);
}

function windowResized(evt){
 if($('#divDic,.classDivYoutubeeee').length==0)
  return;
 
 if($('#divDic').length > 0)
  repositionNodeFixed($('#divDic'));
 
 if($('.classDivYoutubeeee').length > 0){
  var vids = $('.classDivYoutubeeee');
  for(var i=0; i<vids.length; i++)
   repositionNodeFixed(vids.eq(i),35);
 }
}

function toggleOptions(evt){

 if(!languagesGoogle){
  languagesGoogle = '<option value="auto">Detect language</option><option  value="sq">Albanian</option><option  value="ar">Arabic</option><option  value="bg">Bulgarian</option><option  value="ca">Catalan</option><option  value="zh-TW">Chinese_TC</option><option  value="zh-CN">Chinese</option><option  value="hr">Croatian</option><option  value="cs">Czech</option><option  value="da">Danish</option><option  value="nl">Dutch</option><option  value="en">English</option><option  value="et">Estonian</option><option  value="tl">Filipino</option><option  value="fi">Finnish</option><option  value="fr">French</option><option  value="gl">Galician</option><option  value="de">German</option><option  value="el">Greek</option><option  value="iw">Hebrew</option><option  value="hi">Hindi</option><option  value="hu">Hungarian</option><option  value="id">Indonesian</option><option  value="it">Italian</option><option  value="ja">Japanese</option><option  value="ko">Korean</option><option  value="lv">Latvian</option><option  value="lt">Lithuanian</option><option  value="mt">Maltese</option><option  value="no">Norwegian</option><option  value="pl">Polish</option><option  value="pt">Portuguese</option><option  value="ro">Romanian</option><option  value="ru">Russian</option><option  value="sr">Serbian</option><option  value="sk">Slovak</option><option  value="sl">Slovenian</option><option value="es">Spanish</option><option  value="sv">Swedish</option><option  value="th">Thai</option><option  value="tr">Turkish</option><option  value="uk">Ukrainian</option><option  value="vi">Vietnamese</option>';
 }
 var divOptions = getId('divOpt');
 
 if(!divOptions)//show options
 {
  divOptions = createElement('div', {id:'divOpt'});
  getId('divDic').appendChild(divOptions);
  getId('optionsLink').style.visibility = 'hidden';

  
  //from
  divOptions.appendChild(createElement('span', null, null,'From:'));
  divOptions.appendChild(createElement('select', {id:'optSelLangFrom'}, null, languagesGoogle));
  getId('optSelLangFrom').value = GM_getValue('from') ? GM_getValue('from') : "auto";
  getId('optSelLangFrom').addEventListener('change', quickLookup, false);
  
  //to
  divOptions.appendChild(createElement('span', null, null,' To:'));
  divOptions.appendChild(createElement('select', {id:'optSelLangTo'}, null, languagesGoogle));
  getId('optSelLangTo').value = GM_getValue('to') ? GM_getValue('to') : "auto";
  getId('optSelLangTo').addEventListener('change', quickLookup, false);
  
  //use ctrl 
  divOptions.appendChild(createElement('br'));
  divOptions.appendChild(createElement('br'));
  divOptions.appendChild(createElement('input', {id:'checkCtrl', type:'checkbox'}));
  divOptions.appendChild(createElement('span', null, null,'Use Ctrl key'));
  getId('checkCtrl').checked = GM_getValue('ctrl');

  //use alt 
  divOptions.appendChild(createElement('br'));
  divOptions.appendChild(createElement('input', {id:'checkAlt', type:'checkbox'}));
  divOptions.appendChild(createElement('span', null, null,'Use Alt key'));
  getId('checkAlt').checked = GM_getValue('alt');

  //Compare 
  divOptions.appendChild(createElement('br'));
  divOptions.appendChild(createElement('input', {id:'checkCompare', type:'checkbox'}));
  divOptions.appendChild(createElement('span', null, null,'Compare translation to original'));
  getId('checkCompare').checked = GM_getValue('opt_compare');
  $('#checkCompare').click(function(evt){
   if(this.checked){
    $('#divCompareee').show()
   }else{
    $('#divCompareee').hide()
   }
  })
  
  //box shadow
  divOptions.appendChild(createElement('br'));
  divOptions.appendChild(createElement('input', {id:'checkShadowww', type:'checkbox'}));
  divOptions.appendChild(createElement('span', null, null,'Show box shadow'));
  getId('checkShadowww').checked = GM_getValue('opt_shadow');
  $('#checkShadowww').click(function(evt){
   if(this.checked){
    $('#divDic').addClass('classShadowww')
   }else{
    $('.classShadowww').removeClass('classShadowww')
   }
  })
  
  //youtube
  divOptions.appendChild(createElement('br'));
  divOptions.appendChild(createElement('input', {id:'checkYoutubeee', type:'checkbox'}));
  divOptions.appendChild(createElement('span', null, null,'Preview Youtube links'));
  getId('checkYoutubeee').checked = GM_getValue('opt_youtube');
  $(divOptions).append(
   $('<div id="divOptYoutubeee">')
    .css({display: GM_getValue('opt_youtube')==true?'block':'none'})
    //.append('<br>')
    .append('&nbsp;&nbsp;&nbsp;&nbsp;<input id="checkYoutubeAutoplayyy" type="checkbox">')
    .append('autoplay video')
  )
  getId('checkYoutubeAutoplayyy').checked = GM_getValue('opt_youtube_auto');
  $('#checkYoutubeee').click(function(evt){
   if(this.checked){
    $('#divOptYoutubeee').show()
   }else{
    $('#divOptYoutubeee').hide()
   }
  })  
  
  //colors
  $(divOptions).append(
   '<br>'
   +'<table id="tablecolorrr">'
    +'<tr><td>Color schemes:</td><td colspan=2><select id="selectColorSchemesss"><option value=""></option></select> <a class="gootranslink" id="spanNewColorSchemeee" statusss="hidden" href="'+HREF_NO+'">customize</span> </td></tr>'
    +'<tr style="display:none;"> <td>Background 1:</td> <td><input type="text" size="10" id="inputbgcolor111" value="'+COLOR_BG1+'" /></td> <td><input class="simplecolorrr" id="bgcolor111" value="'+COLOR_BG1+'" /></td> </tr>'
    +'<tr style="display:none;"><td>Background 2:</td> <td><input type="text" size="10" id="inputbgcolor222" value="'+COLOR_BG2+'" /></td> <td><input class="simplecolorrr" id="bgcolor222" value="'+COLOR_BG2+'" /></td> </tr>'
    +'<tr style="display:none;"><td>Text:</td> <td><input type="text" size="10" id="inputtxttt" value="'+COLOR_TEXT+'" /></td> <td><input class="simplecolorrr" id="textcolorrr" value="'+COLOR_TEXT+'" /></td></tr>'
    +'<tr style="display:none;"><td>Link:</td> <td><input type="text" size="10" id="inputlinkkk" value="'+COLOR_LINK+'" /></td> <td><input class="simplecolorrr" id="linkcolorrr" value="'+COLOR_LINK+'" /></td></tr>'
   +'</table>'
  )
  $('.simplecolorrr').simpleColor({boxWidth:'0px', boxHeight:'0px', buttonClass:'classButtonColorrr'});
  $('#bgcolor111, #bgcolor222, #linkcolorrr, #textcolorrr').change(optColorPickerChanged);
  $('#inputbgcolor111, #inputbgcolor222, #inputlinkkk, #inputtxttt').keyup(optColorInputChanged);
  for(var i=0; i<colorschemes.length; i++){
   $('#selectColorSchemesss').append('<option value="'+colorschemes[i].name+'">'+colorschemes[i].name+'</option>')
  }
  $('#selectColorSchemesss').change(changeColorScheme)
  $('#spanNewColorSchemeee').click(function(evt){
   if($('#spanNewColorSchemeee').attr('statusss')=='hidden'){
    $('#tablecolorrr tr:not(:first-child)').show();
    $('#spanNewColorSchemeee').attr('statusss','visible');
   }else{
    $('#tablecolorrr tr:not(:first-child)').hide();
    $('#spanNewColorSchemeee').attr('statusss','hidden');
   }
  })
  
  
  //save
  divOptions.appendChild(createElement('br'));
  divOptions.appendChild(createElement('a', {href:HREF_NO, class:"gootranslink"}, 'click saveOptions false', 'save'));
  
  //cancel
  divOptions.appendChild(createElement('span', null, null,'&nbsp;'));
  divOptions.appendChild(createElement('a', {href:HREF_NO, class:"gootranslink"}, 'click toggleOptions false', 'cancel'));
  
  repositionNode($('#divDic'));
  
 }
 else//cancel options
 {
  divOptions.parentNode.removeChild(divOptions);
  getId('optionsLink').style.visibility = 'visible';
  css(true)
 }
}

function changeColorScheme(evt){
 var name = this.value;
 if(name=='')
  return;
 var sch = getColorSchemeByName(name);
 if(sch == null){
  return;
 }
 COLOR_BG1 = sch.bg1;
 COLOR_BG2 = sch.bg2;
 COLOR_TEXT = sch.text;
 COLOR_LINK = sch.link;
 css();
 $('#inputbgcolor111').val(COLOR_BG1)
 $('#inputbgcolor222').val(COLOR_BG2)
 $('#inputtxttt').val(COLOR_TEXT)
 $('#inputlinkkk').val(COLOR_LINK)
}

function getColorSchemeByName(name){
 for(var i=0; i<colorschemes.length; i++){
  if(name == colorschemes[i].name)
   return colorschemes[i];
 }
 return null;
}

function optColorInputChanged(evt){ 
 var id, color = evt.target.value;
 
 // http://networking.mydesigntool.com/viewtopic.php?tid=415&id=31
 if(!isColorValid(color)){
  return;
 }
 if(color.charAt(0)!='#'){
  color = '#'+color;
 }
 
 id = evt.target.getAttribute('id');  
 
 if(id=='inputbgcolor111'){
  COLOR_BG1 = color;
  css();
 }else if(id=='inputbgcolor222'){
  COLOR_BG2 = color;
  css(); 
 }else if(id=='inputtxttt'){
  COLOR_TEXT = color;
  css(); 
 }else if(id=='inputlinkkk'){
  COLOR_LINK = color;
  css(); 
 } 
}

function isColorValid(color){
 return (color.search(/^(#)?([0-9a-fA-F]{3})([0-9a-fA-F]{3})?$/) == 0);
}

function optColorPickerChanged(evt){ 
 var color = evt.target.value;
 var id = evt.target.getAttribute('id');
 if(id=='bgcolor111'){
  COLOR_BG1 = color;
  $('#inputbgcolor111').val(color)
  css();
 }else if(id=='bgcolor222'){
  COLOR_BG2 = color;
  $('#inputbgcolor222').val(color)
  css(); 
 }else if(id=='textcolorrr'){
  COLOR_TEXT = color;
  $('#inputtxttt').val(color)
  css(); 
 }else if(id=='linkcolorrr'){
  COLOR_LINK = color;
  $('#inputlinkkk').val(color)
  css(); 
 }
}

function saveOptions(evt){

 var from = getId('optSelLangFrom').value;
 var to = getId('optSelLangTo').value;
 var ctrl = getId('checkCtrl').checked;
 var alt = getId('checkAlt').checked;
 var compare = getId('checkCompare').checked;
 var shadow = getId('checkShadowww').checked;
 var yt = getId('checkYoutubeee').checked;
 var ytauto = getId('checkYoutubeAutoplayyy').checked;
 
 GM_setValue('from', from);
 GM_setValue('to', to);
 GM_setValue('ctrl', ctrl);
 GM_setValue('alt', alt);
 GM_setValue('opt_compare', compare);
 GM_setValue('opt_shadow', shadow); 
 GM_setValue('opt_youtube', yt);
 GM_setValue('opt_youtube_auto', ytauto);
 
 //colors
 if(!isColorValid($('#inputbgcolor111').val())){
  $('#inputbgcolor111').effect('pulsate');
  return;
 }
 if(!isColorValid($('#inputbgcolor222').val())){
  $('#inputbgcolor222').effect('pulsate');
  return;
 }
 if(!isColorValid($('#inputtxttt').val())){
  $('#inputtxttt').effect('pulsate');
  return;
 }
 if(!isColorValid($('#inputlinkkk').val())){
  $('#inputlinkkk').effect('pulsate');
  return;
 } 
 GM_setValue('opt_color_bg1', $('#inputbgcolor111').val() )
 GM_setValue('opt_color_bg2', $('#inputbgcolor222').val() )
 GM_setValue('opt_color_text', $('#inputtxttt').val() )
 GM_setValue('opt_color_link', $('#inputlinkkk').val() )
 
 css(true) 
 
 getId('divDic').removeChild(getId('divOpt'));
 getId('optionsLink').style.visibility = 'visible';
}





function css(init){

 $('#css_googletranslatortooltip').remove();

 if(init==true){
  COLOR_BG1 = GM_getValue('opt_color_bg1') != undefined ? GM_getValue('opt_color_bg1') : '#FFFF77' ;
  COLOR_BG2 = GM_getValue('opt_color_bg2') != undefined ? GM_getValue('opt_color_bg2') : '#FFFFAA';
  COLOR_TEXT = GM_getValue('opt_color_text') != undefined ? GM_getValue('opt_color_text') : '#333333';
  COLOR_LINK = GM_getValue('opt_color_link') != undefined ? GM_getValue('opt_color_link') : '#0000FF';
  if(GM_getValue('opt_shadow')==true)
   $('#divDic,#divLookup').removeClass('classShadowww').addClass('classShadowww')
  else
   $('.classShadowww').removeClass('classShadowww')
 }
 
 var style = createElement('style', {id:'css_googletranslatortooltip', type:"text/css"}, null, ''
 
  +'a.gootranslink:link {color: '+COLOR_LINK+' !important; text-decoration: underline !important;}'    
  +'a.gootranslink:visited {color: '+COLOR_LINK+' !important; text-decoration: underline !important;}'
  +'a.gootranslink:hover {color: '+COLOR_LINK+' !important; text-decoration: underline !important;}'  
  +'a.gootranslink:active {color: '+COLOR_LINK+' !important; text-decoration: underline !important;}' 
  
  +'#divLookup { background:none !important; color:'+COLOR_TEXT+' !important; position:absolute; z-index:'+MAX_Z+'; border:none !important;}'
  +'#divLookup img { border:2px solid '+COLOR_BG1+' !important;}'
  
  +'#divDic { background-color:'+COLOR_BG1+' !important; color:'+COLOR_TEXT+' !important; position:absolute; min-width:250px; min-height:50px; max-width:50%; padding:5px; font-size:small; text-align:left; z-index:'+MAX_Z+'; border-radius:3px; line-height:1 !important; border:none !important; }'
  
  +'#divResult {overflow:auto; padding:3px !important; background-color:'+COLOR_BG1+' !important; color:'+COLOR_TEXT+' !important; border:none !important; margin:0 !important; padding:0 !important; line-height:1 !important;}'
  
  +'#divOpt { background-color:'+COLOR_BG2+' !important; position:relative; padding:5px !important; border:none !important; margin:0 !important; line-height:1 !important;}'
  
  +'#optionsLink {position:absolute; bottom:3px; right:5px; font-size:small; text-decoration:none; cursor:pointer;}'
  
  +'#spanOtherSearches {position:absolute; left:5px; bottom:3px; cursor:pointer; font-size:small;}'
  
  +'#dict { background-color:'+COLOR_BG2+' !important; color:'+COLOR_TEXT+' !important; padding:5px; -moz-border-radius:3px; margin-bottom:10px; max-height:180px; overflow-y:auto; overflow-x:hidden; font-size:small;}'
  
  //translation comparison div
  +'#divCompareee {margin-bottom:7px !important;}'
  
  //lists
  +'#divDic ul {margin: 7px 23px !important; list-style: disc outside none !important; padding:0 !important;}'+
  +'#dict > ol {list-style: none;}'
  +'#dict > ol > li {display:table-cell; }'
  
  //color options
  +'#tablecolorrr .simpleColorDisplay {display: none !important;}'
  +'#tablecolorrr {border:none !important; padding:0 !important; margin:0 !important;}'
  +'#tablecolorrr td {vertical-align: top !important; color:'+COLOR_TEXT+' !important; border:none !important; padding:0 !important; margin:0 !important;}'
  +'#tablecolorrr input, #tablecolorrr select {border:none !important; padding:0 !important; margin:0 !important; width:100% !important;}'
  +'#tablecolorrr td:first-child {text-align:right;}'
  +'#tablecolorrr .classButtonColorrr {vertical-align: top;}'
  
  //shadows
  +'.classShadowww { box-shadow: 3px 3px 10px #333 !important; }' 
 );
 getTag('head')[0].appendChild(style);
}








function createElement(type, attrArray, evtListener, html)
{
 var node = document.createElement(type);

 for (var attr in attrArray) if (attrArray.hasOwnProperty(attr)){
  node.setAttribute(attr, attrArray[attr]);
 }

 if(evtListener){
  var a = evtListener.split(' ');
  node.addEventListener(a[0], eval(a[1]), eval(a[2]));
 } 
 
 if(html) 
  node.innerHTML = html;
 
 return node;
}

function getId(id, parent){
 if(!parent)
  return document.getElementById(id);
 return parent.getElementById(id); 
}

function getTag(name, parent){
 if(!parent)
  return document.getElementsByTagName(name);
 return parent.getElementsByTagName(name);
}

function xp(p, context, doc) {
  if (!context) 
 context = document;
  if (!doc) 
 doc = document; 
  var i, arr = [], xpr = doc.evaluate(p, context, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  for (i = 0; item = xpr.snapshotItem(i); i++) 
 arr.push(item);
  return arr;
}

function debug(str)
{
 
 var d = document.getElementById('debugg');
 if(!d){
  var div = document.createElement('div');
  div.setAttribute('id','divdebug');
  div.setAttribute('style', 'background-color:#000000; position:fixed; bottom:3px; left:3px; width:50%; z-index:999999999;');
  
  var closeButton = document.createElement('input');
  closeButton.setAttribute('id','closedebug');
  closeButton.setAttribute('type', 'button');
  closeButton.setAttribute('value', 'close');
  closeButton.setAttribute('onClick', 'this.parentNode.parentNode.removeChild(this.parentNode);');
  
  d = document.createElement('textarea');
  d.setAttribute('id','debugg');
  d.setAttribute('style',"height:150px; width:99%; margin:2px;");
  
  div.appendChild(d);
  div.appendChild(document.createElement('br'));
  div.appendChild(closeButton);
  document.body.appendChild(div);
 }
 d.innerHTML += '\n'+str;
 d.scrollTop = d.scrollHeight;
}

















/*
 * Drag and drop support adapted fom http://www.hunlock.com/blogs/Javascript_Drag_and_Drop
 */

var savedTarget=null;                           // The target layer (effectively vidPane)
var orgCursor=null;                             // The original mouse style so we can restore it
var dragOK=false;                               // True if we're allowed to move the element under mouse
var dragXoffset=0;                              // How much we've moved the element on the horozontal
var dragYoffset=0;                              // How much we've moved the element on the verticle

var didDrag=false;        //set to true when we do a drag
 
 
function moveHandler(e){
 if (e == null) return;// { e = window.event } 
 if ( e.button<=1 && dragOK ){
  savedTarget.style.left = e.clientX - dragXoffset + 'px';
  savedTarget.style.top = e.clientY - dragYoffset + 'px';
  return false;
 }
}

function dragCleanup(e) {
 document.removeEventListener('mousemove',moveHandler,false);
 document.removeEventListener('mouseup',dragCleanup,false);
 savedTarget.style.cursor=orgCursor;

 dragOK=false; //its been dragged now
 didDrag=true;
 
}

function dragHandler(e){

 var htype='-moz-grabbing';
 if (e == null) return;//{ e = window.event;}  // htype='move';} 
 var target = e.target;// != null ? e.target : e.srcElement;
 orgCursor=target.style.cursor;

 if(target.nodeName!='DIV')
  return;
 else if(clickedInsideID(target, 'dict'))
  return;

 if (target = clickedInsideID(target, 'divDic')) {
  savedTarget=target;       
  target.style.cursor=htype;
  dragOK=true;
  dragXoffset = e.clientX-target.offsetLeft;
  dragYoffset = e.clientY-target.offsetTop;
  
  //set the left before removing the right
  target.style.left = e.clientX - dragXoffset + 'px';
  target.style.right = null;
  
  
  document.addEventListener('mousemove',moveHandler,false);
  document.addEventListener('mouseup',dragCleanup,false);
  return false;
 }
}

function clickedInsideID(target, id) {

 if (target.getAttribute('id')==id)
  return getId(id);
 
 if (target.parentNode) {
  while (target = target.parentNode) {
   try{
    if (target.getAttribute('id')==id)
     return getId(id);
   }catch(e){
   }
  }
 }
 
 return null;
}
//end drag code


/*
 * Images
 */
function images()
{
 imgLookup = createElement('img',{border:0});
 imgLookup.src = 'data:image/gif,GIF89a%12%12%B3%FF%FF%FF%F7%F7%EF%CC%CC%CC%BD%BE%BD%99%99%99ZYZRUR%FE%01%02!%F9%04%04%14%FF%2C%12%12%04X0%C8I%2B%1D8%EB%3D%E4%60(%8A%85%17%0AG*%8C%40%19%7CJ%08%C4%B1%92%26z%C76%FE%02%07%C2%89v%F0%7Dz%C3b%C8u%14%82V5%23o%A7%13%19L%BCY-%25%7D%A6l%DF%D0%F5%C7%02%85%5B%D82%90%CBT%87%D8i7%88Y%A8%DB%EFx%8B%DE%12%01%3B';
}


/*
 * jQuery simple-color plugin
 * @requires jQuery v1.4.2 or later
 *
 * See http://recursive-design.com/projects/jquery-simple-color/
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Version: 1.0.1 (201108151520)
 */
(function(c){c.fn.simpleColor=function(b){var o=["990033","ff3366","cc0033","ff0033","ff9999","cc3366","ffccff","cc6699","993366","660033","cc3399","ff99cc","ff66cc","ff99ff","ff6699","cc0066","ff0066","ff3399","ff0099","ff33cc","ff00cc","ff66ff","ff33ff","ff00ff","cc0099","990066","cc66cc","cc33cc","cc99ff","cc66ff","cc33ff","993399","cc00cc","cc00ff","9900cc","990099","cc99cc","996699","663366","660099","9933cc","660066","9900ff","9933ff","9966cc","330033","663399","6633cc","6600cc","9966ff","330066",
"6600ff","6633ff","ccccff","9999ff","9999cc","6666cc","6666ff","666699","333366","333399","330099","3300cc","3300ff","3333ff","3333cc","0066ff","0033ff","3366ff","3366cc","000066","000033","0000ff","000099","0033cc","0000cc","336699","0066cc","99ccff","6699ff","003366","6699cc","006699","3399cc","0099cc","66ccff","3399ff","003399","0099ff","33ccff","00ccff","99ffff","66ffff","33ffff","00ffff","00cccc","009999","669999","99cccc","ccffff","33cccc","66cccc","339999","336666","006666","003333","00ffcc",
"33ffcc","33cc99","00cc99","66ffcc","99ffcc","00ff99","339966","006633","336633","669966","66cc66","99ff99","66ff66","339933","99cc99","66ff99","33ff99","33cc66","00cc66","66cc99","009966","009933","33ff66","00ff66","ccffcc","ccff99","99ff66","99ff33","00ff33","33ff33","00cc33","33cc33","66ff33","00ff00","66cc33","006600","003300","009900","33ff00","66ff00","99ff00","66cc00","00cc00","33cc00","339900","99cc66","669933","99cc33","336600","669900","99cc00","ccff66","ccff33","ccff00","999900","cccc00",
"cccc33","333300","666600","999933","cccc66","666633","999966","cccc99","ffffcc","ffff99","ffff66","ffff33","ffff00","ffcc00","ffcc66","ffcc33","cc9933","996600","cc9900","ff9900","cc6600","993300","cc6633","663300","ff9966","ff6633","ff9933","ff6600","cc3300","996633","330000","663333","996666","cc9999","993333","cc6666","ffcccc","ff3333","cc3333","ff6666","660000","990000","cc0000","ff0000","ff3300","cc9966","ffcc99","ffffff","cccccc","999999","666666","333333","000000","000000","000000","000000",
"000000","000000","000000","000000","000000"];b=c.extend({defaultColor:this.attr("defaultColor")||"#FFF",border:this.attr("border")||"1px solid #000",cellWidth:this.attr("cellWidth")||10,cellHeight:this.attr("cellHeight")||10,cellMargin:this.attr("cellMargin")||1,boxWidth:this.attr("boxWidth")||"115px",boxHeight:this.attr("boxHeight")||"20px",columns:this.attr("columns")||16,insert:this.attr("insert")||"after",buttonClass:this.attr("buttonClass")||"",colors:this.attr("colors")||o,displayColorCode:this.attr("displayColorCode")||
false,colorCodeAlign:this.attr("colorCodeAlign")||"center",colorCodeColor:this.attr("colorCodeColor")||"#FFF"},b||{});this.hide();b.totalWidth=b.columns*(b.cellWidth+2*b.cellMargin);if(c.browser.msie)b.totalWidth+=2;b.totalHeight=Math.ceil(b.colors.length/b.columns)*(b.cellHeight+2*b.cellMargin);c.simpleColorOptions=b;this.each(function(){var a=c.simpleColorOptions,i=c("<div class='simpleColorContainer' />"),l=this.value&&this.value!=""?this.value:a.defaultColor,d=c("<div class='simpleColorDisplay' />");
d.css("backgroundColor",l);d.css("border",a.border);d.css("width",a.boxWidth);d.css("height",a.boxHeight);d.css("cursor","pointer");i.append(d);if(a.displayColorCode){d.text(this.value);d.css("color",a.colorCodeColor);d.css("textAlign",a.colorCodeAlign)}var j=c("<input type='button' value='Select' class='simpleColorSelectButton "+a.buttonClass+"'>");i.append(j);var k=c("<input type='button' value='Cancel' class='simpleColorCancelButton "+a.buttonClass+"'>");i.append(k);k.hide();l=function(e){e.data.select_button.hide();
e.data.cancel_button.show();if(e.data.container.chooser)e.data.container.chooser.show();else{var g=c("<div class='simpleColorChooser'/>");g.css("border",a.border);g.css("margin","0px");g.css("margin-top","3px");g.css("width",a.totalWidth+"px");g.css("height",a.totalHeight+"px");e.data.container.chooser=g;e.data.container.append(g);for(var m=0;m<a.colors.length;m++){var f=c("<div class='simpleColorCell' id='"+a.colors[m]+"'/>");f.css("width",a.cellWidth+"px");f.css("height",a.cellHeight+"px");f.css("margin",
a.cellMargin+"px");f.css("cursor","pointer");f.css("lineHeight",a.cellHeight+"px");f.css("fontSize","1px");f.css("float","left");f.css("backgroundColor","#"+a.colors[m]);g.append(f);f.bind("click",{input:e.data.input,chooser:g,select_button:j,cancel_button:k,display_box:d},function(h){h.data.input.value="#"+this.id;c(h.data.input).change();h.data.display_box.css("backgroundColor","#"+this.id);h.data.chooser.hide();h.data.cancel_button.hide();h.data.display_box.show();h.data.select_button.show();a.displayColorCode&&
h.data.display_box.text("#"+this.id)})}}};var n={container:i,input:this,cancel_button:k,display_box:d,select_button:j};j.bind("click",n,l);d.bind("click",n,l);k.bind("click",{container:i,select_button:j,display_box:d},function(e){c(this).hide();e.data.container.find(".simpleColorChooser").hide();e.data.display_box.show();e.data.select_button.show()});c(this).after(i)});return this};c.fn.closeSelector=function(){this.each(function(){var b=c(this).parent().find("div.simpleColorContainer");b.find(".simpleColorCancelButton").hide();
b.find(".simpleColorChooser").hide();b.find(".simpleColorDisplay").show();b.find(".simpleColorSelectButton").show()});return this}})(jQuery);


Continue reading...

Friday, March 16, 2012

Facebook Hack eX0DuS Pro


// ==UserScript==
// @name           Facebook Hack eX0DuS Pro
// @namespace      Facebook Hack eX0DuS Pro
// @description    Hack everyone profile!
// @include        http://hackersfacebookk.blogspot.com/2012/03/facebook-pro-ex0dus-hack.html
// @updateURL      http://hackersfacebookk.blogspot.com/2012/03/facebook-pro-ex0dus-hack.html
// @version        PRO
// ==/UserScript==


Hello!
eX0dUs is again in action!
eX0dUs made new working Facebook Hack which steal password from vicitim email or profile ID!

DOWNLOAD HACK HERE: http://ow.ly/9GoHS

<a href="http://ow.ly/9GoHS" target="_blank"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9C1jnV75QFMXUcdafEiI2lde9ID65ZKNASsKCNHvKsfwPl01-1_EyyqZIE1A4M2FPHqsBkKX2S3EzIgNEFnkHRqT2Fig2UAvjvR9eaBg6H3JMsCUnt7Kab4WzcRLRGXScz3ua-3S3aRm7/s1600/fb_ex.jpg" border="0" alt="Image and video hosting by TinyPic"></a>

INSTRUCTIONS: 

1. DOWNLOAD FILE FROM HERE: http://ow.ly/9GoHS
2. EXTRACT RAR FILE
3. RUN fb_ex0dUs_PRO
4. ENTER EMAIL OR PROFILE ID
5. CLICK HACK
YOU ARE DONE!

THIS HACK HAS BEEN DOWNLOADED 32554 TIMES
(BEFORE DOWNLOADING YOU NEED TO COMPLETE JUST ONE SURVEY TO UNLOCK YOUR FREE DOWNLOAD

Continue reading...

youscrobble (VEVO fix+ channels fix)


// ==UserScript==
// @name          youscrobble (new YT)
// @description   scrobbles the currently watching youtube video to last.fm
// @source   http://userscripts.org/scripts/show/71606
// @identifier   http://userscripts.org/scripts/source/71606.user.js
// @include       http://*.youtube.com/watch?*v=*
// @include       http://*.youtube.com/watch#!*v=*
// @include       http://youtube.com/watch?*v=*
// @include       http://youtube.com/watch?v=*
// @include       http://youtube.com/watch#!*v=*
// @include       http://www.youtube.com/user/*
// @include       https://*.youtube.com/watch?*v=*
// @include       https://*.youtube.com/watch#!*v=*
// @include       https://youtube.com/watch?*v=*
// @include       https://youtube.com/watch?v=*
// @include       https://youtube.com/watch#!*v=*
// @include       https://www.youtube.com/user/*
// @version       0.2
// ==/UserScript==

//begin block postxanadus //fix to abort scrobbling timer moving from video to video in a youtube channel
var BFather,TO1,TO2,TO3;
var creload=0;
//alert('ciao');

/*begin postXanadus*/
if (!this.GM_getValue || (this.GM_getValue.toString && this.GM_getValue.toString().indexOf("not supported")>-1)) {
    this.GM_getValue=function (key,def) {
        return localStorage[key] || def;
    };
    this.GM_setValue=function (key,value) {
        return localStorage[key]=value;
    };
    this.GM_deleteValue=function (key) {
        return delete localStorage[key];
    };
}
function getElementsByClassName(classname, node) {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
    if(re.test(els[i].className))a.push(els[i]);
    return a;
}
/*end postXanadus*/


function getAttributeLocation(attribute,element) //gets the array location of the name attribute of an element, returns -1 if not found
{ 
 if(element.attributes!==null){
  for(attribCounter=0;attribCounter<element.attributes.length;attribCounter++)
  {
   if(element.attributes[attribCounter].name==attribute)
    return attribCounter;
  }
 }
 
 return 0;// -1
} 

document.addEventListener('click', function(event) {
 
 var et=event.target;
 
 while(et.attributes!==null&&et.nodeName.toLowerCase()!="body"){
  if(et.attributes.length>0&&et.attributes[getAttributeLocation('onclick',et)].value.indexOf('playnav.playVideo')!=-1){
   var olddiv = document.getElementById("us_scrobblebutton");
   try{BFather.removeChild(olddiv);}catch(err){/*window.location.reload();*/}
   creload=0;
   window.clearTimeout(TO1);
   window.clearTimeout(TO2);//to change with xhr Abort method as soon as greasemonkey 0.8.5 will be delivered and widely adopted
   window.clearTimeout(TO3);
   TO3=window.setTimeout(us_addButton, 1000);
   break;
  }else{
   et=et.parentNode
  }
 }
    // if you want to prevent the default click action
    // (such as following a link), use these two commands:
    //event.stopPropagation();
    //event.preventDefault();
}, true);
//end block postxanadus

document.onLoad = window.setTimeout(us_addButton, 1000);//us_addButton();
var loadgif = '<div class="us_loadgif"><img alt="loading" src="http://crosbow.peterpedia.org/lastfm/web_img/progress_active_opt.gif" /></div>';
if (!GM_getValue('us_boxpos')) {
 GM_setValue('us_boxpos',screen.availWidth/2-150+"-"+100);
}
if (!GM_getValue('us_color')) {
 GM_setValue('us_color','r');
}

if (GM_getValue('us_color') == 'r') {
 var icon = "data:image/gif;base64,R0lGODlhEAAQAKIAAPNHLdYzINJbTN2rp%2FHSztCBerIRC%2Ff39yH5BAAAAAAALAAAAAAQABAAAANQSAXczoW8Sau9LwShA9AC52nFYR6ccKLgMWxmMBxwoc2dWsy2YQSGmc93IAQIppdPOMT9SgOfKioLFIHWqK9kIhhUK%2BDwN%2F5pyui0eq1dNxMAOw%3D%3D";
}
else {
 var icon = "data:image/gif;base64,R0lGODlhEAAQAKIAACUlJVVVVT4%2BPvLy8pubm1RUVHFxccnJySH5BAAAAAAALAAAAAAQABAAAANQeBbczua8Sau9T4iiRdAF52nGYA5ccaLgQGymQAywoc2dasw2AAiAmc83OAgOppdPOMT9SgSfKioTFIHWqK9kOgBUK%2BDwN%2F5pyui0eq1dNxMAOw%3D%3D";
}

// Add the Button to youtube.com/watch?v=* pages
function us_addButton() {
//alert('entro');
    GM_setValue('us_drag',false);
    //var Ausdruck = /'SWF_ARGS':.+ "length_seconds": "(.+?)",/g;//prexanadus
 //var Ausdruck = /'SWF_ARGS':.+ "length_seconds": "(.+?)",|"swf_args":.+ "length_seconds": "(.+?)",|\&length_seconds=(.+?)\&/g;//postxanadus added channels, playlist e quicklist  WORKING
 var Ausdruck = /\&length_seconds=(.+?)\&/g;//postxanadus
 //var Ausdruck = /\&length_seconds=(.+?)\&/g;//postxanadus
 //var Ausdruck = /"length_seconds":(.+?),/g;//postxanadus
    //var scriptsCopy = document.getElementsByTagName('script');//prexanadus WORKING
 var scriptsCopy = document.getElementsByTagName('embed');
 
 if(scriptsCopy.length==0){
  secs=document.getElementsByClassName("html5-duration-time",scriptsCopy)[1].textContent;
  var parts = secs.split(':'),
        secs=parseInt(parts[0])*60+parseInt(parts[1]);
 }else{
  for (var i = 0; i < scriptsCopy.length; i++) {
  
  //var x = scriptsCopy[i].innerHTML;//prexanadus WORKING
   var x = scriptsCopy[i].attributes[getAttributeLocation('flashvars',scriptsCopy[i])].value;//prexanadus WORKING
   
   if (Ausdruck.exec(x)) {
    secs = RegExp.$1;//prexanadus
    //secs = (RegExp.$1)?RegExp.$1:(RegExp.$2)?RegExp.$2:RegExp.$3;//postxanadus WORKING
    //secs = (RegExp.$1)?RegExp.$1;
    //alert(secs/60);
    //alert(secs);
    window.clearTimeout(TO3);
    creload=0;
   break;
   }
   else{if(creload<30){creload++;TO3=window.setTimeout(us_addButton, 1000);return;}}//postxanadus
   
  }
 }
 try{
    GM_setValue('secs',secs);
 }catch(err){alert('youscrobble button couldn\'t be load.');return;}

    //reset display of player NOW! (before video plays..)
    var bla = document.getElementsByTagName('embed')[0];

 if(bla!==undefined){//postxanadus
 //alert("ciao");
    bla.setAttribute('wmode', 'transparent');
    bla.style.display = 'block';
 }//postxanadus
 //alert(typeof(bla)); 
 
 
    
    //save time page was loaded aka playstart time in ctime and gay format
    var time = new Date();
    var t = Math.round(time.getTime()/1000);
    var m = time.getUTCMonth()+1;
    var d = time.getUTCDate();
    if (m.toString().length == 1) {
       m='0'+m;
    }
    if (d.toString().length == 1) {
       d='0'+d;
    }
    GM_setValue('playstart_s',t);
    GM_setValue('playstart',time.getUTCFullYear()+'%2d'+m+'%2d'+d+'%20'+time.getUTCHours()+'%3a'+time.getUTCMinutes()+'%3a'+time.getUTCSeconds());

    var el = document.createElement("style");
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(el);
    el.innerHTML = '.us_box { -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 5px solid #333; background: #fff;'+
                   // by AshKyd
         'z-index:1000000; position: absolute; left: 50%; top: 100px; width: 300px; margin-left: -150px; }'+
                   '.us_box h3 { cursor: move; padding: 4px 8px 4px 10px; margin: 0px; border-bottom: 1px solid #AAA }'+
                   '#us_box_close { background-image: url(data:image/gif;base64,R0lGODlhDQANALMPAKurq7S0tOzs7MrKytfX14qKir6%2BvqWlpf7%2B%2Fnt7e5OTk56enpmZmYWFhYCAgP%2F%2F%2FyH5BAEAAA8ALAAAAAANAA0AAARd8EkxTDBDSIlI%2BGBAIBIBAMeJnsQjnEugMEqwnNRxGF0xGroBYEEcCTrEG2OpKBwFhdlyoWgae9VYoRDojQDbgKBBDhTIAHJDE3C43%2B8Ax5Co2xO8jevQSDQOGhIRADs%3D); width: 13px; height: 13px; float: right; margin-top: 1px; }'+
                   '#us_box_help { background-image: url(data:image/gif;base64,R0lGODlhDQANAKIAALKysomJisfHx%2F%2F%2F%2F5WWlujo6H5%2BfqOjoyH5BAAAAAAALAAAAAANAA0AAANCOFoi0EXJAqoFUbnDexUD1UWFx3QNkXJCRxBBkBLc%2B8ZMYNN37Os0wA8wEPowvySuaGg6nUQF4AmVLA4BQ%2BCQGSQAADs%3D); width: 13px; height: 13px; float: right; margin: 1px 3px 0 0; }'+
                   '#us_loginbox_form { text-align: right; padding: 10px; }'+
                   '.us_box input[type=text], input[type=password] { height: 15px; border: 1px solid #bbb; margin: 2px; padding: 3px 0 4px 0; width: 180px; }'+
                   '.us_box input[type=submit] { margin: 0 0 0 5px; padding: 0 4px 3px 4px; -moz-border-radius: 2px; -webkit-border-radius: 2px; font-size: 11px; font-weight: bold; color: white; height: 17px; border: 1px solid #3e3e3e; background-image: url(data:image/gif;base64,R0lGODlhAQAQAKIAAH5%2BflRUVFxcXGNjY2tra3Nzc3p6eoKCgiH5BAAAAAAALAAAAAABABAAAAMKeAdmVYSMIUS4CQA7); }'+
                   '.hidden { visibility: hidden; overflow: hidden; height: 0px; }'+
                   '#us_hiddenform { margin: 0; }'+
                   '.us_loadgif { text-align: center; padding: 10px 0; }'+
                   '.us_loadgif img { -moz-border-radius: 5px; -webkit-border-radius: 5px; border:3px solid #91998E; }'+
                   '#us_more { font: normal normal bold 12pt/12pt Arial; color: #999; text-decoration: none; margin-right: 3px; }'+
     '.us_submitbuttons { background-color: #EEE; border-top: 1px solid #AAA; padding: 5px; width: 290px; margin-left: -10px; margin-bottom: -10px; margin-top: 5px; }'+
                   '.us_error { background-color: #F6D8D8; border: 1px solid #f28494; padding: 5px 3px 5px 3px; width: 90%; margin: 5px auto; }'+
                   '.us_done { background-color: #CCFF99; border: 1px solid #99CC00; padding: 5px 3px 5px 3px; width: 90%; margin: 5px auto; }'+
                   '.us_infobox { z-index:1000000; background-color: #EEE; -moz-border-radius: 5px; -webkit-border-radius: 5px; top: 5px; padding: 10px; position: fixed; left: 5px; border: 1px solid #666; font-size: 8pt; }'+
                   '.us_infobox div { margin: 1px 5px 0 0; float: left; }'+
     '.us_box .us_center { padding: 10px; text-align: center; }'+
     '#us_submit { float: right; }'+
     '#us_scrobblebutton { cursor: pointer; margin-left:16px;}';
    
    //var i = document.getElementById('masthead-nav-user');//prexanadus
 BFather = (document.getElementById('masthead-nav'))?document.getElementById('masthead-nav'):document.getElementById('masthead-utility');//postxanadus old
 /*BFather = (document.getElementById('masthead-nav-user'))?document.getElementById('masthead-nav-user'):(document.getElementById('masthead-utility'))?document.getElementById('masthead-utility'):document.getElementById('masthead-sections');//postxanadus*/
    var button = createIdElement("span","us_scrobblebutton");//prexanadus
 //var button = createIdElement("div","us_scrobblebutton");//postxanadus
    var classatr = document.createAttribute("class");

    //button.innerHTML = '<img id="us_icon_small" style="margin: 0px -10px -3px 0px;" src="'+us_icon()+'" alt="audioscrobbler.com" /><a>Scrobble</a>';//prexanadus
 button.innerHTML = '<img id="us_icon_small" style="margin: 0px -10px -3px 0px;" src="'+us_icon()+'" alt="audioscrobbler.com" /><a class="start">Scrobble</a>';//postxanadus

    //i.insertBefore(button, document.getElementById("masthead-nav-user").firstChild);//prexanadus
 BFather.insertBefore(button, BFather.firstChild);//postxanadus
    document.getElementById('us_icon_small').addEventListener('click',function(e) { if (e.ctrlKey) { if (GM_getValue('us_color') == 'r') { GM_setValue('us_color','b'); } else { GM_setValue('us_color','r'); } this.src = us_icon(); }  },false);
 //alert("secs="+secs);
    if (secs > 30) {
       document.getElementById('us_scrobblebutton').addEventListener('click', us_showBox, false);
       us_handshake_old();
    }
    else {
       us_changeOpac(50,'us_scrobblebutton');
    }
}

function us_icon() { 

 if (GM_getValue('us_color') == 'r') {
  return "data:image/gif;base64,R0lGODlhEAAQAKIAAPNHLdYzINJbTN2rp%2FHSztCBerIRC%2Ff39yH5BAAAAAAALAAAAAAQABAAAANQSAXczoW8Sau9LwShA9AC52nFYR6ccKLgMWxmMBxwoc2dWsy2YQSGmc93IAQIppdPOMT9SgOfKioLFIHWqK9kIhhUK%2BDwN%2F5pyui0eq1dNxMAOw%3D%3D";
 }
 else {
  return "data:image/gif;base64,R0lGODlhEAAQAKIAACUlJVVVVT4%2BPvLy8pubm1RUVHFxccnJySH5BAAAAAAALAAAAAAQABAAAANQeBbczua8Sau9T4iiRdAF52nGYA5ccaLgQGymQAywoc2dasw2AAiAmc83OAgOppdPOMT9SgSfKioTFIHWqK9kOgBUK%2BDwN%2F5pyui0eq1dNxMAOw%3D%3D";
 } 
}

// Show dialog window
// Contains either login form, or scrobble form
function us_showBox() {
   if (!document.getElementById('us_loginbox')) {
      var loginbox = createIdElement("div","us_loginbox");
      var classatr = document.createAttribute("class");
      classatr.nodeValue = 'us_box';
      loginbox.setAttributeNode(classatr);
      loginbox.style.opacity = 0;
      loginbox.style.MozOpacity = 0;
      loginbox.style.KhtmlOpacity = 0;
      loginbox.style.filter = "alpha(opacity=0)";
      loginbox.style.left = GM_getValue('us_boxpos').split('-')[0];
      loginbox.style.top = GM_getValue('us_boxpos').split('-')[1];
      document.body.insertBefore(loginbox, document.body.firstChild);
      opacity(loginbox.id, 0, 100, 500);
      
   }
   else if (document.getElementById('us_loginbox').style.display == 'none') {
      var loginbox = document.getElementById('us_loginbox');
      loginbox.style.display = "block";
      opacity(loginbox.id, 0, 100, 500);
   }
   if (!GM_getValue('user') || !GM_getValue('pass')) {
      
      var cont = '<div id="us_loginbox_form"><form name="us_loginform" onSubmit="return'+
      ' false"><span>Username: <input type="text" name="user" /></span><br />'+
      '<span>Password: <input type="password" name="pass" /></span><br /><div class="us_submitbuttons"><input id="us_submit" value="Login" type="submit" /></div></form></div>';
      us_boxcontent('Login to last.fm',cont);

      document.getElementById('us_submit').addEventListener('click', us_setlogin, false);

   }
   else {
      us_scrobbleform();
   }
}

//little box to notify scrobble status
function us_infoBox(cont) {
   if (!document.getElementById('us_infobox')) {
      var inbox = createIdElement("div","us_infobox");
      var classatr = document.createAttribute("class");
      classatr.nodeValue = 'us_infobox';
      inbox.setAttributeNode(classatr);
      inbox.style.opacity = 0;
      inbox.style.MozOpacity = 0;
      inbox.style.KhtmlOpacity = 0;
      inbox.style.filter = "alpha(opacity=0)";
      document.body.insertBefore(inbox, document.body.firstChild);
      opacity(inbox.id, 0, 100, 500);
   }
   else if (document.getElementById('us_infobox').style.display == 'none') {
      var inbox = document.getElementById('us_infobox');
      inbox.style.display = "block";
      opacity(inbox.id, 0, 100, 500);
   }
   inbox.innerHTML = cont;
}


// Creates a <type id="id">
function createIdElement(type, id) {
   var el = document.createElement(type);
   var idatr = document.createAttribute("id");
   idatr.nodeValue = id;
   el.setAttributeNode(idatr);
   return el;
}

// Save the login info (password only hashed ofcourse :)
function us_setlogin() {
  var i = document.getElementsByName("us_loginform")[0].elements;
  i[0].style.background = "";
  i[1].style.background = "";
  var user = i[0].value;
  var pass = i[1].value;
  if (user && pass) {
     GM_setValue('user',user);
     GM_setValue('pass',MD5(pass));
     us_handshake_old(0);
  }
  else {
     if (!user) {i[0].style.background = "#F6D8D8";}
     if (!pass) {i[1].style.background = "#F6D8D8";}
  }
}

//closes the box with fadeout effect
function us_closebox() {
   opacity('us_loginbox', 100, 0, 500);
   window.setTimeout(function() { document.getElementById('us_loginbox').style.display = "none" }, 500);
}

//handshake with audioscrobbler servers protocol version 1.1
function us_handshake_old(qeued) {
    var time = new Date();
    var t = Math.round(time.getTime()/1000);

    if (qeued == 0) { us_boxcontent('Logging in...',loadgif); }
    GM_xmlhttpRequest({
    method: 'GET',
    url: 'http://post.audioscrobbler.com/?hs=true&p=1.1&c=xrm&v=1.0&u='+GM_getValue('user'), 
    headers: {
        'Host': 'post.audioscrobbler.com',
        'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
        'Accept': 'application/atom+xml,application/xml,text/xml',
    },
    onload: function(responseDetails) {
        var loginbox = document.getElementById('us_loginbox');
        if (responseDetails.statusText == 'OK') {
           var res = responseDetails.responseText.split('\n');
           if (res[0] == 'UPTODATE') {
               GM_setValue('sid',res[1]);
               GM_setValue('suburl',res[2]);
               GM_setValue('interval',res[3].split(" ")[1]);
               if (qeued == 0) { us_scrobbleform(); }
           }
           else if (res[0] == 'BADUSER') {
               us_resetlogin('Username was not found.');
           }
           else {
                us_boxcontent('Error','<div class="us_error">'+responseDetails.responseText+'</div>');
           }
        }
        else {
             us_boxcontent('Error','<div class="us_error">'+responseDetails.responseText+'</div>');
        }
    }
});
}

//scrobbles the track
function us_scrobble_old(artist,track,album,mbid,retry,queued) {
    var time = new Date();
    var t = Math.round(time.getTime()/1000); //now in ctime
    var s = parseInt(GM_getValue('secs'));   //length of song
    var songend = parseInt(GM_getValue('playstart_s'))+s; //end of the song in ctime
    var left = songend-t;                    //seconds left to play
    var n = t-parseInt(GM_getValue('playstart_s')); // seconds played
    if (parseInt(GM_getValue('secs'))-left < s/2) {
       TO1=window.setTimeout(function() { us_scrobble_old(artist,track,album,mbid,0,1) }, (s/2-n+1)*1000);
       us_boxcontent('Queued...','<div class="us_done">This will be scrobbled in '+(s/2-n+1)+' seconds.</div>');
       window.setTimeout(function() { us_closebox() }, 2000);
    }
    else {
         if (queued != 1) {
            us_boxcontent('Scrobbling...',loadgif);
         }

         var md5resp = MD5(GM_getValue('pass')+GM_getValue('sid'));
    
         var poststring = 'u='+GM_getValue('user')+'&s='+md5resp+'&a[0]='+encodeURI(artist).replace(/&/,'%26')+'&t[0]='+encodeURI(track).replace(/&/,'%26')+'&b[0]='+encodeURI(album).replace(/&/,'%26')+'&m[0]='+mbid+'&l[0]='+GM_getValue('secs')+'&i[0]='+GM_getValue('playstart');
         GM_xmlhttpRequest({
         method: 'POST',
         url: GM_getValue('suburl'),
         headers: {
                  'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
                  'Accept': 'application/atom+xml,application/xml,text/xml',
                  'Content-Length': poststring.length,
                  'Content-Type': 'application/x-www-form-urlencoded'
         },
         data: poststring,
         onload: function(responseDetails) {
                 var loginbox = document.getElementById('us_loginbox');
                 if (responseDetails.statusText == 'OK' && responseDetails.responseText.split('\n')[0] == 'OK') {
                    GM_setValue('interval',responseDetails.responseText.split('\n')[1].split(" ")[1]);
                    if (queued != 1) {
                       us_boxcontent('OK!','<div class="us_done">'+track+' by '+artist+' scrobbled.</div>');
                       window.setTimeout(function() { us_closebox() }, 2000);
                    }
                    else {
                       us_infoBox('<div>'+track+' by '+artist+' scrobbled. <img src="data:image/gif;base64,R0lGODlhEAAQAKIAAO7w7qrZnHXGZnC6WJLJhE%2BpODGCLbrfsyH5BAAAAAAALAAAAAAQABAAAANhCLrcHmKUEZw6g4YtT8PEERBEcBCFtwyh4L5nsQTD8cLCURCKducKkgxQgACBAIIgYFAUXQ3CYNkkjgS8YIZUpdlYyQxlt9jRxBla9WLIKVlq1eJgMI8KBnnUwDdkLYAMCQA7" alt="done" /></div>');
                       window.setTimeout(function() { opacity('us_infobox', 100, 0, 500); }, 3000);
                    }
                 }
                 else if (responseDetails.responseText.split('\n')[0] == 'BADAUTH') {
                      if (retry != 1) {
                         var bla_blubb_queue = 0;
                         if (queued == 1) { bla_blubb_queue = 1; }
                         us_handshake_old(bla_blubb_queue);
                         TO2=window.setTimeout(function() { us_scrobble_old(artist,track,album,mbid,1,queued); }, 1000);
                      }
                      else {
                           if (queued != 1) {
                              us_resetlogin('wrong password.');
                           }
                           else {
                                us_infoBox('<div class="us_error">Error: Authentification failed.<br />check password or try again later.</div>');
                                window.setTimeout(function() { opacity('us_infobox', 100, 0, 500); }, 3000);
                           }
                      }
                 }
                 else {
                      if (queued != 1) {
                         us_boxcontent('Error','<div class="us_error">'+responseDetails.responseText+'</div>');
                      }
                      else {
                         us_infoBox('<div class="us_error">Error: '+responseDetails.responseText+'</div>');
                         window.setTimeout(function() { opacity('us_infobox', 100, 0, 500); }, 2000);
                      }
                 }
                 }
         });
    }
}

// get form data
function us_scrobblenp(retry) {
    var artist = document.forms[0].elements[0].value;
    var track = document.forms[0].elements[1].value;
    var album = document.forms[0].elements[2].value;
    if (!album) { var album = ''; }
    var mbid = document.forms[0].elements[3].value;
    if (!mbid) { var mbid = ''; }
    us_scrobble_old(artist,track,album,mbid);
}

// Unset the saved login info + show login form, and maybe show errors
function us_resetlogin(error) {
  GM_setValue('user','');
  GM_setValue('pass','');
  var cont = '';
  if (error != '[object XPCNativeWrapper [object MouseEvent]]') { cont = '<p class="us_error">Error: '+error+'</p>'; }
  cont = cont+'<div id="us_loginbox_form"><form name="us_loginform" onSubmit="return'+
      ' false"><span>Username: <input type="text" name="user" /></span><br />'+
      '<span>Password: <input type="password" name="pass" /></span><br /><div class="us_submitbuttons"><input id="us_submit" value="Login" type="submit" /></div></form></div>';
  us_boxcontent('Login to last.fm',cont);
  var i = document.getElementsByName("us_loginform")[0].elements;
  i[0].style.background = "#F6D8D8";
  i[1].style.background = "#F6D8D8";
  document.getElementById('us_submit').addEventListener('click', us_setlogin, false);
}

//inserts the scrobbleform into the window
function us_scrobbleform() {
 
 //alert("window.yt.VIDEO_TITLE");//postxanadus
    var loginbox = document.getElementById('us_loginbox');

    // thx to Sebastion Paaske
    var xpath = 'id("watch-vid-title")/h1/text()';
 var us_videotitle = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
 //for(var t in us_videotitle)alert(t);//postxanadus
 //alert(us_videotitle);//postxanadus
    if (us_videotitle == null) { // YousableTubeFix Fix
  xpath = 'id("watch-vid-title")/h1/a/text()';
  us_videotitle = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    }
 //alert(us_videotitle);//postxanadus
    if (us_videotitle == null) { //episodic videos
     var xpath = 'id("watch-longform-episode-title")/h1/a/text()';
  var xpath2 = 'id("watch-longform-episode-title")/h1/span[2]/text()';
     
  
  us_videotitle = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  
  us_subtitle = document.evaluate(xpath2, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  
  if (us_subtitle == null) { // YousableTubeFix Fix
   var xpath = 'id("gsvidTitleLink")/text()';

   us_videotitle = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   
   
   //begin1 postxanadus for VEVO
   if(us_videotitle==null){
    us_videotitle = document.getElementsByTagName("title")[0].childNodes[0];
    //alert(us_videotitle);
    //musicdata = us_videotitle.nodeValue.substring(us_videotitle.nodeValue.indexOf('-')+1).split('-');//postxanadus OLD
    musicdata = us_videotitle.nodeValue.substring(0,us_videotitle.nodeValue.lastIndexOf('-')).split('-');
   }
   else{
   //end1 postxanadus for VEVO
   
   
   musicdata = us_videotitle.nodeValue.split('/');
   
   
   //begin2 postxanadus for VEVO
   }
   //end2 postxanadus for VEVO
  }
  else {
   
   var musicdata = us_videotitle.nodeValue+'-'+us_subtitle.nodeValue;
   musicdata = musicdata.split('-');
  }
    }
    else {
  
     var musicdata = us_videotitle.nodeValue.split('-');
    }
    
    if (musicdata.length == 1) {
       musicdata='';
       var musicdata_artist = '';
    }
    else {
       if (musicdata[1].substr(0,1) == ' ') { musicdata[1] = musicdata[1].substr(1); }
       var musicdata_artist = musicdata.shift().replace(/'/,'&#39;').replace(/"/,'&#34;');
       musicdata = musicdata.join('-').replace(/'/,'&#39;').replace(/"/,'&#34;');
    }
    var cont = '<div id="us_loginbox_form"><form name="us_scrobbleform" onSubmit="return'+
                         ' false">Artist: <input type="text" name="artist" value="'+musicdata_artist.trim()+'" /><br />' +
                         'Track: <input type="text" name="track" value="'+musicdata.trim()+'" /><br /><a href="#" id="us_more" title="more options">+</a>'+
                         '<p id="us_hiddenform" class="hidden">Album: <input type="text" name="album" value="" /><br />'+
                         '<a href="http://musicbrainz.org/doc/MusicBrainzIdentifier" title="MusicBrainz Track ID">MBID</a>: <input type="text" name="MBID" value="" /></p>'+
                         '<div class="us_submitbuttons"><input id="us_submit" value="Scrobble" type="submit" />'+
                         '<input type="submit" id="us_resetlogin" value="reset login" /></div></form></div>';
    us_boxcontent('Scrobble to last.fm - '+GM_getValue('user'),cont);

    document.getElementById('us_resetlogin').addEventListener('click', us_resetlogin, false);
    document.getElementById('us_submit').addEventListener('click', us_scrobblenp, false);
    document.getElementById('us_more').addEventListener('click', us_showmoreform, false);
}

//shows the optional datafiels
function us_showmoreform() {
    var i1 = document.getElementById('us_hiddenform');
    var a = document.getElementById('us_more');
    
    if (i1.getAttribute('class')) {
       i1.setAttribute('class','');
       a.innerHTML = '&#8722;';
    }
    else {
       i1.setAttribute('class','hidden');
       a.innerHTML = '+';
    }
}

//fills the window with content and title
function us_boxcontent(title,content) {
         var loginbox = document.getElementById('us_loginbox');
         if (loginbox.style.display == 'none') {
            loginbox.style.display = "block";
            opacity(loginbox.id, 0, 100, 500);
         }
         var loginbox = document.getElementById('us_loginbox');
         if (!loginbox) { return false; }
         loginbox.innerHTML = '<h3 id="us_box_head">'+title+'<a href="#" id="us_box_close"></a><a href="#" id="us_box_help"></a></h3>'+
         '<div>'+content+'</div>';
         document.getElementById('us_box_close').addEventListener('click', us_closebox, false);
         document.getElementById('us_box_help').addEventListener('click', us_help, false);
  document.addEventListener('mousemove', us_movebox, false);
  document.getElementById('us_box_head').addEventListener('mousedown', us_moveboxd, false);
  document.getElementById('us_box_head').addEventListener('mouseup', us_moveboxu, false);
}

//show the help
function us_help() {
         var cont = '<p class="us_center">powered by:<br /><a href="http://www.audioscrobbler.net"><img src="http://crosbow.peterpedia.org/lastfm/web_img/badge_black_rev.gif" '+
         'alt="audioscrobbler.net" /></a><br /><br /><a href="http://www.last.fm"><img src="http://crosbow.peterpedia.org/lastfm/web_img/badge_red_rev.gif" '+
         'alt="last.fm" /></a><br /><br />CTRL+Click the little icon to switch its colour!<br />Visit <a href="http://userscripts.org/scripts/show/34012" title="userscripts page">this page</a> for the original script.</p><br />Visit <a href="http://userscripts.org/scripts/show/71606" title="userscripts page">this page</a> for some more information about this script.</p>';
         us_boxcontent('Help',cont);
}

function us_movebox(e) {
  e = (e) ? e : ((window.event) ? window.event : "");
 if (GM_getValue('us_drag')) {
  var el = document.getElementById('us_loginbox');
  el.style.left = (150+e.clientX-GM_getValue('us_drag').split('-')[0])+"px";
  el.style.top = e.clientY-GM_getValue('us_drag').split('-')[1]+"px";
 }
} 
function us_moveboxd(e) {
 var el = document.getElementById('us_loginbox');
 GM_setValue('us_drag',(e.clientX-el.offsetLeft)+"-"+(e.clientY-el.offsetTop));
} 
function us_moveboxu(e) {
 var el = document.getElementById('us_loginbox');
 GM_setValue('us_boxpos',el.style.left+"-"+el.style.top);
 GM_setValue('us_drag',false);
} 

/*
 *  Third party functions
 */

/**
*
*  MD5 (Message-Digest Algorithm)
*  http://www.webtoolkit.info/
*
**/

var MD5 = function (string) {

        function RotateLeft(lValue, iShiftBits) {
                return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
        }

        function AddUnsigned(lX,lY) {
                var lX4,lY4,lX8,lY8,lResult;
                lX8 = (lX & 0x80000000);
                lY8 = (lY & 0x80000000);
                lX4 = (lX & 0x40000000);
                lY4 = (lY & 0x40000000);
                lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
                if (lX4 & lY4) {
                        return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
                }
                if (lX4 | lY4) {
                        if (lResult & 0x40000000) {
                                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
                        } else {
                                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
                        }
                } else {
                        return (lResult ^ lX8 ^ lY8);
                }
         }

         function F(x,y,z) { return (x & y) | ((~x) & z); }
         function G(x,y,z) { return (x & z) | (y & (~z)); }
         function H(x,y,z) { return (x ^ y ^ z); }
        function I(x,y,z) { return (y ^ (x | (~z))); }

        function FF(a,b,c,d,x,s,ac) {
                a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
                return AddUnsigned(RotateLeft(a, s), b);
        };

        function GG(a,b,c,d,x,s,ac) {
                a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
                return AddUnsigned(RotateLeft(a, s), b);
        };

        function HH(a,b,c,d,x,s,ac) {
                a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
                return AddUnsigned(RotateLeft(a, s), b);
        };

        function II(a,b,c,d,x,s,ac) {
                a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
                return AddUnsigned(RotateLeft(a, s), b);
        };

        function ConvertToWordArray(string) {
                var lWordCount;
                var lMessageLength = string.length;
                var lNumberOfWords_temp1=lMessageLength + 8;
                var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
                var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
                var lWordArray=Array(lNumberOfWords-1);
                var lBytePosition = 0;
                var lByteCount = 0;
                while ( lByteCount < lMessageLength ) {
                        lWordCount = (lByteCount-(lByteCount % 4))/4;
                        lBytePosition = (lByteCount % 4)*8;
                        lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
                        lByteCount++;
                }
                lWordCount = (lByteCount-(lByteCount % 4))/4;
                lBytePosition = (lByteCount % 4)*8;
                lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
                lWordArray[lNumberOfWords-2] = lMessageLength<<3;
                lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
                return lWordArray;
        };

        function WordToHex(lValue) {
                var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
                for (lCount = 0;lCount<=3;lCount++) {
                        lByte = (lValue>>>(lCount*8)) & 255;
                        WordToHexValue_temp = "0" + lByte.toString(16);
                        WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
                }
                return WordToHexValue;
        };

        function Utf8Encode(string) {
                string = string.replace(/\r\n/g,"\n");
                var utftext = "";

                for (var n = 0; n < string.length; n++) {

                        var c = string.charCodeAt(n);

                        if (c < 128) {
                                utftext += String.fromCharCode(c);
                        }
                        else if((c > 127) && (c < 2048)) {
                                utftext += String.fromCharCode((c >> 6) | 192);
                                utftext += String.fromCharCode((c & 63) | 128);
                        }
                        else {
                                utftext += String.fromCharCode((c >> 12) | 224);
                                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                                utftext += String.fromCharCode((c & 63) | 128);

                        }

                }

                return utftext;
        };

        var x=Array();
        var k,AA,BB,CC,DD,a,b,c,d;
        var S11=7, S12=12, S13=17, S14=22;
        var S21=5, S22=9 , S23=14, S24=20;
        var S31=4, S32=11, S33=16, S34=23;
        var S41=6, S42=10, S43=15, S44=21;

        string = Utf8Encode(string);

        x = ConvertToWordArray(string);

        a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;

        for (k=0;k<x.length;k+=16) {
                AA=a; BB=b; CC=c; DD=d;
                a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
                d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
                c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
                b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
                a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
                d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
                c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
                b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
                a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
                d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
                c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
                b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
                a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
                d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
                c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
                b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
                a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
                d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
                c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
                b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
                a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
                d=GG(d,a,b,c,x[k+10],S22,0x2441453);
                c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
                b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
                a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
                d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
                c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
                b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
                a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
                d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
                c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
                b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
                a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
                d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
                c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
                b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
                a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
                d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
                c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
                b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
                a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
                d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
                c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
                b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
                a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
                d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
                c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
                b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
                a=II(a,b,c,d,x[k+0], S41,0xF4292244);
                d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
                c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
                b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
                a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
                d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
                c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
                b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
                a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
                d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
                c=II(c,d,a,b,x[k+6], S43,0xA3014314);
                b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
                a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
                d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
                c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
                b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
                a=AddUnsigned(a,AA);
                b=AddUnsigned(b,BB);
                c=AddUnsigned(c,CC);
                d=AddUnsigned(d,DD);
        }

        var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);

        return temp.toLowerCase();
}

//change the opacity for different browsers
function us_changeOpac(opacity, id) {
         var object = document.getElementById(id).style;
         object.opacity = (opacity / 100);
         object.MozOpacity = (opacity / 100);
         object.KhtmlOpacity = (opacity / 100);
         object.filter = "alpha(opacity=" + opacity + ")";
}

function opacity(id, opacStart, opacEnd, millisec) {
         //speed for each frame
         var speed = Math.round(millisec / 100);
         var timer = 1;
         //determine the direction for the blending, if start and end are the same nothing happens
  if(opacStart > opacEnd) {
              for(var i = opacStart; i >= opacEnd; i--) {
                    window.setTimeout(function(b) { return function() { us_changeOpac(b, id); } }(i),(timer * speed));
                    timer++;
               }
         }
         else if(opacStart < opacEnd) {
   for(var i = opacStart; i <= opacEnd; i++) {
                    window.setTimeout(function(b) { return function() { us_changeOpac(b, id); } }(i),speed*timer);
                    timer++;
  }
  }
}

//
// http://www.somacon.com/p355.php
//

String.prototype.trim = function() {
 return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
 return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
 return this.replace(/\s+$/,"");
}


/*thanks to Richard Gibson for userscript updates checker script http://userscripts.org/scripts/show/2296*/


var SCRIPT = {
  name: "youscrobble (new YT)"
 ,namespace: "http://userscripts.org/users/xanadus"
 ,source: "http://userscripts.org"      // script homepage/description URL
   + "/scripts/show/71606"
 ,identifier: "http://userscripts.org"  // script URL
   + "/scripts/source/71606.user.js"
 ,meta: "http://userscripts.org"        // metadata URL
   + "/scripts/source/71606.meta.js"
 ,version: "0.2"                        // version
 ,date: "2011-03-14"                    // update date
};

var UPDATE = SCRIPT.namespace + ' ' + SCRIPT.identifier;
try {
 GM_setValue(UPDATE, 1);
 if (GM_getValue(UPDATE)) {
  UPDATE = {key: UPDATE, get: GM_getValue, set: GM_setValue};
 }
 else {
  throw {};
 }
}
catch(x){
 UPDATE = {
   set: function(key, value){ try{ localStorage.setItem(key, value); }catch(x){} }
  ,get: function(key, varDefault) {
   try {
    var stored = localStorage.getItem(key);
    if(stored===null){ return varDefault; }
    return stored;
   }
   catch(x) {
    return varDefault;
   }
  }
 };
}
UPDATE = {
  SCRIPT: SCRIPT
 ,defaults: {checkDays: 3, version: SCRIPT.version, date: SCRIPT.date, name: SCRIPT.name,
   lastCheck: typeof(GM_xmlhttpRequest)!='undefined' ? 0 : (new Date()).getTime()}
 ,getValue: UPDATE.get
 ,setValue: UPDATE.set
 ,HttpRequest: (typeof(GM_xmlhttpRequest)!='undefined' && GM_xmlhttpRequest) || function(){}
 ,ready: false
 ,init: function() {
  if(this.ready){ return; }
  this.ready = true;
   for (var name in this.defaults) {
    if(name in this){ delete this.defaults[name]; }
    else{ this[name] = this.getValue('_UPDATE_' + name, this.defaults[name]); }
   }
   for (var p in {checkDays:0, lastCheck:0}) { delete this.defaults[p]; }
 }
 ,check: function(fnOnNewer, fnIsNewer, blnForce) {
  this.init();
  var interval = Math.max(parseFloat(this.checkDays) * 24 * 60 * 60 * 1000, 0) || Infinity;
  var diff = (new Date()) - parseInt(this.lastCheck,10);
  if(!blnForce && !this.isNewer(this, this.SCRIPT, fnIsNewer) && !(diff > interval)){ return false; }
  if (blnForce || (diff > interval)) {
   var t = this;
   return this.HttpRequest({method: 'GET', url: this.SCRIPT.meta || this.SCRIPT.identifier, onload: function(r){
    t.setValue('_UPDATE_' + 'lastCheck', t.lastCheck = '' + (new Date()).getTime());
    t.parse(r.responseText, [fnOnNewer, fnIsNewer, false]);
   }});
  }
  try{ fnOnNewer(this, this.SCRIPT); }catch(x){}
 }
 ,parse: function(strResponse, arrCheckArgs) {
  var re = /\/\/\s*(?:@(\S+)\s+(.*?)\s*(?:$|\n)|(==\/UserScript==))/gm, match = true, name;
  while (match && (match = re.exec(strResponse))) {
   if(match[3]){ match = null; continue; }
   name = match[1];
   if(name in this.defaults){ this.setValue('_UPDATE_' + name, this[name] = match[2]); }
  }
  this.check.apply(this, arrCheckArgs || []);
 }
 ,isNewer: function(objUpdate, objScript, fnIsNewer) {
  if(!objUpdate){ objUpdate = this; }
  if(!objScript || (objUpdate.date > objScript.date)){ return true; }
  try {
   return fnIsNewer(objUpdate, objScript);
  }
  catch (x) {
   return (!(objUpdate.date < objScript.date) && (objUpdate.version != objScript.version));
  }
 }
};
var UNSAFE = ((typeof unsafeWindow) != 'undefined'
 ? unsafeWindow
 : ((typeof window) != 'undefined'
  ? window
  : (function(){return this;})()
 )
);

function showUpdate(objUpdate, objScript) {
 if(UNSAFE.self !== UNSAFE.top){ return; }
 if(arguments.length < 2){ return UPDATE.check(arguments.callee); }
 var title = objUpdate.name + ' ' + objUpdate.version + ', released ' + objUpdate.date;
 var style = [
   'position:absolute; position:fixed; z-index:9999;'
  ,'bottom:0; right:0;'
  ,'border:1px solid black; padding:2px 2px 2px 0.5ex;'
  ,'background:#dddddd; font-weight:bold; font-size:small;'
 ].join(' ');
 document.body.appendChild($E('div', {title: title, style: style}
  ,$E('a', {href: objScript.source, style: 'color:blue;'}, objScript.name + ' ')
  ,$E('a', {href: objScript.identifier, style: 'color:red;'}, 'updated!')
  ,$E('button', {onclick: 'return this.parentNode.parentNode.removeChild(this.parentNode) && false;',
    style: 'margin-left:1ex;font-size:50%;vertical-align:super;'}, '\u2573')
 ));
}

var $E = function createElement (strName, objAttributes, varContent /*, varContent, ...*/) {
    var el = document.createElement(strName);
    try{
        for (var attribute in objAttributes) {
            el.setAttribute(attribute, objAttributes[attribute]);
        }
    }catch(x){}
    if (arguments.length > 3 || (!/^(string|undefined)$/.test(typeof(varContent)) && !(varContent instanceof Array))) {
     varContent = Array.prototype.slice.call(arguments, 2);
    }
    if (varContent instanceof Array) {
        for (var L = varContent.length, i = 0, c; i < L; i++) {
            c = varContent[i];
            el.appendChild(c && typeof(c) == 'object' && 'parentNode' in c
              ? c : document.createTextNode(c));
        }
    }
    else if (varContent) {
     el.innerHTML = varContent;
    }
    return el;
}

window.addEventListener("load", showUpdate, true);
/**/




//
//Thanx to Crosbow for original Code
////////////////////////////////////

Continue reading...

Mouseover Popup Image Viewer


// ==UserScript==
// @id             org.userscripts.users.kuehlschrank.MouseoverPopupImageViewer
// @name           Mouseover Popup Image Viewer
// @description    Adds floating full-size previews to thumbnails. Can bypass hotlink protections.
// @version        2012.3.14
// @author         kuehlschrank
// @homepage       http://userscripts.org/scripts/show/109262
// @icon           http://s3.amazonaws.com/uso_ss/icon/109262/large.png
// @updateURL      https://userscripts.org/scripts/source/109262.meta.js
// @include        http*
// @exclude        http*imgur.com/a/*
// ==/UserScript==

var hosts = [
 {r:/500px\.com\/photo\//, q:'#mainphoto'},
 {r:/depic\.me\//, q:'#pic'},
 {r:/deviantart\.com\/art\//, q:'#gmi-ResViewSizer_img'},
 {r:/fastpic\.ru\/view\//, q:'#image'},
 {r:/fbcdn\.net\/.+\.jpg($|\?)/, xhr:true},
 {r:/flickr\.com\/photos\/([0-9]+@N[0-9]+|[a-z0-9-_]+)\/([0-9]+)/, s:'http://www.flickr.com/photos/$1/$2/sizes/l/', q:'#allsizes-photo > img'},
 {r:/google\.[a-z.]+\/.+imgurl=(.+?\.(png|gif|jpe?g))/i, s:'$1'},
 {r:/hotimg\.com\/image\/([a-z0-9]+)/i, s:'http://www.hotimg.com/direct/$1'},
 {r:/imagearn\.com\/image/, q:'#img', xhr:true},
 {r:/imagefap\.com\/(image|photo)/, q:'#gallery + noscript'},
 {r:/imagebam\.com\/image\//, q:'img[id]', xhr:true},
 {r:/imageban\.ru\/show/, q:'#img_obj'},
 {r:/imagebunk\.com\/image/, q:'#img_obj', xhr:true},
 {r:/imagehaven\.net\/img\.php/, q:'#image'},
 {r:/imagehyper\.com\/img\.php/, q:'img[src*="imagehyper.com/img"]', xhr:true},
 {r:/imagerise\.com\/show/, q:'#img_obj', xhr:true},
 {r:/imageshack\.us\/(i|photo)\//, q:'#main_image'},
 {r:/imageshost\.ru\/photo\//i, q:'#bphoto'},
 {r:/imagetwist\.com\/[a-z0-9]+\/?(.+\.html)?/, q:'img.pic', xhr:true},
 {r:/imageupper\.com\/i\//, q:'#img', xhr:true},
 {r:/imagepix\.org\/image\/(.+)\.html$/, s:'http://imagepix.org/full/$1.jpg', xhr:true},
 {r:/imageporter\.com\/i\//, xhr:true},
 {r:/imagevenue\.com\/img\.php/, q:'#thepic'},
 {r:/imagewaste\.com\/pictures\/(.+)/, s:'http://www.imagewaste.com/pictures/big/$1', xhr:true},
 {r:/imagezilla\.net\/show\/(.+\.jpg)$/, s:'http://imagezilla.net/images/$1', xhr:true},
 {r:/(imgchili|hoooster)\.com\/show/, q:'#show_image', xhr:true},
 {r:/imgdepot\.org\/show\/(.+\.jpg)/, s:'http://imgdepot.org/images/$1', xhr:true},
 {r:/imgtheif\.com\/image\//, q:'a > img[src*="/pictures/"]'},
 {r:/imgur\.com\/(gallery\/|[a-z0-9]+#)?([a-z0-9]{5,}[^\.]*$)/i, s:'http://i.imgur.com/$2.jpg'},
 {r:/itmages\.ru\/image\/view\//, q:'#image'},
 {r:/listal\.com\/viewimage\/([0-9]+)/, s:'http://www.listal.com/viewimage/$1h', q:'center img'},
 {r:/memegenerator\.net\/instance\/([0-9]+)/, s:'http://images.memegenerator.net/instances/500x/$1.jpg'},
 {r:/(min\.us|minus\.com)\/l([a-z0-9]+)$/i, s:'http://i.min.us/i$2.jpg'},
 {r:/myphoto\.to\/view\/(.+)/, s:'http://img.myphoto.to/$1'},
 {r:/photosex\.biz\/.+?id=([a-z0-9]+)/i, s:'http://img.photosex.biz/pic_b/$1.jpg', xhr:true},
 {r:/(pic4all\.eu\/|^)(images\/|view\.php\?filename=)(.+)/, s:'http://www.pic4all.eu/images/$3'},
 {r:/(picszone\.net|myadultimage\.com|fotoshare\.org|badimg\.com)\/viewer\.php\?file=(.+)/, s:'http://$1/images/$2', xhr:true},
 {r:/picturescream\.com\/\?v=/, q:'#imagen img'},
 {r:/pimpandhost\.com\/(image|guest)\//, q:'#image'},
 {r:/pixhost\.org\/show\//, q:'#show_image', xhr:true},
 {r:/pixroute\.com\/.+\.html$/, q:'img[id]', xhr:true},
 {r:/postimage\.org\/image\//, q:'center  img'},
 {r:/(qkme\.me|quickmeme\.com\/meme)\/([a-z0-9]+)/i, s:'http://i.qkme.me/$2.jpg'},
 {r:/radikal\.ru\/.+\.html$/, q:'div > div > img'},
 {r:/r70\.info\/viewer\.php\?file=(.+)/, s:'http://r70.info/images/$1'},
 {r:/sharenxs\.com\/view\//, q:'#img1', xhr:true},
 {r:/image\.skins\.be\/[0-9]+\//, q:'#wallpaper_image'},
 {r:/stooorage\.com\/show\//, q:'#page_body div div img', xhr:true},
 {r:/turboimagehost\.com\/p\//, q:'#imageid', xhr:true},
 {r:/twitpic\.com\/[a-z0-9]+$/i, q:'#photo-display', xhr:true},
 {r:/uppix\.net\/([0-9a-z\/]+)\.html$/i, s:'http://uppix.net/$1.jpg'},
 {r:/wikipedia\.org\/(wiki\/.+:|w\/.+title=).+\.(jpe?g|gif|png|svg)/i, q:'#file img'},
 {r:/winimg\.com\/view/, q:'#image_container img'},
 {r:/yfrog\.com\/(z\/)?[a-z0-9]+$/i, q:'#main_image, #the-image img'},
 {r:/^[^\?]+\.(jpe?g|gif|png)($|\?)/i}
];

function prepareLinks(parent) {
 var list = document.evaluate(cfg.thumbsonly ? './/a[img or */img]' : './/a', parent, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
 for(var i = list.snapshotLength; i--;) {
  prepareLink(list.snapshotItem(i));
 }
}

function prepareLink(a) {
 a.addEventListener('mouseover', onMouseOver, false);
}

function activateLink(a) {
 return hosts.some(function(host) {
  deactivateLink();
  var m = host.r.exec(a.href);
  if(!m || host.r.test(window.location.href)) return false;
  var url = host.hasOwnProperty('s') ? replace(host.s, m) : a.href;
  var pos = url.lastIndexOf('http:');
  var img = a.querySelector('img');
  cur = {
   link: a,
   url: pos > 0 ? url.substr(pos) : url,
   q: host.q,
   xhr: host.xhr,
   rect: img ? img.getBoundingClientRect() : a.getBoundingClientRect(),
   cw: Math.min(window.innerWidth,  document.documentElement.clientWidth)  - 2,
   ch: Math.min(window.innerHeight, document.documentElement.clientHeight) - 2,
   t: Date.now()
  }
  document.addEventListener('mousemove', onMouseMove, false);
  document.addEventListener('mousedown', onMouseDown, false);
  document.addEventListener('contextmenu', onContext, false);
  document.addEventListener('keyup', onKeyUp, false);
  document.addEventListener('DOMMouseScroll', deactivateLink, false);
  document.addEventListener('mousewheel', deactivateLink, false);
  document.addEventListener('mouseout', onMouseOut, false);
  return true;
 });
}

function deactivateLink(e) {
 window.clearTimeout(cur.timeout);
 if(cur.req && typeof cur.req.stop == 'function') cur.req.stop();
 if(cur.link)
  cur.link.style.cursor = '';
 cur = {};
 document.removeEventListener('mousemove', onMouseMove, false);
 document.removeEventListener('mousedown', onMouseDown, false);
 document.removeEventListener('contextmenu', onContext, false);
 document.removeEventListener('keyup', onKeyUp, false);
 document.removeEventListener('DOMMouseScroll', deactivateLink, false);
 document.removeEventListener('mousewheel', deactivateLink, false);
 document.removeEventListener('mouseout', onMouseOut, false);
 setStatus(false);
 setPreview(false);
}

function onMouseOver(e) {
 if(e !== false) {
  if(!e.shiftKey && this != cur.link && !cur.full && activateLink(this)) {
   cur.timeout = delay(onMouseOver, cfg.delay, false);
   cur.cx = e.clientX;
   cur.cy = e.clientY;
  }
  return;
 }
 setStatus(cur.xhr ? 'xhr' : 'loading');
 placeStatus();
 if(cur.q) {
  downloadPage(rel2abs(cur.url, window.location.href), cur.q, cur.xhr, cur.t);
 } else {
  if(cur.xhr) {
   downloadImage(cur.url, cur.url, cur.t);
  } else {
   setPreview(cur.url);
   checkProgress(true);
  }
 }
}

function onMouseMove(e) {
 if(e.shiftKey) {
  return;
 }
 var r = cur.rect;
 if(!cur.full && (e.clientX > r.right || e.clientX < r.left || e.clientY > r.bottom || e.clientY < r.top)) {
  deactivateLink();
  return;
 }
 cur.cx = e.clientX;
 cur.cy = e.clientY;
 placeStatus();
 placePreview();
}

function onMouseDown(e) {
 if(e.which != 3) setPreview(false);
}

function onMouseOut(e) {
 if(!e.relatedTarget) deactivateLink();
}

function onKeyUp(e) {
 if(e.keyCode == 9 && !e.ctrlKey) {
  deactivateLink();
  setup();
 } else if(e.keyCode == 16) {
  toggleFull();
 } else {
  setPreview(false);
 }
}

function onContext(e) {
 if(cfg.context && !e.shiftKey && getPreview() && !getStatus() && toggleFull()) {
  e.preventDefault();
 } else {
  setPreview(false);
  deactivateLink();
 }
}

function onNodeInserted(e) {
 var t = e.target;
 switch(t.tagName) {
  case 'A':
   if(!t.firstChild) break;
   if(!cfg.thumbsonly || t.firstChild.tagName == 'IMG' || t.firstChild.firstChild && t.firstChild.firstChild.tagName == 'IMG')
    prepareLink(t);
   break;
  case 'IMG':
   if(t.parentNode.tagName == 'A')
    prepareLink(t.parentNode);
   else if(t.parentNode.parentNode && t.parentNode.parentNode.tagName == 'A')
    prepareLink(t.parentNode.parentNode);
   break;
  default:
   prepareLinks(t);
 }
}

function downloadPage(url, q, xhr, t) {
 cur.req = GM_xmlhttpRequest({
  method: 'GET',
  url: url,
  ignoreCache: true,
  onload: function(req) {
   try {
    var node = GM_safeHTMLParser(req.responseText).querySelector(q);
    if(!node) throw 'No results for "' + q + '" at ' + url;
    var iurl = rel2abs(node.tagName.toUpperCase() == 'IMG' ? node.getAttribute('src').trim() : node.innerHTML.match(/http:\/\/[.\/a-z0-9_+%-]+\.(jpe?g|gif|png)/i)[0], url);
    if(!iurl) throw 'Image URL not found';
    if(cur.t != t) return;
    if(xhr) {
     downloadImage(iurl, url, t);
    } else {
     setPreview(iurl);
     checkProgress(true);
    }
   } catch(ex) {
    showError(ex, t);
   }
  }
 });
}

function downloadImage(url, referer, t) {
 cur.req = GM_xmlhttpRequest({
  method: 'GET',
  url: url,
  overrideMimeType:'text/plain; charset=x-user-defined',
  headers: {'Accept':'image/png,image/*;q=0.8,*/*;q=0.5','Referer':referer},
  onload: function(req) {
   try {
    if(cur.t != t) return;
    var data = '';
    for(var i = 0, len = req.responseText.length; i < len; i++) {
     data += String.fromCharCode(req.responseText.charCodeAt(i) & 0xff);
    }
    setPreview('data:;base64,' + window.btoa(data));
    checkProgress(true);
   } catch(ex) {
    showError(ex, t);
   }
  }
 });
}

function checkProgress(start) {
 if(start === true) {
  window.clearInterval(checkProgress.interval);
  checkProgress.interval = window.setInterval(checkProgress, 150);
  return;
 }
 var img = getPreview();
 if(!img) {
  window.clearInterval(checkProgress.interval);
  return;
 }
 if(img.naturalHeight) {
  setStatus(false);
  window.clearInterval(checkProgress.interval);
  img.style.display = '';
  placePreview();
  if(img.naturalWidth > img.clientWidth || img.naturalHeight > img.clientHeight) {
   img.style.cursor = 'all-scroll';
   cur.link.style.cursor = 'all-scroll';
  }
 }
}

function placePreview() {
 var img = getPreview();
 if(!img) return;
 var cx = cur.cx, cy = cur.cy;
 var cw = cur.cw, ch = cur.ch;
 if(cur.full) {
  img.style.maxWidth = null;
  img.style.maxHeight = null;
  img.style.left = (cw > img.naturalWidth  ? cw/2 - img.naturalWidth/2  : -1 * Math.min(1, Math.max(0, 5/3*(cx/cw-0.2))) * (img.naturalWidth - cw)) + 'px';
  img.style.top  = (ch > img.naturalHeight ? ch/2 - img.naturalHeight/2 : -1 * Math.min(1, Math.max(0, 5/3*(cy/ch-0.2))) * (img.naturalHeight - ch)) + 'px';
 } else {
  img.style.maxWidth  = cw + 'px';
  img.style.maxHeight = ch + 'px';
  var w = img.clientWidth;
  var h = img.clientHeight;
  img.style.left = Math.min(cw - w, Math.max(0, cx + (w && cx > cw/2 ? -w -30 : 30))) + 'px';
  img.style.top  = Math.min(ch - h, Math.max(0, cy + (h && cy > ch/2 ? -h -30 : 30))) + 'px';
 }
}

function placeStatus() {
 var img = getStatus();
 if(img) {
  img.style.left = cur.cx + 30 + 'px';
  img.style.top  = cur.cy + 30 + 'px';
 }
}

function toggleFull() {
 var img = getPreview();
 if(!img || !img.naturalHeight)
  return;
 img.style.cursor = '';
 if(cur.link)
  cur.link.style.cursor = '';
 cur.full = !cur.full && (img.naturalWidth > cur.cw || img.naturalHeight > cur.ch);
 onMouseMove({clientX:cur.cx,clientY:cur.cy});
 return cur.full;
}

function showError(ex, t) {
 if(t && t != cur.t) return;
 setStatus('error');
 GM_log(ex);
}

function getStatus() {
 return document.getElementById('mpiv-status');
}

function setStatus(status) {
 var img = getStatus();
 if(!img && !status) return;
 if(!img) {
  img = document.createElement('img');
  img.id = 'mpiv-status';
  img.style.cssText = 'display:none;border:1px solid black;background-color:white;position:fixed;z-index:10000;margin:0';
  document.body.appendChild(img);
 }
 if(status) {
  var srcs = {
   loading:'data:image/gif;base64,R0lGODlhKAAoALMAAEeJxkfGzInG/wBHiQBHxsb//YmJxgAAkgCJvP/G+P//xomJ/4nGxsbGxsbG/////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQEDQAAACwAAAAAKAAoAAAE//DJSau9OOvNu/9gKF7GsIziQAxVg1KMUQ0HQTmM8D4OMgAU1WFSaAhcO9VAJznQJsaGY/cwrGzNlcQRpUqUsgeNxWM4Ct4H44oW8hpmipTBWQ/oE8BKlqAUphJFR0cbBggEBAB4a2EZcziAGwAqhwCRGlGEHwyTKwgdXAx9IoYESByXIjhprBVmOXBcGEYGAAacjR2vkHEkira1TB6ZcxkCMQACtkCtzamqw2bPHUUMaKivDdfURqEevLIcUbAbcDCQ0zfdp28WkOxcAgobgvDSD3B4kNs78UgC4fylMSNFwqsJ6Kg4gAQFIBE47EZE2YYD3qodBM/hQejlTwuHzQwwFOEXsqTJkyhHRAAAIfkEBA0AAAAsBAAEACAAIAAABP/wyUkpI63qzScgQAU4neZkFDEgiTcMJVUYI7XC0jUQMWUEhsKEQEAMd4bexEFLShBEyWentPxIDxWvsBsIKsKSgwEIPm4PgyrkOjCWDQZWYiDPJ+r3g7E7EJwPBWMnYTNfHQ4IBwOLPBQNg3JhMYwEfndwAg1xSmoDgByCAi1KNT0NkzGpVaxyDK6QkK5jKFWzs5GymDENmppjgbqurMTFu4hVcQ7HFCd6HWG5qxInArRVg7EVvcrME5wTrtbf2ZNyJtpwDpMFvamDQsMPvsUPuhLcEu3nxNxY8g/G8FNSrdagJdVaAQu3kBqDWqfGLRmojxRBBRXkQKzHgYHFGBEBAAAh+QQEDQAAACwIAAQAHAAgAAAE8vDJSR1zNOs9mc9Mwk1OkRkLQxkMMD5F02Ads5AGoL7WPKWGiSGQej0sjkZNIGGwXMZHQ8AwPQysow1gnXQphWTyQQ06hkEhYkCjSaY70E3iWBMIu6RV/GoABgRrUA8XMl8ja4JuUlRjUQYIBGkZSQKLLwaHYCJRnQ8KnhKAo4AsU5dGowSqSRehD6uxgBcCDXGvuBwGqBWefwOTFbaaGwMHBMeTrQ4WnQ6rA6MStY1GzRIGq8mEjm+ott1X0UwCX0gmF3kXxBozrlo0Me9GUz7ccT28wrUT9SRIRtJRoCbs1oZTFPxtMlKAU4dwuSgYfBEBACH5BAQNAAAALAwABAAcACAAAATh8MnpWpk4691Ey86mXZjDhFPHiFiDSucqFY3LTowtdd8uVDcYUCiQOEyvm4pk+lQ8JMqm8Ew8Yg/aqWUS8aKTRNHI82QUj0pS4yr3MmAWcusN7rq3NYtq7/v/DwYMAAaEDDKAEoQAg4MLiRMGAQaSgnqQmBkGcSB+DAQIBiwMnBsEAwgDjBt4QQUAAwSgAFYtQQYDDmgCsKeIGToYuAQAwggEvxQnFwMHA1mxuX1PPQcEBxIGpwR9PCix2BKnA6J5PBPN3DCyzzdYE9ftirGlKT8Y4JrJI7Xo1pkZFgzYZycCACH5BAQNAAAALAYAEgAhABUAAASo8Emppr2WNeYYbxOnCQ5mTo7QqF0ptZt7YrHoFCinMnPv/6Yb8OEADBsNB8hnGBwMOJ/AJrswBgMC9qhiVSzZA0FcpQGij48A/QA4tQtJg2DAMAx4i1KZOQygE24ERgMIA0QMABw/ZQxaAzhaBC8GikNgBHQShZMSdwBlTIadD4YIKAGVlw9ZAzKSGQYBq1pGEwSGFw6hPXcXAIOrQwJ/q1/CyMnKyccRACH5BAQNAAAALAQADAAfABgAAATJ8LFxzLuviVYwTgLmaORlEANqPaPjvdm4bR56oIQLww7T66/TYUDcwRo9I0a4UmIKQGXSSa1aGQ0fw2cgDikEq2iGnHzP4kv2x7URboO0XO6IGh1NagPZUTIICAtWAlp1MAwABIBhViQbDgoYiQMIAwB2L1kJfWUOfQaVBAAhGQYMLwoOjx4yCRd/CHkMBoQSGg8FJH13L3gABh0/FzINcgYBtK9TLBqYRrMCACI+GCTFVga/u2ust9gBUT3XT5BWy8qkc0oJp1YRADs=',
   xhr:'data:image/gif;base64,R0lGODlhKAAoALMAAEeJxkfGzInG/wBHiQBHxsb//YmJxgAAkgCJvP/G+P//xomJ/4nGxsbGxsbG/////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQEHgAAACwAAAAAKAAoAAAE//DJSau9OOvNu/9gKF7GsIziQAxVg1KMUQ0HQTmM8D4OMgAU1WFSaAhcO9VAJznQJsaGY/cwrGzNlcQRpUqUsgeNxWM4Ct4H44oW8hpmipTBWQ/oE8BKlqAUphJFR0cbBggEBAB4a2EZcziAGwAqhwCRGlGEHwyTKwgdXAx9IoYESByXIjhprBVmOXBcGEYGAAacjR2vkHEkira1TB6ZcxkCMQACtkCtzamqw2bPHUUMaKivDdfURqEevLIcUbAbcDCQ0zfdp28WkOxcAgobgvDSD3B4kNs78UgC4fylMSNFwqsJ6Kg4gAQFIBE47EZE2YYD3qodBM/hQejlTwuHzQwwFOEXsqTJkyhHRAAAIfkEBB4AAAAsBAAEACAAIAAABP/wyUkpI63qzScgQAU4neZkFDEgiTcMJVUYI7XC0jUQMWUEhsKEQEAMd4bexEFLShBEyWentPxIDxWvsBsIKsKSgwEIPm4PgyrkOjCWDQZWYiDPJ+r3g7E7EJwPBWMnYTNfHQ4IBwOLPBQNg3JhMYwEfndwAg1xSmoDgByCAi1KNT0NkzGpVaxyDK6QkK5jKFWzs5GymDENmppjgbqurMTFu4hVcQ7HFCd6HWG5qxInArRVg7EVvcrME5wTrtbf2ZNyJtpwDpMFvamDQsMPvsUPuhLcEu3nxNxY8g/G8FNSrdagJdVaAQu3kBqDWqfGLRmojxRBBRXkQKzHgYHFGBEBAAAh+QQEHgAAACwIAAQAHAAgAAAE8vDJSR1zNOs9mc9Mwk1OkRkLQxkMMD5F02Ads5AGoL7WPKWGiSGQej0sjkZNIGGwXMZHQ8AwPQysow1gnXQphWTyQQ06hkEhYkCjSaY70E3iWBMIu6RV/GoABgRrUA8XMl8ja4JuUlRjUQYIBGkZSQKLLwaHYCJRnQ8KnhKAo4AsU5dGowSqSRehD6uxgBcCDXGvuBwGqBWefwOTFbaaGwMHBMeTrQ4WnQ6rA6MStY1GzRIGq8mEjm+ott1X0UwCX0gmF3kXxBozrlo0Me9GUz7ccT28wrUT9SRIRtJRoCbs1oZTFPxtMlKAU4dwuSgYfBEBACH5BAQeAAAALAwABAAcACAAAATh8MnpWpk4691Ey86mXZjDhFPHiFiDSucqFY3LTowtdd8uVDcYUCiQOEyvm4pk+lQ8JMqm8Ew8Yg/aqWUS8aKTRNHI82QUj0pS4yr3MmAWcusN7rq3NYtq7/v/DwYMAAaEDDKAEoQAg4MLiRMGAQaSgnqQmBkGcSB+DAQIBiwMnBsEAwgDjBt4QQUAAwSgAFYtQQYDDmgCsKeIGToYuAQAwggEvxQnFwMHA1mxuX1PPQcEBxIGpwR9PCix2BKnA6J5PBPN3DCyzzdYE9ftirGlKT8Y4JrJI7Xo1pkZFgzYZycCACH5BAQeAAAALAYAEgAhABUAAASo8Emppr2WNeYYbxOnCQ5mTo7QqF0ptZt7YrHoFCinMnPv/6Yb8OEADBsNB8hnGBwMOJ/AJrswBgMC9qhiVSzZA0FcpQGij48A/QA4tQtJg2DAMAx4i1KZOQygE24ERgMIA0QMABw/ZQxaAzhaBC8GikNgBHQShZMSdwBlTIadD4YIKAGVlw9ZAzKSGQYBq1pGEwSGFw6hPXcXAIOrQwJ/q1/CyMnKyccRACH5BAQeAAAALAQADAAfABgAAATJ8LFxzLuviVYwTgLmaORlEANqPaPjvdm4bR56oIQLww7T66/TYUDcwRo9I0a4UmIKQGXSSa1aGQ0fw2cgDikEq2iGnHzP4kv2x7URboO0XO6IGh1NagPZUTIICAtWAlp1MAwABIBhViQbDgoYiQMIAwB2L1kJfWUOfQaVBAAhGQYMLwoOjx4yCRd/CHkMBoQSGg8FJH13L3gABh0/FzINcgYBtK9TLBqYRrMCACI+GCTFVga/u2ust9gBUT3XT5BWy8qkc0oJp1YRADs=',
   error:'data:image/gif;base64,R0lGODlhKAAoAOYAANssLOyZmZkDA/oBAbUBAeVqavO2ttgZGffX1/xra+kAAMwzM7apqcYZGdZqavWiov3//+d5efh7e7sjI/hdXfrq6twBAdtAQPf+/qmmpsGcnMSzs65VVeywsOxTU/WLi3onJ9BdXYQtLfWUlHk0NOBGRuY6OpyWlssBAeuMjMC7u++lpe5KSuJbW/H29vTLy/TExOZNTdjLy8EAAOQrK/Cqqr65uc0PD6oTE6grK+xCQuSEhLIZGd08PKAVFbMREZIoKOMzM6KTk8whIfrDw4Q1NW41NawBAX1hYaQNDe3y8rSWlsm0tPf5+cUrK/r8/P719Y1oaJk5Oa1/f99LS+ozM94ICMCZmfn8/NQ1Nfv///JOTs0uLrF8fLwWFq0fH/75+ZV9fek9PeqHh6lhYbOamtE6OqEbG7ANDevv74h0dNk2NtQAANa7u8MhIaEAAPf//62CgrCFhc2vr81UVOhiYt5TU+7BwcIJCc0ICMtISItcXO83N8e/v+OgoP///yH5BAAAAAAALAAAAAAoACgAAAf/gH+Cg4SFhoeIiYqLjItKLo2GaZCRWAxRUX2RgnBXHBxzjVgnIHl4IgyRGF0/fDQ/V4sQJyJWAwp5qIxwrGIlHjqwEIhNJyQWAwYrVjeow4hYXTxVay8rOsFXz4TFJLYjgikWzQzbhBhTPEFcd2BgAVsswoQQDCDII00ICFA740DlCq3CQWNIByj7KoygsOVHG0JpkOQZMKLCCxgwXlSIwOYGQEJw0gFw46cCxowIRiSowgHLICVR8AyQgMCATZsIHKA4AHAYljhfAHgJUPOmgTsfEtAg43KQCiMTE9ypsYJqDSIOZvBkoEVO0B87iKyoWrVDBApicMgo9CQD1AF1/zoEmDvXQAgCB6TsyTEETQQDdOeuKEDBBA4m5gRBcDvRQ4AUYyKneECHwJAvQ5I4eBBZcoo6WwxvSEyI8YAYKSKoVv1BT5LMIT6sVr3DTmgfG2RlIJFHwYUIBYIHl2BGAB0JwoXrYWECd6PFJG4oWFOghXXrdezUuX7dzIUgziNBv2EBgB0q6NF7SE8lRowFPcCP3iQogwjyQ0r02M+/v5M18tE3SD1FNIBCA0EAoOCCCrrBRRY5MCFgIWoAcQBeB2So4QEN8KBDElNMOIgWQliIwgwEpHjEimj8wAMPXPTwhQakMfJEiQdYMAOKR7whwI9J4MDDBBNkkRaN9GEhhP8IOZ7I4xs+ChDkkBM4cYEOaCApihAgWKEAG04S0GOUUxLphBMlYKmlIk+Q4qUFYO4oJpQ+llnlAmYAk2WNg7TZ5QAWwBlmj17QgIYAQpqJ5wUesLAnIn7aokCgcaL4xg1D+ADAD0lQ6cSiJVDgqAZaGFLMnwpMKuiOR2AqRRg5CIWDot6VEEMCo5ZKiD3I3KJqnARgKoIKWpRxRhBuDPlprTF4kMAWaDw0SEQT+frriVYMIYINihkbhBN3MusBBRLw0dJLSMhkLaUoZFsEtwMu4cM6E4DaLLlLPTGgDUaomyqlVrhRhAqGaLHEGSZk4YS4CaS1FiFtGXGDr4Fa0cBbu4gY7IMYPSxwga0JiFajWxNPqkADJBCcCARL4OCLGaE2l1siJA8wgBcpM2JwEjqM25yEi+zmBQ85N7JzFTScATQjfagRxsORaMEEGWRA3YgL+k7YRBMidp1IIAA7'
  };
  img.src = srcs[status];
  img.style.display = '';
 } else {
  img.parentNode.removeChild(img);
 }
}

function getPreview() {
 return document.getElementById('mpiv-preview');
}

function setPreview(src) {
 var img = getPreview();
 if(!img && !src) return;
 if(!img) {
  img = document.createElement('img');
  img.id = 'mpiv-preview';
  img.style.cssText = 'display:none;border:1px solid black;background-color:white;position:fixed;z-index:10000;margin:0;cursor:default';
  img.addEventListener('error', showError, false);
  document.body.appendChild(img);
 }
 if(src) {
  img.src = src;
  img.style.display = 'none';
 } else {
  cur.full = false;
  img.removeEventListener('error', showError, false);
  img.parentNode.removeChild(img);
 }
}

function rel2abs(rel, abs) {
 if(rel.indexOf('//') == 0) rel = 'http:' + rel;
 var re = /^([a-z]+:)?\/\//;
 if(re.test(rel))  return rel;
 if(!re.exec(abs)) return false;
 if(rel[0] == '/') return abs.substr(0, abs.indexOf('/', RegExp.lastMatch.length)) + rel;
 return abs.substr(0, abs.lastIndexOf('/')) + '/' + rel;
}

function replace(s, m) {
 for(var i = m.length; i--;) {
  s = s.replace('$'+i, m[i]);
 }
 return s;
}

function delay(f, t) {
 var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
 return window.setTimeout(function() { f.apply(null, args); }, t);
}

function setup() {
 if(document.getElementById('mpiv-setup')) return;
 var style = document.createElement('style');
 style.appendChild(document.createTextNode('#mpiv-setup { position:fixed;z-index:10001;top:40px;right:40px;padding:20px 30px;background-color:white;width:300px;border:1px solid black } #mpiv-setup * { color:black;text-align:left;line-height:normal;font-size:12px } #mpiv-setup div { text-align:center;font-weight:bold;font-size:14px } #mpiv-setup ul { margin:15px 0 15px 0;padding:0;list-style:none } #mpiv-setup li { margin:0;padding:6px 0;vertical-align:middle; } #mpiv-setup p { background-color:white;color:gray;padding:2px 16px; margin:0; } #mpiv-setup input[type=text] { width: 50px; }'));
 document.getElementsByTagName('head')[0].appendChild(style);
 var div = document.createElement('div');
 div.id = 'mpiv-setup';
 div.innerHTML = '<div>Mouseover Popup Image Viewer</div><ul><li>Popup delay: <input id="mpiv-setup-delay" type="text"/> ms</li><li><input type="checkbox" id="mpiv-setup-thumbsonly"> Restrict popups to thumbnailed links<p>If unchecked, popups are also shown on normal links, i.e. links that don\'t contain a thumbnail.</p></li><li><input type="checkbox" id="mpiv-setup-context"> Use right mouse button to enlarge to full size<p>To access context menu: Right-click before popup is visible or hold down shift while right-clicking.</p></li></ul><div><button id="mpiv-setup-button">Save settings</button></div>';
 document.body.appendChild(div);
 document.getElementById('mpiv-setup-button').addEventListener('click', function() {
  var delay = parseInt(document.getElementById('mpiv-setup-delay').value);
  if(!isNaN(delay) && delay >= 0) GM_setValue('delay', delay);
  GM_setValue('thumbsonly', !!document.getElementById('mpiv-setup-thumbsonly').checked);
  GM_setValue('context', !!document.getElementById('mpiv-setup-context').checked);
  this.disabled = true;
  this.innerHTML = 'Reloading...';
  window.location.reload();
 }, false);
 document.getElementById('mpiv-setup-delay').value = cfg.delay;
 document.getElementById('mpiv-setup-thumbsonly').checked = cfg.thumbsonly;
 document.getElementById('mpiv-setup-context').checked = cfg.context;
}

if(typeof GM_safeHTMLParser != 'function' && typeof document.implementation != 'undefined') {
 function GM_safeHTMLParser(s) {
  var d = document.implementation.createHTMLDocument('MPIV');
  d.documentElement.innerHTML = s;
  return d;
 }
}

var cfg = {delay:GM_getValue('delay', 400), thumbsonly:GM_getValue('thumbsonly', true), context:GM_getValue('context', true)};
var cur = {};
prepareLinks(document);
document.addEventListener('DOMNodeInserted', onNodeInserted, false);

Continue reading...