// set cj cookies
var cj_aid = get_param('AID');
if (cj_aid) { createCookie("cj_AID",cj_aid,14); };
var cj_pid = get_param('PID');
if (cj_pid) { createCookie("cj_PID",cj_pid,14); };
var cj_sid = get_param('SID');
if (cj_sid) { createCookie("cj_SID",cj_sid,14); };

//site_history: cookie storing the last 10 pages visited on the site
//site_referrer: cookie storing the ?adv=blah bit if it exists, otherwise storing the document.referrer when they first visit the site

// ---------------------------------------------- site_history ---------------------------------------
var create_id = false;
var page_name = location.href;
page_name = page_name.substring(page_name.lastIndexOf('/'), page_name.length) + ',';
var site_history_str = readCookie('site_history');
if (site_history_str==null) site_history_str = '';

// make sure there aren't more than 9 pages listed, then add this one to the front
if (site_history_str != "") {
  var count;
  var i = 0;
  for (count = 1; count<10 && i != -1; count++) {
    i = site_history_str.indexOf(',',i+1);
  }
  if (i != -1) site_history_str = site_history_str.substring(0,i);
}
var sh = page_name+site_history_str;
createCookie("site_history",sh,60);

// ---------------------------------------------- site_referrer,site_adv,user_id ---------------------------------------
var sr=readCookie('site_referrer');
var found_referrer_cookie = (sr==null) ? false : true;
if (!found_referrer_cookie) {
    // create the site_referrer cookie
    if (document.referrer != ""){
        sr = document.referrer;
    }
    else {
        sr = 'none';
    }
    createCookie("site_referrer",sr,60);

    // create the site_adv cookie
    if (document.URL.indexOf("?adv=") != -1){
        adv = document.URL.substring((document.URL.indexOf("?adv=")+5), document.URL.length);
        createCookie("site_adv",adv,60);
    }
    else {
        if (document.URL.indexOf("?source=voiprevieworg") != -1) adv = 'vr1';
        else adv = 'none';
        createCookie("site_adv",adv,60);
    }

    // create user_id cookie
    var date = new Date();
    // user_id = current_time-random number from 10000-99999
    var user_id = date.getTime()+'-'+(Math.round((Math.random()*89999)+10000));
    createCookie('user_id',user_id,60);  

    // log first visit to db
    log_first_visit(user_id,sr,sh,adv);
}

// ---------------------------------------------- get query string param  ---------------------------------------

function get_param(name) {
  var i = document.URL.indexOf('?'+name+'=');
  if (i==-1) {
    i = document.URL.indexOf('&'+name+'=');
  };
  if (i==-1) return null;
  var p = document.URL.substring(i+1, document.URL.length);
  var j = p.indexOf('&');
  if (j!=-1) {
    p = p.substring(0,j);
  };
  p = p.substring(name.length+1,p.length);
  return p;
}

// ---------------------------------------------- log first visit ---------------------------------------

function log_first_visit(user_id,sr,sh,adv) {
  var ajax_script = '/cgi/first_visit_win.pl';
  // site history and site referrer are now passed in directly so they aren't lost in the case the browser has cookies disabled.
  // var sh = (readCookie("site_history")!=null) ? readCookie("site_history") : '';
  // var sr = (readCookie("site_referrer")!=null) ? readCookie("site_referrer") : '';
  var this_url = (location.href !=null) ? location.href : '';
  var url = ajax_script+"?ajax=yes&user_id="+escape(user_id);
  url += "&site_history="+escape(sh);
  url += "&site_referrer="+escape(sr);
  url += "&site_adv="+escape(adv);
  url += "&url="+escape(this_url);
  makeXMLHttpRequest( url, first_visit_result, 'txt' );
}

function first_visit_result( res ) {
  var res1;
  var ret;
  if( res1 = res.match(/<body>(.+)<\/body>/) ) {
		eval( "var data = "+res1[1]+";" );
		ret = data.result;
  }
}


// ---------------------------------------------- cookie handling functions ---------------------------------------

/*
When calling createCookie() you have to give it three bits of information: the name and value of the cookie and the number of days it is to remain active.
*/

function createCookie(name,value,days,path,domain) {
  domain = (domain) ? domain : 'joiphone.com';
  path = (path) ? path : '/';
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path="+path+"; domain="+domain;
}

/*
To read out a cookie, call this function and pass the name of the cookie. Put the name in a variable. First check if this variable has a value (if the cookie does not exist the variable becomes null, which might upset the rest of your function), then do whatever is necessary.
*/

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/*
Pass the name of the cookie to be erased
*/
function eraseCookie(name) {
	createCookie(name,"",-1);
}

// ----------------------------------------------- ajax stuff -----------------------------------------------
function makeXMLHttpRequest(url, func){

	http_request = false;
	
	http_request_data_handler = func;

	http_request_type = arguments[2] || "xml";

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
            // See note below about this line
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
//        alert('Error! Cannot create an XMLHTTP instance');
        return false;
    }


    http_request.onreadystatechange = function(){
		if (http_request.readyState == 4) {
            if (http_request.status == 200) {
				answ = null;
				switch(http_request_type){
					case "xml": answ = http_request.responseXML; break;
					case "txt": answ = http_request.responseText; break;
					case "xmltxt": answ = (IE)? http_request.responseText : http_request.responseXML; break;
					case "jsobj" : answ =  PB_AJAX_createJSObjFromXML(http_request.responseXML);
				}
				http_request_data_handler(answ);
            } else {
//                alert('There was a problem with the request.');
				return false;
            }
        }		
	}

    this.http_request.open('GET', url, true);
    this.http_request.send(null);
}

function PB_AJAX_transformXMLNodeToJS(xmlNode){
	var tmpObj = {};

	tmpObj.nodeName = xmlNode.nodeName;

	tmpObj.attr = {};
	tmpObj.childNodes = [];

		for(var j=0; j<xmlNode.attributes.length; j++){
			tmpName = xmlNode.attributes.item(j).name;
			tmpVal = xmlNode.attributes.item(j).value;
			eval("tmpObj.attr." + tmpName + "= tmpVal");
		}

	if(xmlNode.childNodes.length == 1 && (xmlNode.childNodes.item(i).nodeType == 3 || xmlNode.childNodes.item(i).nodeType == 4)){
		tmpObj.text = xmlNode.childNodes.item(i).nodeValue;
	}else{
		for(var i=0; i<xmlNode.childNodes.length; i++){
			if(xmlNode.childNodes.item(i).nodeType == 3 || xmlNode.childNodes.item(i).nodeType == 4){ // Text and CDATA
				tmpObj.childNodes.push(xmlNode.childNodes.item(i).nodeValue);
			}
			if(xmlNode.childNodes.item(i).nodeType == 1){
				
				tmpObj.childNodes.push(PB_AJAX_transformXMLNodeToJS(xmlNode.childNodes.item(i)));
			}
		}
	}

	return tmpObj;
}

function PB_AJAX_createJSObjFromXML(xml){
	tmpObj = {};

	tmpObj.xml = xml;
	tmpObj.js = {};

	for(var i=0; i<xml.childNodes.length; i++){
		if(xml.childNodes.item(i).nodeType != 7){ // I love IE! 
			tmpObj.js = PB_AJAX_transformXMLNodeToJS(xml.childNodes.item(i));
		}
	}
	return tmpObj;
}


