// ==UserScript==
// @name          Gmail wikimail
// @namespace     http://ouseful.open.ac.uk
// @description	  Adds a wikimail toggle button.
// @include       http://mail.google.com/*
// @include       https://mail.google.com/*
// @include       http://mail.googlemail.com/*
// @include       https://mail.googlemail.com/*

// ==/UserScript==
// Mwenu option code reused from http://userscripts.org/scripts/show/2431

// Utility functions
function getObjectMethodClosure(object, method) {
  return function() {
    return object[method].apply(object, arguments);
  }
}

// Shorthand
var newTextNode = getObjectMethodClosure(document, "createTextNode");
var newNode = getObjectMethodClosure(document, "createElement");
var getNode = getObjectMethodClosure(document, "getElementById");

// Contants
const TOGGLE_FONT_IMAGE = "data:image/gif;base64,R0lGODlhEAAQAIABAAAAzP%2F%2" +
   "F%2FyH5BAEAAAEALAAAAAAQABAAAAImjI%2BJwO28wIGG1rjUlFrZvoHJVz0SGXBqymXphU5" +
   "Y17Kg%2BnixKBYAOw%3D%3D";

// Globals
var showWiki=false;
var wikimailLink = null;

function initializeWikimail() {
  var linksContainer = getNode("ap");
  
  if (!linksContainer) {
    return;
  }

  wikimailLink = newNode("div");
  wikimailLink.className = "ar";
  wikimailLink.addEventListener("click", wikimail, false);
  wikimailLink.innerHTML =
    '<span class="l">' +
      '<img class="ai" width="16" height="16" src="' + TOGGLE_FONT_IMAGE + '">' +
      '<u>Show/hide wikimail</u>' +
    '</span>';

  linksContainer.appendChild(wikimailLink);
  
  checkToggleFontParent();
}

var wikimailText='';

function initWikimailCreate(){
//inspired by http://userscripts.org/scripts/show/4138
  var composeEditBar = getNode('sp_compose');
  if (!composeEditBar) return;
  
  var wikiName=newNode('input');
  wikiName.setAttribute('size',40);
  wikiName.setAttribute('type','text');
  wikiName.setAttribute('id','wmName');
  var el = newNode('span');
  var txt = newTextNode('Create wikimail');
  el.appendChild(txt);
  
  el.setAttribute('style', 'color:#0000CC; background-color:#C3D9FF; margin-right:10px;font-weight:bold; font-style:underline; border:0px; cursor:pointer; text-decoration:underline;');
  el.addEventListener('click', wikimailCreate,false);
  
  var reset=newNode('span');
  var parentDiv = composeEditBar.parentNode; 
  parentDiv.insertBefore(wikiName,composeEditBar);
  parentDiv.insertBefore(el, composeEditBar);
}

function wikimailCreate(){
//alert('boo');
 var iframe = document.getElementById('hc_compose');
 var wikiframe = newNode('iframe');
 
 var wikiName=document.getElementById('wmName').value;
 
 var wikipath='';var wikidomain='';
 var slashed=wikiName.indexOf('/');
 if (slashed!=-1) {wikidomain=wikiName.substring(0,slashed);wikipath=wikiName.substring(slashed);} else wikidomain=wikiName;
 wikiURL='http://'+wikidomain+'.com'+wikipath;
 wikiframe.setAttribute('src',wikiURL);
 wikiframe.setAttribute('style','width:800px;height:600px;background:white');
 iframe.parentNode.insertBefore(wikiframe,iframe);
 iframe.contentDocument.body.innerHTML='wikimail:'+wikiName;

}


function wikimailShowWiki() {
    const urlRegex = /\b(wikimail:([^\s+\"\<\>]+))/ig;
    var allowedParents = ["body","div","blockquote"];
    var xpath = "//text()[(parent::" + allowedParents.join(" or parent::") + ") and " +
                "contains(translate(., 'WIKIMAIL', 'wikimail'), 'wikimail')]";

    var candidates = document.evaluate(xpath, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

    for (var cand = null, i = 0; (cand = candidates.snapshotItem(i)); i++) {

        if (urlRegex.test(cand.nodeValue)) {
            var iframe = document.createElement("iframe");
            iframe.setAttribute("id","wmFrm");

            var source = cand.nodeValue;
            
            cand.parentNode.replaceChild(iframe, cand);

            urlRegex.lastIndex = 0; var wikidomain=''; var wikipath=''; var wikisrc=''; var slashed;
            for (var match = null, lastLastIndex = 0; (match = urlRegex.exec(source)); ) {
                iframe.setAttribute('style','width:800px;height:600px');
                wikipath='';wikidomain='';
                wikisrc=match[2]; slashed=wikisrc.indexOf('/');
                if (slashed!=-1) {wikidomain=wikisrc.substring(0,slashed);wikipath=wikisrc.substring(slashed);} else wikidomain=wikisrc;
                wikiURL='http://'+wikidomain+'.com'+wikipath;
                //alert(wikiURL);
				iframe.setAttribute('src',wikiURL);
                lastLastIndex = urlRegex.lastIndex;
                wikimailText=match[0];
            }
        }
    }
    showWiki=true;
 }
 
 function wikimailHideWiki(){
  var replaceNode=getNode("wmFrm");
  var txtNode=newTextNode(wikimailText);
  replaceNode.parentNode.replaceChild(txtNode, replaceNode);
  showWiki=false;
 }
 
 function wikimail(){
    if (showWiki) {
     wikimailHideWiki();
    } else {
     wikimailShowWiki();
   }
}

function checkToggleFontParent() {
  if (wikimailLink.parentNode != getNode("ap")) {
    getNode("ap").appendChild(wikimailLink);
  }
  
  window.setTimeout(checkToggleFontParent, 200);
}

initializeWikimail();
initWikimailCreate();
