// ==UserScript==
// @name         WIW forum seged
// @namespace    http://www.atleta.hu/gm/wiw
// @description  v0.2 Kicsit baratsagosabba teszi a forum hasznalatat. Megnoveli a beiro ablak meretet es megjegyzi az utoljara elkuldott hozzaszolas szoveget arra az esetre, ha az uzenet irasa kozben kivagott volna minket a rendszer.
// @include      http://*wiw.hu/pages/forum/topic.jsp*
// @include      http://*wiw.net/pages/forum/topic.jsp*
// @include      http://*wiw.hu/pages/forum/topic.jsp*
// @include      http://*wiw.net/pages/forum/topic.jsp*

// ==/UserScript==

/*
        Author: Laszlo Marai / atleta
        Date:   2007-08-30
        License: General Public License
*/

(function(){
    var xp = new XPathHelper( document );
    
    const VERSION = "0.5";
    const NO_VERSION = "NO VERSION INFO";
    const BASE_KEY = "WiWForumHelper.";
    const VERSION_KEY = BASE_KEY + "Version";
    const NO_COMMENT = "";
    //const URI_BASE = document.baseURI.replace( /(http:\/\/[^\/]*)\/.*/, "$1" );
   
    // This regex is really cute and works in the JSShell, but magically misbehaves in GM...???
    const WIW_URL_TRANS = /(http:\/\/www\.(i?wiw\.hu|iwiw\.(net|cz|sk|com)))/g;
//    const WIW_URL_TRANS = /http:\/\/www\.iwiw\.(hu|net|cz|sk|com)/g;


    const NEWLINE = /\n/g;
    const COMMENT_BOX = "//default:textarea";
    const COMMENT_BOX_SIZE = "180px";
    const REPLY_TO = "//default:input[@name='p_answeredmessageid']";

    //const SUBMIT_BUTTON = "//default:span[child::text()='Vigyük fel']/..";
    const SUBMIT_BUTTON = "//default:div[@class='sendcomment']/default:a[1]";
    const TOPIC_LINK = "//default:label[child::text()='Link:']/../default:p[1]/default:a[1]"
    const TOPIC_ID_RX = /.*\/pages\/forum\/topic.jsp\?topicID=([0-9]*)/
    const TOPIC_ID = getTopicId();

    const USER_ID = getUserId( xp );
    const COMMENT_KEY = BASE_KEY + "Comment." + TOPIC_ID;
    const REPLY_TO_KEY = BASE_KEY + "ReplyTo." + TOPIC_ID;
	const LAST_COMMENT_KEY = BASE_KEY + "LastSeen." + TOPIC_ID;
    const OWN_COMMENTS = "//default:table[@class='forummessage' and default:tr/default:td/default:a[@href='/pages/user/userdata.jsp?userID=" + USER_ID + "']]/default:tr[1]/default:td[2]";
	const COMMENT_ID_RX = /([0-9]*)\.$/;


    function XPathHelper( document ) {
        var createResolver = function( resolver ) {
            return function( ns ) { 
                return resolver.lookupNamespaceURI( ns == "default" ? "" : ns )
            }
        }

        this.evaluate = function( location ) {
            return myDocument.evaluate( location, myDocument, 
            resolver, XPathResult.ANY_TYPE, null );
        }

        this.getFirst = function( location ) {
            return this.evaluate( location ).iterateNext();
        }

        var resolver = createResolver( 
        document.createNSResolver(document.documentElement) );
        var myDocument = document;
    }

    function handleUpgrade() {
        if ( GM_getValueUTF8( VERSION_KEY, NO_VERSION ) != VERSION ) {
            GM_setValueUTF8( VERSION_KEY, VERSION );
        }
    }

    function toUTF8(s) {
        return unescape( encodeURIComponent( s ) );
    }

    function fromUTF8(s) {
        return decodeURIComponent( escape( s ) );
    }

    function GM_getValueUTF8( key, deflt ) {
        GM_log( "Get: " + key + " (" + toUTF8( deflt ) + ")" );
        return fromUTF8( GM_getValue( key, toUTF8( deflt ) ) );
/*        var ret = azazaz( key );
        GM_log( "Got: " + ret );
        return ret;*/
    }

    function GM_setValueUTF8( key, value ) {
        GM_log( "Set: " + key + " = " + value );
        GM_setValue( key, toUTF8( value ) );
    }
    function getUserId( xpath ) {
        var anchor = xpath.getFirst( "//default:div[@id='wellcome']/default:div/default:a");

        return anchor.href.split( "userID=" )[1];
    }

    function getTopicId() {
        link = xp.getFirst( TOPIC_LINK );
        return TOPIC_ID_RX.exec( link.href )[1];
    }

    // Increase the size of the input box (we could add UI for this so that
    //  the user can do it for himself)
    function resizeCommentBox() {
        commentBox.style.height = COMMENT_BOX_SIZE;
    }

    // This will be called upon comment submit
    function submitCallback( event ) { 
        GM_setValueUTF8( COMMENT_KEY, commentBox.value );
        GM_setValueUTF8( REPLY_TO_KEY, replyTo.value );
		GM_setValue( LAST_COMMENT_KEY, 

//        commentBox.value += "\n\n[9099]";
    }

    // Install onClick listener on the submit button so that we can save
    // the comment
    function installListener() {
        var anchor = xp.getFirst( SUBMIT_BUTTON );
        anchor.addEventListener( 'click', submitCallback, true );
    }

    // Check if the last comment posted has actually appeared on the forum
    function checkLastPost() {
        var savedComment = GM_getValueUTF8( COMMENT_KEY, NO_COMMENT );
		var lastSeen = GM_getValue( LAST_COMMENT_KEY, 0 );

        if ( savedComment != NO_COMMENT ) {
			var myLast = xp.getFirst( OWN_COMMENTS );
            if ( !myLast || Number( COMMENT_ID_RX.execute( myLast.textContent )[1] ) <= lastSeen ) {
				//replyTo.value = GM_getValueUTF8( REPLY_TO_KEY, "" );
				var replyTo = GM_getValueUTF8( REPLY_TO_KEY, "0" );
				if ( Number( replyTo ) > 0 ) {
					document.location = "javascript:answerToThis( " + 
						GM_getValueUTF8( REPLY_TO_KEY, "" ) + ", 1 );";
				}
				commentBox.value = savedComment;
            } else {
                GM_setValueUTF8( COMMENT_KEY, NO_COMMENT );
            }
        }
    }

    var commentBox = xp.getFirst( COMMENT_BOX );
    var replyTo = xp.getFirst( REPLY_TO );

    handleUpgrade();
    resizeCommentBox();
    checkLastPost();
    installListener();

    // Focus input field, scroll to view
    // Test: remember the last comment no. seen, and if we have a comment with a greater
    // no. than that, then the posting was successful
    // Quickish test/hack
    /*
    function mycounter(e){
    	document.location="javascript:textCounter(document.forms['mainForm'].p_messagetext,document.forms['mainForm'].len_text,3990);";
    }
    mycounter(0);
    document.forms['mainForm'].p_messagetext.onkeyup = mycounter;
    document.forms['mainForm'].p_messagetext.onkeydown = mycounter;*/

})();
