// BlipFromReader v0.1
// 
// Copyright 2008 Wiktor Gworek (http://blog.mocna-kawa.com)
// 
// Based on Treader from Bob Lee (http://crazybob.org/)
// 
// ==UserScript==
// @name           BlipFromReader
// @namespace      http://blog.mocna-kawa.com
// @description    Możesz blipować bezpośrednio z Google Reader o nowościach. Wybierz nius i naciśniej Shift+B.
// @include        http://www.google.com/reader/*
// ==/UserScript==

function showStatus(status, statusType) {
    var outer = document.getElementById('message-area-outer'), 
        inner = document.getElementById('message-area-inner');
    GM_log(statusType + ': ' + status)
    inner.innerHTML = status;
    outer.className = statusType;
}

function showInfo(txt) {
    showStatus(txt, 'info-message');
}

function showError(txt) {
    showStatus('Błąd: ' + txt, 'error-message')
}

function getLabelForStatus(code) {
    switch (code) {
        case 401: 
            return 'Zły login lub hasło.'
        default:
            return 'Coś złego stało się z Blipem. Spróbuj jeszcze raz.'
    }
}

// Wysyła wiadomość do Blipa.
function postBlip(blip) {
  showInfo('Wysyłam blipa...');
  GM_xmlhttpRequest({
    method: 'POST',
    url: 'http://api.blip.pl/updates.json',
    headers: {
      'X-Blip-api': '0.02',
      'User-Agent': 'BlipReader',
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: 'update[body]=' + encodeURIComponent(blip),
    onload: function(response) {
      if (response.status == 201) {
        showInfo("Blip został wysłany.")
      } else {
        showError(getLabelForStatus(response.status))
      }
    },
    onerror: function(response) {
      showError(response.responseText);
    }
  })
}

// Wydobywa napis z linku tytułowego.
function getLabel(titleLink) {
  return titleLink.firstChild.nodeValue;
}

// Zapytanie używtkonika o tekst blipa.
function promptForBlip(titleLink) {
  var blip = prompt("Tekst blipa: ", getLabel(titleLink) + ": " + titleLink.href);
  if (blip) {
    postBlip(blip);
  }
}

// Wyszukuje aktualny tytuł wiadomości w Google Readerze.
function findCurrentTitleLink() {
  var entry = document.getElementById('current-entry');
  if (entry) {
    var anchors = entry.getElementsByTagName('a');
    for (var i = 0; i < anchors.length; i++) {
      if ("entry-title-link" == anchors[i].className) {
        return anchors[i];
      }    
    }
  }
  return null;
}

// Wysyła blipa, kiedy Shift+B zostanie naciśnięte.
document.addEventListener('keypress', function(event) {
  // Obrona przed innymi kombinacjami z Shiftem
  if (!event.shiftKey || event.metaKey || event.altKey  || event.target.type == "text") {
    return;
  }

  // Shift+B
  if (event.charCode == 66) {
    var titleLink = findCurrentTitleLink();
    if (titleLink) {
      promptForBlip(titleLink);
    }
  }

}, false);


