// ==UserScript==
// @name           See Google Maps/Local view in Panoramio
// @namespace      http://www.lysator.liu.se/~jhs/userscript
// @description    Add a link to Panoramio in the Google Maps/Local page header
// @include        http://local.google.com/*
// @include        http://maps.google.com/*
// ==/UserScript==

if (location.pathname.match(/\//g).length > 1) return; // only root directory
init( document.getElementById( "link" ) );

function init( link ) {
  function mapMoved( event ) {
    if (event.attrName != "href") return; // false alarm
    dest.href = urlFromGURL( event.newValue );
  }

  var dest = link.cloneNode( true );
  dest.removeAttribute( "id" );
  dest.lastChild.innerHTML = "Panoramio";
  dest.href = urlFromGURL( link.href );
  link.parentNode.appendChild( dest );

  link.addEventListener( "DOMAttrModified", mapMoved, false );
}

function urlFromGURL( url ) {
  var dst = "http://www.panoramio.com/";
  var got = url.match( /&ll=([\d.]+),([\d.]+).*/ );
  if (got) {
    dst += "#lt="+ got[1] +"&ln="+ got[2];
    if (got = url.match( /&z=(\d+)/ ))
      dst += "&z="+ got[1];
    if (got = url.match( /&t=(.)/ ))
      dst += "&k="+ ({ k:1, h:2 }[got[1]]);
    else
      dst += "&k=0";
  }
  return dst;
}
