/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * 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', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @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
 */

 

	
 
 
var legal_characters = '"!#$%()*+,-./0123456789:;<=>?@ÀÁÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_´abcdefghijklmnopqrstuvwxyz{|}~àáãäçèéêëìíîïñòóôõöùúûü';
 
var keyEncryption=25;

var options = { path: '/', expires: 10 };
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            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.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encrypt_cookie(value,keyEncryption), 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 = decrypt_cookie(cookie.substring(name.length + 1),keyEncryption);
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function GetActiveCookie() {
    var cookieValue = null;
    var maxDate = new Date(new Date().getFullYear() - 2, new Date().getMonth(), new Date().getDay());
    var lastCookie = 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]);
            var options = { path: '/', expires: 10 };
            var cookieData = cookie.split('=');
            var cookieName = cookieData[0];
            var cookieValue = cookieData[1];
            // Does this cookie string begin with the name we want?
            if (decrypt_cookie(cookieValue, keyEncryption).indexOf('viapresse') > 0) {
                cookieValue = decrypt_cookie(cookieValue, keyEncryption);
                var obj = JSON.parse(cookieValue);
                if (obj.state == 1 )
                    return obj;
                if (obj.dateCreation > maxDate) {
                    maxDate = obj.dateCreation;
                    lastCookie = obj;
                }
            }
        }
    }
	
    return lastCookie;
}

function GetCookie() {
    var cookieValue = null;
    var maxDate = new Date(new Date().getFullYear() - 2, new Date().getMonth(), new Date().getDay());
    var lastCookie = 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]);
            var options = { path: '/', expires: 10 };
            var cookieData = cookie.split('=');
            var cookieName = cookieData[0];
            var cookieValue = cookieData[1];
            // Does this cookie string begin with the name we want?
            if (decrypt_cookie(cookieValue, keyEncryption).indexOf('viapresse') > 0) {
                cookieValue = decrypt_cookie(cookieValue, keyEncryption);
                var obj = JSON.parse(cookieValue);
                if (obj.state == 0 )
                    return obj;
                if (obj.dateCreation > maxDate) {
                    maxDate = obj.dateCreation;
                    lastCookie = obj;
                }
            }
        }
    }
	
    return lastCookie;
}

function GetDesactiveCookie(client) {
    var cookieValue = null;
    var maxDate = new Date(new Date().getFullYear() - 2, new Date().getMonth(), new Date().getDay());
    var lastCookie = 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]);
            var options = { path: '/', expires: 10 };
            var cookieData = cookie.split('=');
            var cookieName = cookieData[0];
            var cookieValue = cookieData[1];
            // Does this cookie string begin with the name we want?
            if (decrypt_cookie(cookieValue, keyEncryption).indexOf('viapresse') > 0) {
                cookieValue = decrypt_cookie(cookieValue, keyEncryption);
                var obj = JSON.parse(cookieValue);
                
				if (obj.state == 0 && client==obj.numClient)
					{
					  return obj;
					}
                else if (obj.state == 0)
                    {
					 return obj;
					}
                if (obj.dateCreation > maxDate) {
                    maxDate = obj.dateCreation;
                    lastCookie = obj;
                }
            }
        }
    }
    return lastCookie;
}



function DeactivateAllCookies()
{
        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]);
                DeactivateCookie(cookie);
            }
        }
}

function DeactivateCookie(cookie) {
        var options = { path: '/', expires: 10 };
        var cookieData = cookie.split('=');
        var cookieName = cookieData[0];
        var cookieValue = cookieData[1];
        // Does this cookie string begin with the name we want?
        if (decrypt_cookie(cookieValue, keyEncryption).indexOf('viapresse') > 0) {
            cookieValue = decrypt_cookie(cookieValue,keyEncryption);
            var obj = JSON.parse(cookieValue);
            obj.state = 0;
            $.cookie(cookieName, JSON.stringify(obj, false), options);
        }
}

function DeleteAllCookieActive() {
		var cookieValue = null;
        var options;
        var cookieData;
        var cookieName;
        		
		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]);
				options = { path: '/', expires: 10 };
				cookieData = cookie.split('=');
				cookieName = cookieData[0];
				cookieValue = cookieData[1];
				// Does this cookie string begin with the name we want?
				if (decrypt_cookie(cookieValue, keyEncryption).indexOf('viapresse') > 0) {
					cookieValue = decrypt_cookie(cookieValue,keyEncryption);
					var obj = JSON.parse(cookieValue);
					$.cookie(cookieName, null);
				}
		 }
        }
}

function encryptIt(text) {
    return encrypt_cookie(text, keyEncryption);
}

function decryptIt(text) {
    return decrypt_cookie(text, keyEncryption);
}

function encrypt_cookie(cookie_value, encrypt_key) {

  var cookie_character;
  var character_location;
  var encrypted_location;
  var encrypted_character;

  // This variable holds the encrypted cookie characters
  var encrypted_string = "";
  
  // Run through each character in the cookie value
  for (var counter = 0; counter < cookie_value.length; counter++) {
  
    // Get the current cookie character
    cookie_character = cookie_value.substring(counter, counter + 1);
    
    // Get the character's location in the string of legal characters
    character_location = legal_characters.indexOf(cookie_character);
    if(character_location>=0)
    {
        // XOR the character location with the encrypt_key
        encrypted_location = character_location ^ encrypt_key;
        
        // Use the encrypted location to specify the encrypted 
        // character within the string of legal characters
        encrypted_character = legal_characters.substring(encrypted_location, 
                   encrypted_location + 1);
        
        // Add the encrypted character to the string
        encrypted_string += encrypted_character ;
    }
    else
        encrypted_string += cookie_character ;
    
  }
  return encrypted_string;
}

function decrypt_cookie(encrypted_string, encrypt_key) {
 
  encrypted_string = encrypted_string || '' ;
  var cookie_character;
  var character_location;
  var encrypted_location;
  var encrypted_character;

  // This variable holds the decrypted cookie value
  var cookie_value = "";
  
  // Run through each character in the encrypted string
  for (var counter = 0; counter < encrypted_string.length; counter++) {
  
    // Get the current encrypted character
    encrypted_character = encrypted_string.substring(counter, counter + 1);
    
    // Get the character's location in the string of legal characters
    encrypted_location =legal_characters.indexOf(encrypted_character);
    if(encrypted_location>=0)
    {
        // XOR the character location with the encrypt_key
        character_location = encrypted_location ^ encrypt_key;

        // Use the character location to specify the plain text 
        // character within the string of legal characters
        cookie_character = legal_characters.substring(character_location, 
                  character_location + 1);
        
        // Add the plain text character to the string
        cookie_value += cookie_character ;
    }
    else
        cookie_value += encrypted_character; 
  }
  return cookie_value
}


/* Google's scripts  */
function SetGA_Logged() {
/*		var _gaq = _gaq || [];
		_gaq.push(
		['_setAccount', 'UA-4687361-1'],
		['_setCustomVar', 2, 'visiteur', 'cookie', 2],
		['_trackPageview', '/cookie.html']);*/


}
/* Google's scripts  */
function SetGA_Customer() {
//		var _gaq = _gaq || [];
//		_gaq.push(
//        ['_setCustomVar', 3, 'achat', 'client', 1], 
//		['_trackPageview', document.location.pathname+document.location.search]);

}

function SetGA_UnLogged() {
/*		var _gaq = _gaq || [];

		_gaq.push(
        ['deleteCustomVar', 2,], 
		['_trackEvent', 'cookie', 'statut', 'inactif']);*/
}


/* Fonctionnal scripts  */
//create Account Method
function CreateAccount() {
	SetGA_Logged();
    var data = resultat || GetActiveCookie();
    $.cookie(encryptIt(COOKIE_NAME), JSON.stringify(data, false), options);
}
//Authenticate Method
function Authenticate(activecookie) {
	
	if (activecookie) {
        if (activecookie.client ==1)
			{
			 SetGA_Logged();
			// SetGA_Customer();
			}
        else
           { 
			 SetGA_Logged();
		   }
	}
}



//cas de la commande validé, change le statut dans le cookie GA de logué à client
function ConfirmCommande() {
    SetGA_Customer();
    var user = JSON.parse(resultat) || GetActiveCookie();
    if (user) {
        var data = JSON.parse($.cookie(encryptIt(user.customer))); // || <%= resultat %>;
        data.client = 1;
        $.cookie(encryptIt(user.customer), JSON.stringify(data, false), options);
    }
    else
        InitUnknownSession();
}


function InitSession() { //
    var user = resultat || GetActiveCookie();
    var current=GetActiveCookie();
    if (current) {
        // Reactivation du cookie
        current.state = 1;
        $.cookie(encryptIt(user.customer), JSON.stringify(current, false), options);
    }
    else
        InitUnknownSession();
}

function InitUnknownSession() {
    SetGA_UnLogged();
}

