/*
 * Scone - The Web Enhancement Framework
 * Copyright (C) 2009 Harald Weinreich, Volkert Buchmann, Frank Wollenweber, Torsten Haß
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package scone.accesstracking;


import scone.netobjects.LinkToken;
import scone.proxy.HtmlTokenEditor;
import scone.util.ErrorLog;
import scone.util.tokenstream.SconePipe;
import scone.util.tokenstream.Token;
import scone.util.tokenstream.TokenInputStream;
import scone.util.tokenstream.TokenOutputStream;


/**
 * Adds onClick-Events to all A and AREA elements.<p> 
 * These Events set the linkId, which will be sent to the proxy for user action tracking.<p>
 *
 * The following Code is inserted: <code>onClick=&quot;_scone_setlink(linkId);&quot;</code>, where linkId is the number of that link.
 * The JavaScript function <code>_scone_setlink()</code> is defined in the ActionTrackingMeg.
 *
 * @author Harald Weinreich
 * @author Volkert Buchmann 
 */

public class LinkEventAdder extends HtmlTokenEditor {

    /**
     * accepts all links
     */
    public void handleRequest(SconePipe pipe) {
        try {
            TokenInputStream in = pipe.getTokenInputStream();
            TokenOutputStream out = pipe.getTokenOutputStream();
   		
            LinkToken lt = null;
            Token t = null;

            while ((t = in.read()) != null) {
                if (t instanceof LinkToken) {
                    lt = (LinkToken) t;
                    // This adds the linkId to the stop message from the browser...
                    String onClick = ";_scone_link('" + lt.getLink().getLinkId() + "');";   

                    if (lt.hasParam("onclick")) {
                        onClick += lt.getParam("onclick");
                        lt.removeParam("onclick");  // Does an "onClick" already exist: remember and delete
                    }   
                    lt.setParam("onclick", onClick, "onClick");   // set new onclick
                }
                out.write(t);
            }
        } catch (Exception exc) {
            ErrorLog.log(this, "handleRequest()", "", exc);
        }         
    }
   
}
