/**
 * VPRO Stat
 * @requires jQuery Library
 */
 var VproStat = {
 	// Site identifiers
	SITE_3VOOR12 : "3voor12",
	//SITE_CINEMA : "cinema",		// More sites will be added later
	
	// Cookie keys
	COOKIE_CLICK  : 'click',
	COOKIE_MEDIA  : 'media',
	COOKIE_USERID : 'userid',
	COOKIE_UUID   : 'UUID',
	
	NEED_CLEANUP : [ 'media' ],
	
	separator : ',',

	/**
	 * Get an instance
	 * @param {String} Site name (SITE_*)
	 * @return An instance of VproStat
	 */
	getInstance : function(site){
		this.cleanupCookies();
		this.site = site;
		this.checkUUId();			// Generate a UUID when necessary (to track not logged in)
		this.updateClickId();		// Generate a new click ID

		return this;
	},
	
	/**
	 * Prevent cookie from sticking when they're not relevant anymore
	 */
	cleanupCookies : function() {
		for (var cookie in this.NEED_CLEANUP) {
			this.removeCookie(this.NEED_CLEANUP[cookie]);
		}
	},
	
	/**
	 * @param {String} key
	 * @param {Array} stats
	 */
	log : function(key, stats){
		this.cookie(key, this.serializeStats(stats), {path: '/'});
	},
	
	/**
	 * create a long string of key-value pairs
	 * @param {Array} array of stat values (site_section, nodenr)
	 * @return {String} serialized value string
	 */
	serializeStats : function(stats){
		return this.site + this.separator + stats.join(this.separator);
	},
	
	/**
	 * Set the user ID cookie when the user is logged in
	 * or remove it when the user is not logged in
	 * @param User ID
	 */
	setUserId : function(uId){
		if (uId != -1) {
			// Set the USERID cookie
			this.cookie(this.COOKIE_USERID, uId, {path: '/'});
		} else if (this.cookie(this.COOKIE_USERID)) {
			// Remove the USERID cookie if it exists and the user is not logged in
			this.removeCookie(this.COOKIE_USERID);
		}
	},
	
	removeCookie : function(cookie) {
		this.cookie(cookie, '', {path: '/', expires: -1});
	},
	
	/**
	 * Create a UUID cookie if it doesn't exist yet or update the expiray when it exists
	 */
	checkUUId : function(){
		if(!this.cookie(this.COOKIE_UUID)){
			// Generate new UUID
			this.cookie(this.COOKIE_UUID, new UUID(), {path: '/', expires: 365});
		}
		else{
			// Keep existing UUID, but reset expiry
			this.cookie(this.COOKIE_UUID, this.cookie(this.COOKIE_UUID), {path: '/', expires: 365});
		}
	},
	
	/**
	 * Update the click ID cookie
	 */
	updateClickId : function(){
		// Generate a new click UUID
		this.cookie(this.COOKIE_CLICK, new UUID(), {path: '/'});
	},
	
	/**
	 * Create a cookie with the given name and value and other optional parameters.
	 *
	 * @example $.cookie('the_cookie', 'the_value');
	 * @desc Set the value of a cookie.
	 * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
	 * @desc Create a cookie with all available options.
	 * @example $.cookie('the_cookie', 'the_value');
	 * @desc Create a session cookie.
	 * @example $.cookie('the_cookie', '', {expires: -1});
	 * @desc Delete a cookie by setting a date in the past.
	 *
	 * @param String name The name of the cookie.
	 * @param String value The value of the cookie.
	 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
	 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
	 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
	 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
	 *                             when the the browser exits.
	 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
	 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
	 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
	 *                        require a secure protocol (like HTTPS).
	 * @type undefined
	 *
	 * @name $.cookie
	 * @cat Plugins/Cookie
	 * @author Klaus Hartl/klaus.hartl@stilbuero.de
	 */
	
	/**
	 * Get the value of a cookie with the given name.
	 *
	 * @example $.cookie('the_cookie');
	 * @desc Get the value of a cookie.
	 *
	 * @param String name The name of the cookie.
	 * @return The value of the cookie.
	 * @type String
	 *
	 * @name $.cookie
	 * @cat Plugins/Cookie
	 * @author Klaus Hartl/klaus.hartl@stilbuero.de
	 */	
	cookie : function(name, value, options){
	
	    if (typeof value != 'undefined') { // name and value given, set cookie
	        options = options || {};
	        var expires = '';
	        if (options.expires && (typeof options.expires == 'number' || options.expires.toGMTString)) {
	            var date;
	            if (typeof options.expires == 'number') {
	                date = new Date();
	                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
	            } else {
	                date = options.expires;
	            }
	            expires = '; expires=' + date.toGMTString(); // use expires attribute, max-age is not supported by IE
	        }
	        var path = options.path ? '; path=' + options.path : '';
	        var domain = options.domain ? '; domain=' + options.domain : '';
	        var secure = options.secure ? '; secure' : '';
	        document.cookie = [name, '=', (options.encodeValue)? encodeURIComponent(value) : value, expires, path, domain, secure].join('');
	    } else { // only name given, get cookie
	        var cookieValue = null;
	        if (document.cookie && document.cookie != '') {
	            var cookies = document.cookie.split(';');
	            for (var i = 0; i < cookies.length; i++) {
	                var cookie = jQuery.trim(cookies[i]);
	                // Does this cookie string begin with the name we want?
	                if (cookie.substring(0, name.length + 1) == (name + '=')) {
	                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
	                    break;
	                }
	            }
	        }
	        return cookieValue;
	    }
	}
};

/*

uuid.js - Version 0.1
JavaScript Class to create a UUID like identifier

Copyright (C) 2006, Erik Giberti (AF-Design), All rights reserved.

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

The latest version of this file can be downloaded from
http://www.af-design.com/resources/javascript_uuid.php

HISTORY:
6/5/06 - Initial Release

*/


// on creation of a UUID object, set it's initial value
function UUID(){
	this.id = this.createUUID();
}

// When asked what this Object is, lie and return it's value
UUID.prototype.valueOf = function(){ return this.id; }
UUID.prototype.toString = function(){ return this.id; }

//
// INSTANCE SPECIFIC METHODS
//

UUID.prototype.createUUID = function(){
	// JavaScript Version of UUID implementation.
	//
	// Copyright 2006 Erik Giberti, all rights reserved.
	//
	// Loose interpretation of the specification DCE 1.1: Remote Procedure Call
	// described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37
	// since JavaScript doesn't allow access to internal systems, the last 48 bits 
	// of the node section is made up using a series of random numbers (6 octets long).
	//  
	var dg = UUID.timeInMs(new Date(1582, 10, 15, 0, 0, 0, 0));
	var dc = UUID.timeInMs(new Date());
	var t = dc - dg;
	var h = '-';
	var tl = UUID.getIntegerBits(t,0,31);
	var tm = UUID.getIntegerBits(t,32,47);
	var thv = UUID.getIntegerBits(t,48,59) + '1'; // version 1, security version is 2
	var csar = UUID.getIntegerBits(UUID.randrange(0,4095),0,7);
	var csl = UUID.getIntegerBits(UUID.randrange(0,4095),0,7);

	// since detection of anything about the machine/browser is far to buggy, 
	// include some more random numbers here
	// if nic or at least an IP can be obtained reliably, that should be put in
	// here instead.
	var n = UUID.getIntegerBits(UUID.randrange(0,8191),0,7) + 
			UUID.getIntegerBits(UUID.randrange(0,8191),8,15) + 
			UUID.getIntegerBits(UUID.randrange(0,8191),0,7) + 
			UUID.getIntegerBits(UUID.randrange(0,8191),8,15) + 
			UUID.getIntegerBits(UUID.randrange(0,8191),0,15); // this last number is two octets long
	return tl + h + tm + h + thv + h + csar + csl + h + n; 
}

//
// GENERAL METHODS (Not instance specific)
//

// Pull out only certain bits from a very large integer, used to get the time
// code information for the first part of a UUID. Will return zero's if there 
// aren't enough bits to shift where it needs to.
UUID.getIntegerBits = function(val,start,end){
	var base16 = UUID.returnBase(val,16);
	var quadArray = new Array();
	var quadString = '';
	var i = 0;
	for(i=0;i<base16.length;i++){
		quadArray.push(base16.substring(i,i+1));	
	}
	for(i=Math.floor(start/4);i<=Math.floor(end/4);i++){
		if(!quadArray[i] || quadArray[i] == '') quadString += '0';
		else quadString += quadArray[i];
	}
	return quadString;
}

// Numeric Base Conversion algorithm from irt.org
// In base 16: 0=0, 5=5, 10=A, 15=F
UUID.returnBase = function(number, base){
	//
	// Copyright 1996-2006 irt.org, All Rights Reserved.	
	//
	// Downloaded from: http://www.irt.org/script/146.htm	
	// modified to work in this class by Erik Giberti
	var convert = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    if (number < base) var output = convert[number];
    else {
        var MSD = '' + Math.floor(number / base);
        var LSD = number - MSD*base;
        if (MSD >= base) var output = this.returnBase(MSD,base) + convert[LSD];
        else var output = convert[MSD] + convert[LSD];
    }
    return output;
}

// This is approximate but should get the job done for general use.
// It gets an approximation of the provided date in milliseconds. WARNING:
// some implementations of JavaScript will choke with these large numbers
// and so the absolute value is used to avoid issues where the implementation
// begin's at the negative value.
UUID.timeInMs = function(d){
	var ms_per_second = 100; // constant
	var ms_per_minute = 6000; // ms_per second * 60;
	var ms_per_hour   = 360000; // ms_per_minute * 60;
	var ms_per_day    = 8640000; // ms_per_hour * 24;
	var ms_per_month  = 207360000; // ms_per_day * 30;
	var ms_per_year   = 75686400000; // ms_per_day * 365;
	return Math.abs((d.getUTCFullYear() * ms_per_year) + (d.getUTCMonth() * ms_per_month) + (d.getUTCDate() * ms_per_day) + (d.getUTCHours() * ms_per_hour) + (d.getUTCMinutes() * ms_per_minute) + (d.getUTCSeconds() * ms_per_second) + d.getUTCMilliseconds());
}

// pick a random number within a range of numbers
// int c randrange(int a, int b); where a <= c <= b
UUID.randrange = function(min,max){
	var num = Math.round(Math.random() * max);
	if(num < min){ 
		num = min;
	} else if (num > max) {
		num = max;
	}
	return num;
}

// end of UUID class file