
var acwebconnecting_traffic = (function() {

	// init variables
	debug_mode = false;
	traffic_host = "traffic.acwebconnecting.com";
	new_stat_id = "0b3c8241d5d12a7f9620bbe294e970c1b81f5286";
	is_ready = false;
	new_session = false;
	stat_id = null;
	date_now = new Date();
	date_old = date_now.getTime()-(24*3600*1000);
	date_cookie = date_now.getTime()+(90*24*3600*1000);
	date_session = new Date(date_now.getFullYear(), date_now.getMonth(), date_now.getDate()+1, 0, 0, 0);
	forceJQuery = 0;

	//
	function initJQuery() {

	    if (typeof(jQuery) == 'undefined' || forceJQuery || $().jquery < '1.5.0') {
	    	debug('Load JQuery JS');
            document.write("<scr"+"ipt type=\"text/javascript\" src=\"http://"+traffic_host+"/js/jquery-1.7.0.min.js\"></scr"+"ipt>");
	    }
	}

	//
	function initSWFObject() {

	    if (typeof(swfobject) == 'undefined') {
	    	debug('Load SWFObject JS');
            document.write("<scr"+"ipt type=\"text/javascript\" src=\"http://"+traffic_host+"/js/swfobject-2.2.js\"></scr"+"ipt>");
	    }
	}

	//
	function initColorMaker() {

	    if (typeof(colormaker) == 'undefined') {
	    	debug('Load ColorMaker JS');
            document.write("<scr"+"ipt type=\"text/javascript\" src=\"colormaker.js\"></scr"+"ipt>");
	    }
	}

	//
	function initACWebconnecting() {

		if (typeof(get_from_acwebconnecting) == 'undefined') {
			debug('Load ACWebconnecting JS');
			document.write("<scr"+"ipt type=\"text/javascript\" src=\"http://"+traffic_host+"/stats2_cookie.php?get_from_acwebconnecting=1\"></scr"+"ipt>");
		}
	}

	//
	function check_external_functions() {

		is_ready = typeof(jQuery) == 'undefined' || typeof(swfobject) == 'undefined' || typeof(colormaker) == 'undefined' || typeof(get_from_acwebconnecting) == 'undefined' ? false : true;
		debug('Is ready : '+(is_ready ? "OK" : "KO"), 'info');

		debug('Check JQuery loaded : '+(typeof(jQuery) == 'undefined' ? 'KO' : 'OK'), typeof(jQuery) == 'undefined' ? 'warn' : 'debug');
		debug('Check SWFObject loaded : '+(typeof(swfobject) == 'undefined' ? 'KO' : 'OK'), typeof(swfobject) == 'undefined' ? 'warn' : 'debug');
		debug('Check ColorMaker loaded : '+(typeof(colormaker) == 'undefined' ? 'KO' : 'OK'), typeof(colormaker) == 'undefined' ? 'warn' : 'debug');
		debug('Check ACWebconnecting loaded : '+(typeof(get_from_acwebconnecting) == 'undefined' ? 'KO' : 'OK'), typeof(get_from_acwebconnecting) == 'undefined' ? 'warn' : 'debug');
	}

	/*
	 * include another js file
	 * http://code.seebz.net/p/include/
	 */
	function include(src, attributes)
	{
		try {
			attributes = attributes || {};
			attributes.type = "text/javascript";
			attributes.src = src;

			var script = document.createElement("script");
			for(aName in attributes)
				script[aName] = attributes[aName];

			document.getElementsByTagName("head")[0].appendChild(script);
			return true;
		} catch(e) { return false; }
	}

	/*
	 * get a cookie
	 * http://www.supportduweb.com/scripts_tutoriaux-code-source-73-gestion-des-cookies-en-javascript-document-cookie-javascript-get-cookie-set-cookie.html
	 */
	function gcookie(name)
	{
		if(document.cookie.length>0)
		{
			start=document.cookie.indexOf(name+"=");
			pos = start+name.length+1;
			if(start!=0)
			{
				start=document.cookie.indexOf("; "+name+"=");
				pos = start+name.length+3;
			}
			if(start!=-1)
			{
				start=pos;
				end=document.cookie.indexOf(";",start);
				if(end==-1)
				{
					end=document.cookie.length;
				}
				return unescape(document.cookie.substring(start,end));
			}
		}
		return '';
	}

	/*
	 * set a cookie
	 * http://www.supportduweb.com/scripts_tutoriaux-code-source-73-gestion-des-cookies-en-javascript-document-cookie-javascript-get-cookie-set-cookie.html
	 */
	function scookie(name,value,time)
	{
		var expire=new Date(time);
		document.cookie=name+'='+escape(value)+';expires='+expire.toUTCString();
		return true;
	}

	/**
	 * This method is for Cross-site Origin Resource Sharing (CORS) POSTs
	 *
	 * @param string   url      the url to post to
	 * @param mixed    data     additional data to send [optional]
	 * @param function callback a function to call on success [optional]
	 * @param string   type     the type of data to be returned [optional]
	 */
	function postCORS(url, data, callback, type)
	{
	    try {
	        // Try using jQuery to POST
	        var jqxhr = jQuery.post(url, data, callback, type);
	        jqxhr.error(function(jqXHR, textStatus, errorThrown){ throw 'jQuery KO'; })
	    } catch(e) {
	        // jQuery POST failed
	        var params = '';
	        for (key in data) {
	            params = params+'&'+key+'='+encodeURIComponent(data[key]);
	        }
	        // Try XDR, or use the proxy
	        if (jQuery.browser.msie && window.XDomainRequest) {
	            // Use XDR
	            var xdr = new XDomainRequest();
	            xdr.open("post", url);
	            xdr.send(params);
	            xdr.onload = function() {
	                callback(handleXDROnload(this, type), 'success', this);
	            };
	        } else {
	            try {
	                // Use the proxy to post the data.
	                request = new proxy_xmlhttp();
	                request.open('POST', url, true);
	                request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	                request.send(params);
	            } catch(e) {
	                // could not post using the proxy
	                debug('could not post using the proxy', 'warn');
	            }
	        }
	    }
	}

	/**
	 * Because the XDomainRequest object in IE does not handle response XML,
	 * this function acts as an intermediary and will attempt to parse the XML and
	 * return a DOM document.
	 *
	 * @param XDomainRequest xdr  The XDomainRequest object
	 * @param string         type The type of data to return
	 *
	 * @return mixed
	 */
	function handleXDROnload(xdr, type)
	{
	    var responseText = xdr.responseText, dataType = type || "";
	    if (dataType.toLowerCase() == "xml"
	        && typeof responseText == "string") {
	        // If expected data type is xml, we need to convert it from a
	        // string to an XML DOM object
	        var doc;
	        try {
	            if (window.ActiveXObject) {
	                doc = new ActiveXObject('Microsoft.XMLDOM');
	                doc.async = 'false';
	                doc.loadXML(responseText);
	            } else {
	                var parser = new DOMParser();
	                doc = parser.parseFromString(responseText, 'text/xml');
	            }
	            return doc;
	        } catch(e) {
	            // ERROR parsing XML for conversion, just return the responseText
	        }
	    }
	    return responseText;
	}

	//
	function debug(info, level) {
		if (debug_mode && window.console) {
			switch (level) {
	 			case 'debug':
					console.log(info);
					break;
				case 'info':
					console.info(info);
					break;
				case 'warn':
					console.warn(info);
					break;
				case 'error':
					console.error(info);
					break;
				default:
					console.log(info);
					break;
			}
		}
	}

	//
	function stats_log(site_id) {

		debug('post data for site '+site_id+' on '+document.URL, 'info');
		var stat_id_save = stat_id;

		postCORS(
			'http://'+traffic_host+'/stats2_log.php',
			{
				site_id:	 site_id,
				stat_id:	 stat_id,
				url:		 document.URL,
				referrer:	 document.referrer,
				cookies:	 document.cookie
			},
			function(data) {

				if ($.parseJSON(data) == 'bad stat_id') {
					ec.set('stat_id', new_stat_id);
				} else if (data) {
					debug('CRC KO');
					var cookies = typeof(data) == 'object' ? data : $.parseJSON(data);
					$.each(cookies, function(key, value) {
						if (value && value != 'null' && value != '#deleted#') {
							var date = key == 'acwebconnecting_session' ? date_session : date_cookie;
							scookie(key, value, date);
							debug('set cookie '+key+' : "'+value+'"');
						} else {
							scookie(key, '', date_old);
						}
					});
				} else {
					debug('CRC OK');
				}

				if (new_session) {
					include('http://'+traffic_host+'/stats2_cookie.php?set_stat_id='+stat_id_save);
					debug('set acwebconnecting stat_id '+stat_id_save);
				}
			}
		);

	}

	// Init external functions
	initJQuery();
	initSWFObject();
	initColorMaker();
	initACWebconnecting();

	//
	return {
		"send": function(site_id) {

			// check external functions
			check_external_functions();
			if (!is_ready) { return false; }

			// stat_id from acwebconnecting
			get_from_acwebconnecting();
			debug('From acwebconnecting stat_id : '+stat_id, 'info');

			// new session
			if (!gcookie('acwebconnecting_session') || !stat_id) {
				new_session = true;
				debug('New session');
			}

			// colormaker
			ec = new colormaker();
			if (stat_id) {
				if (new_session) {
					ec.set('stat_id', stat_id);
					debug('set ColorMaker cookie');
				}
				stats_log(site_id);
			} else {
				ec.get('stat_id', function(value, all_candidates) {

					for (var item in all_candidates) {
						debug(item+':'+all_candidates[item]);
					}

					if (value == undefined) {
						stat_id = new_stat_id;
						ec.set('stat_id', stat_id);
						debug('New stat_id : '+stat_id, 'info');
					} else {

						stat_id = value;
						debug('Get stat_id : '+stat_id, 'info');
					}

					//
					if (stat_id != null) {
						stats_log(site_id);
					}
				});
			}

		}
	}

}) ();

