// ==UserScript==
// @name                Hodnocení keší
// @namespace	        http://www.me2d09.cz/GM/
// @description	        přidává do stránek geocaching.com políčko pro hodnocení keší na geocaching.cz
// @include		http://www.geocaching.com/seek/cache_details.aspx*
// ==/UserScript==

//nastaveni
if (GM_getValue("user") == undefined)
{
  var usr = prompt("Toto je poprvé co používáte hodnocení keší. Zadejte své přihlašovací jméno na geocaching.cz","jmeno");
  if (usr == null)
    alert("Script teď nebude správně fungovat");
  else
    GM_setValue("user", usr);

  var pass = prompt("Pokud chcete uložit heslo, zadejte ho, jinak stiskněte storno. POZOR: ukládání hesla není bezpečné!","heslo");
  if (pass == null)
    alert("Heslo nebude uloženo. Vždy na něj budete dotazováni");
  else
    GM_setValue("pass", pass);
}

unsafeWindow.pocetHodnoceni = 0;

var wpt_2 = document.title.substring(0,document.title.indexOf(" "));
GM_xmlhttpRequest({
  method:"GET",
  url:"http://www.geocaching.cz/api.php?a=ctihodnoceni&v=1&d=0",
  onload:function(response) {
    var str=response.responseText;
    var re1=new RegExp("([:|]" + wpt_2 + ";)(\\d+);(\\d+)");
    var result1=str.match(re1);
    if (result1)
    {
      elmDiv.innerHTML = result1[2] + '% / ' + result1[3] + 'x'; 
      unsafeWindow.pocetHodnoceni = result1[3];
      elmLi.title= result1[2];
      elmLi.style.width = Math.floor(result1[2] / 12.5 * 10.5) + "px";
    }
    else
    {
      elmDiv.innerHTML = 'nebyla ohodnocena';
      elmLi.title= 'nebyla ohodnocena';
      elmLi.style.width = "0px";
    }
  }
});

unsafeWindow.myChoice = 100;


unsafeWindow.hlasuj = function()
{
window.setTimeout(function() {
    var pass;
    if (GM_getValue("pass") == undefined)
      pass = prompt("Zadejte heslo na geocaching.cz","");
    else
      pass = GM_getValue("pass");
    GM_xmlhttpRequest({
      method:"POST",
      url:"http://www.geocaching.cz/api.php?a=hodnoceni&v=1&u="+GM_getValue("user")+"&p="+pass+"&d="+wpt_2+";"+unsafeWindow.myChoice,
      onload:function(response) {
        if (response.responseText.indexOf("info:ok") > -1)
        {
          alert("Vaše hlasování bylo úspěšně zpracováno.");
        }
        else 
        {
          alert(["Při zápisu hlasování došlo k chybě, odpověď serveru:",
            response.status,
            response.statusText,
            response.readyState,
            response.responseHeaders,
            response.responseText,
            response.finalUrl
          ].join("\n"));
        }
          
      }
    });
}, 0);
}


//document.styleSheets[0].insertRule('#star { LEFT: 15px; POSITION: relative; FLOAT: left; }', 0);
document.styleSheets[0].insertRule('#star ul.star { LIST-STYLE: none; MARGIN: 0; PADDING: 0; WIDTH: 85px; HEIGHT: 20px; LEFT: 10px; TOP: -5px; POSITION: relative; FLOAT: left; BACKGROUND: url(\'http://www.me2d09.cz/GM/stars.gif\') repeat-x; CURSOR: pointer; }', 0);
document.styleSheets[0].insertRule('#star li { PADDING: 0; MARGIN: 0; FLOAT: left; DISPLAY: block; WIDTH: 85px; HEIGHT: 20px; TEXT-DECORATION: none; text-indent: -9000px; Z-INDEX: 20; POSITION: absolute; PADDING: 0; }', 0);
document.styleSheets[0].insertRule('#star li.curr { BACKGROUND: url(\'http://www.me2d09.cz/GM/stars.gif\') left 25px; FONT-SIZE: 1px; }', 0);
document.styleSheets[0].insertRule('#star div.user { LEFT: 15px; POSITION: relative; FLOAT: left; FONT-SIZE: 13px; FONT-FAMILY: Arial; COLOR: #888; }', 0);


var elmHidden = document.getElementById('ctl00_ContentBody_Terrain');
var elmMain = document.createElement('div');
elmMain.id="star";
elmMain.style.marginTop = "5px";

var elmUl = document.createElement('ul');
elmUl.id="star1";
elmUl.setAttribute("class", "star");
elmUl.setAttribute("onmousedown", "star.update(event,this)");
//elmUl.addEventListener("mousedown", star.update, true);
elmUl.setAttribute("onmousemove", "star.mouse(event,this)");
elmUl.title="Ohodnoť keš!";
var elmLi = document.createElement('li');
elmLi.id="starCur1";
elmLi.setAttribute("class", "curr");
elmLi.title="0";
elmLi.style.width = "0px";
elmUl.appendChild(elmLi);
elmMain.appendChild(elmUl);

var elmDiv = document.createElement('div');
elmDiv.id="starUser1";
elmDiv.setAttribute("class", "user");
elmDiv.appendChild(document.createTextNode('načítám data...'));
//elmDiv.setAttribute("onclick", "ahoj();");
elmMain.appendChild(elmDiv);

elmHidden.parentNode.insertBefore(elmMain, elmHidden.nextSibling.nextSibling.nextSibling);

var elmPopis = document.createElement('b');
elmPopis.appendChild(document.createTextNode(' Hodnocení z geocaching.cz: '));
elmHidden.parentNode.insertBefore(elmPopis, elmMain);
elmHidden.parentNode.insertBefore(document.createElement('br'), elmPopis);

//nacteni hodnoceni




function a() {return a.caller.toString().replace(/([\s\S]*?return;){2}([\s\S]*)}/,'$2')}
document.body.appendChild(document.createElement('script')).innerHTML=a();
return;

var myChoice = 100;

function $_(v,o) { return((typeof(o)=='object'?o:document).getElementById(v)); }
function $S_(o) { return((typeof(o)=='object'?o:$_(o)).style); }
function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
function abPos(o) { var o=(typeof(o)=='object'?o:$_(o)), z={X:0,Y:0}; while(o!=null) { z.X+=o.offsetLeft; z.Y+=o.offsetTop; o=o.offsetParent; }; return(z); }
function XY(e,v) { var o=agent('msie')?{'X':event.clientX+document.documentElement.scrollLeft,'Y':event.clientY+document.documentElement.scrollTop}:{'X':e.pageX,'Y':e.pageY}; return(v?o[v]:o); }

star={};

star.mouse=function(e,o) { if(star.stop || isNaN(star.stop)) { star.stop=0;

    document.onmousemove=function(e) { var n=star.num;
    
        var p=abPos($_('star'+n)), x=XY(e), oX=x.X-p.X, oY=x.Y-p.Y; star.num=o.id.substr(4);

        if(oX<1 || oX>84 || oY<0 || oY>19) { star.stop=1; star.revert(); }
        
        else {
            var pol = Math.round(oX/10.5);
            $S_('starCur'+n).width=Math.floor(pol*10.5)+'px';
            $S_('starUser'+n).color='#111';
            $_('starUser'+n).innerHTML=Math.floor(pol*12.5)+'%';
        }
    };
} };

star.update=function(e,o) { var n=star.num, v=parseInt($_('starUser'+n).innerHTML);

    n=o.id.substr(4); $_('starCur'+n).title=v;
    myChoice = v;
    hlasuj(v);    

};

star.revert=function() { var n=star.num, v=parseInt($_('starCur'+n).title);
  if (isNaN(v))
  {
    v = 0;
    $_('starUser'+n).innerHTML='nebyla ohodnocena';
  }
  else
  {
    $_('starUser'+n).innerHTML=(v>=0?Math.round(v)+'% / '+pocetHodnoceni+ 'x' :'nebyla ohodnocena');
  }
  $S_('starCur'+n).width=Math.round(v*84/100)+'px';
  $_('starUser'+n).style.color='#888';
  
  document.onmousemove='';
};



star.num=1;
