/**
 * Functions:
 * maxCookie( 3 ); - Determines the number of results that is stored in the cookie, default is 3.
 * showResults( 3 ); - Determines the number of results that is shown in the box, default is 3.
 * AddLastVisited( label, url ); - Add a url to the cookie, including the label of the url
 * ShowLastVisited(); - Creates a html div with last visited pages.
 * LastVisitedLoader( element, type, handler ); - Event handler for binding of several functions
 *
 *  Implementation example:
 *      LastVisitedLoader( window, "load", function(){
 *              maxCookie( 3 );
 *              showResults( 3 );
 *              AddLastVisited( "label", "url.html" );
 *              ShowLastVisited();
 *           }
 *      );
 *
 * Developed for UPC NL
 *
 * @author Benno Crombeen 
 */

(function(){

    var Cookie = {};
    Cookie.showMaxResults = 3;
    Cookie.maxCookie = 3;
    Cookie.contents = null;
    Cookie.buildHTML = '';

    /**
     * Toevoegen van een label en url
     */
    Cookie.AddLastVisited = function( label, url )
    {
        if( label == undefined || label == '' ){
            return;
        }

        if( url == undefined || url == '' ){
            return;
        }

        var cookievalue = '';

        Cookie.checkCookies();

        if( Cookie.contents != null )
            var arrValues = Cookie.contents.split( '&' );
        else
            var arrValues = new Array();
        

        if( arrValues.length == 0 ){

            cookievalue += "1[label:" + label + "|url:" + url + "]";

        } else {

            cookievalue += "1[label:" + label + "|url:" + url + "]";

            var pattern = /(\d+)\[.+\]/;

            var arrCurrent = cookievalue.match( pattern );

            arrCurrent[0] = arrCurrent[0].replace( arrCurrent[1], '' );

            var intCookieItemCounter = 2;//interne counter voor cookiepositie

            for( var i = 0; i<arrValues.length; i++ ){

                if( ( parseInt( Cookie.maxCookie ) + 1 ) == intCookieItemCounter ){
                    break;
                }

                var res = arrValues[i].match( pattern );

                var old = res[0].replace( res[1], '' );

                if( old != arrCurrent[0] ){
                    //doublures er tussenuit vissen
                    res[0] = res[0].replace( res[1], intCookieItemCounter );

                    cookievalue += "&" + res[0];

                    intCookieItemCounter++;
                }

            }

        }

        cookievalue = encodeURIComponent( cookievalue );

        document.cookie = "upclastvisited=" + cookievalue + "; max-age=" + ( 60 * 60 * 24 * 30 ) + "; path=/";

    };

    /**
     * Laatste urls tonen die zijn opgeslagen in de cookie
     */
    Cookie.ShowLastVisited = function()
    {
        if( Cookie.checkCookies() == false ){
            return;
        }

        var arrValues = Cookie.contents.split('&');

        for( var i=0; i<arrValues.length; i++ ){

            if( (i + 1) > Cookie.showMaxResults  ){
                break;
            }
            
            var pattern = /(\d+)(\[.+\])/;
            
            var res = arrValues[i].match( pattern );

            res[2] = res[2].replace( /[\[]/g, '' );
            res[2] = res[2].replace( /[\]]/g, '' );

            var options = res[2].split( '|' );

            var labelpos = options[0].indexOf( ':' );
            var labelstart = labelpos + 1;
            var labelend = options[0].length;
            var label = options[0].substring( labelstart, labelend );

            var urlpos = options[1].indexOf( ':' );
            var urlstart = urlpos + 1;
            var urlend = options[1].length;
            var url = options[1].substring( urlstart, urlend );

            Cookie.buildHTML += '<a href="' + url + '" name="&amp;lpos=last_visited&amp;lid=' + res[1] + '">' + label + '</a>';
  
        }

        var block = document.getElementById( 'last_visited' );// createElement( 'div' );

        var result = document.createElement( 'div' );
        result.className = 'newslink';

        result.innerHTML = Cookie.buildHTML;

        block.innerHTML = ' <h2>Laatst bekeken producten</h2>';
        block.appendChild( result );

        block.style.display = 'block';
    };

    /**
     * Kijken of de cookie upclastvisited bestaat
     */
    Cookie.checkCookies = function()
    {
        var allcookies = document.cookie;

        var position = allcookies.indexOf( 'upclastvisited=' );

        if( position == -1 ){
            return false;
        }

        var start = position + 15;
        var end = allcookies.indexOf( ';', start );
        if( end == -1 ) end = allcookies.length;

        var value = allcookies.substring( start, end );
        value = decodeURIComponent( value );

        Cookie.contents = value;

        return true;
    };

    /**
     * Hoeveelheid urls, die in COOKIES opgeslagen wordt
     */
    Cookie.saveInCookie = function( intaantal )
    {
        if( intaantal == undefined || intaantal == '' ){
            return;
        }
        Cookie.maxCookie = intaantal;
    };

    /**
     * Hoeveelheid weer te geven URLS
     */
    Cookie.showAantalLinks = function( intaantal )
    {
        if( intaantal == undefined || intaantal == '' ){
            return;
        }
        Cookie.showMaxResults = intaantal;
    };


    // addEvent written by Dean Edwards, 2005
    // http://dean.edwards.name/weblog/2005/10/add-event/
    var Event = {};

    Event.addEvent = function( element, type, handler ){
        // assign each event handler a unique ID
        if (!handler.$$guid) handler.$$guid = Event.addEvent.guid++;
        // create a hash table of event types for the element
        if (!element.events) element.events = {};
        // create a hash table of event handlers for each element/event pair
        var handlers = element.events[type];
        if (!handlers) {
            handlers = element.events[type] = {};
            // store the existing event handler (if there is one)
            if (element["on" + type]) {
                handlers[0] = element["on" + type];
            }
        }
        // store the event handler in the hash table
        handlers[handler.$$guid] = handler;
        // assign a global event handler to do all the work
        element["on" + type] = Event.handleEvent;
    };

    Event.addEvent.guid = 1;

    Event.handleEvent = function(event) {
        var returnValue = true;
        // grab the event object (IE uses a global event object)
        event = event || Event.fixEvent(window.event);

        // get a reference to the hash table of event handlers
        var handlers = this.events[event.type];
        // execute each event handler
        for (var i in handlers) {
            this.$$handleEvent = handlers[i];
            if (this.$$handleEvent(event) === false) {
                returnValue = false;
            }
        }
        return returnValue;
    };

    // Add some "missing" methods to IE's event object
    Event.fixEvent = function(event) {
        // add W3C standard event methods
        event.preventDefault = Event.fixEvent.preventDefault;
        event.stopPropagation = Event.fixEvent.stopPropagation;
        return event;
    };

    Event.fixEvent.preventDefault = function() {
        this.returnValue = false;
    };

    Event.fixEvent.stopPropagation = function() {
        this.cancelBubble = true;
    };

    /*
     * Expose de functies, als ze nog niet bestaan,
     *  Indien ze bestaan exception gooien
     */
    if( ! window.ShowLastVisited ){
        window.ShowLastVisited = Cookie.ShowLastVisited;
    } else {
        throw( 'ShowLastVisited already defined' );
    }

    if( ! window.AddLastVisited ){
        window.AddLastVisited = Cookie.AddLastVisited;
    } else {
        throw( 'AddLastVisited already defined' );
    }

    if( ! window.maxCookie ){
        window.maxCookie = Cookie.saveInCookie;
    } else {
        throw( 'maxCookie already defined' );
    }

    if( ! window.showResults ){
        window.showResults = Cookie.showAantalLinks;
    } else {
        throw( 'showResult already defined' );
    }

    if( ! window.LastVisitedLoader ){
        window.LastVisitedLoader = Event.addEvent;
    } else {
        throw( 'LastVisitedLoader already defined' );
    }

})();
