// begin cbltpxl.js
//
// Cobalt Pixel Tag javascript v0.1
// Hawk Newton <hnewton@cobaltgroup.com>
//
// Copyright 2008 Cobalt Group inc, All Rights Reserved
//
// Constructor:
// 		All fields are required.
//
//      var pixelTag = new CBLTPixelTag({
//                                siteId: 'siteId',
//                                pageName: 'pageName',
//                                pageLabel: 'pageLabel',
//                                pageLayout: 'pageLayout'});
//
//
// After you've instantiated the object you can call one of the below methods:
//
// Fire page render:
//		pixelTag.firePageRender();
//
//
// Fire inventory search event:
//		Optional fields are noted, all others are required
//
//		pixelTag.fireInventorySearch({
//                                searchType: 'New',			// must be New, Used, or All
//                                vehicleType: 'Truck',			// optional
//                                vehicleMake: 'GMC',
//                                vehicleModel: 'BFT',
//                                priceRange: '10000-50000',	// optinal, must be in high-low format
//                                yearRange: '2007-2008',		// optinal, must be in high-low format
//                                mileageRange: '0-100'});		// optinal, must be in high-low format
//
//
// View vehicle:
//		VIN is optional but *HIGHLY* desired.
//
//		pixelTag.fireVehicleView({vin: '123123123ZXCX2'});
//
//
// Lead Submission:
//		The ID is the id of the lead.  You can generate your own UUID if need be.
//
//		pixelTag.fireLeadSubmit({id: '123123123SDFSAF'});

//alert("divij");

function CBLTPixelTag(arg) {
  this.siteId = escape(arg.siteId);
  this.pageName = escape(arg.pageName);
  this.pageLabel = escape(arg.pageLabel);
  this.pageLayout = escape(arg.pageLayout);
};

CBLTPixelTag.prototype.firePageRender = function() {
  var pixelTag = CBLTPixelTag.createCommonTag(this);
  CBLTPixelTag.appendTag(pixelTag);
};

CBLTPixelTag.prototype.fireInventorySearch = function(inventory) {
  var pixelTag = CBLTPixelTag.createCommonTag(this);
  
  pixelTag += '&inventory_search_type=' + escape(inventory.searchType);
  pixelTag += '&cs:i:vt=' + escape(inventory.vehicleType ? inventory.vehicleType : 'All');
  pixelTag += '&inventory_make=' + escape(inventory.vehicleMake);
  pixelTag += '&inventory_model=' + escape(inventory.vehicleModel);
  pixelTag += '&cs:i:pr=' + escape(inventory.priceRange ? inventory.priceRange : 'unspecified');
  pixelTag += '&cs:i:pay=' + escape(inventory.payRange ? inventory.payRange : 'unspecified');
  pixelTag += '&cs:i:y=' + escape(inventory.yearRange ? inventory.yearRange : 'unspecified');
  pixelTag += '&cs:i:mi=' + escape(inventory.mileageRange ? inventory.mileageRange : 'unspecified');
  pixelTag += '&cs:loc=' + escape(inventory.locale ? inventory.locale : 'en_US');
  
  CBLTPixelTag.appendTag(pixelTag);
};

CBLTPixelTag.prototype.fireVehicleView = function(vehicle) {
  var pixelTag = CBLTPixelTag.createCommonTag(this);
  
  pixelTag += '&cs:i:vin=' + escape(vehicle.vin ? vehicle.vin : 'NULL');
  
  CBLTPixelTag.appendTag(pixelTag);
};

CBLTPixelTag.prototype.fireLeadSubmit = function(lead) {
  var pixelTag = CBLTPixelTag.createCommonTag(this);
  
  pixelTag += '&cs:l=' + escape(lead.id ? lead.id : 'NULL');
  CBLTPixelTag.appendTag(pixelTag);
};

//
// Private below
//

CBLTPixelTag.createCommonTag = function(tag) {
  var eventId = 'js-' + new UUID();
  var sessionId = 'js-' + CBLTPixelTag.getOrCreateId('cbltSessionId', 1800);		// 30 minutes
  var visitorId = 'js-' + CBLTPixelTag.getOrCreateId('cbltVisitorId', 5256000);	// 10 years

  var request = CBLTPixelTag.prepareURI(location.href);
  var requestHost = request.domain;
  var requestURI = request.uri;

  var referrerHost;
  var referrerURI;

  if(typeof(document.referrer) != 'undefined' && document.referrer != '') {
    var referrer = CBLTPixelTag.prepareURI(document.referrer);
    referrerHost = referrer.domain;
    referrerURI = referrer.uri;
  }

  var pixelTag = 'header_event_id=' + eventId + '&header_session_id=' + sessionId + '&header_visitor_id=' + visitorId + '&header_request_domain=' + requestHost + '&header_request_uri=' + requestURI;

  pixelTag += referrerHost ? '&header_referrer_domain=' + referrerHost : '';
  pixelTag += referrerURI ? '&header_referrer_uri=' + referrerURI : '';
  
  // add the site id, page name, page label, and page layout
  pixelTag += '&header_site_id=' + tag.siteId + '&header_page_name=' + tag.pageName + '&header_page_label=' + tag.pageLabel + '&header_page_layout=' + tag.pageLayout;
  
  pixelTag = 'http://traffic.prod.cobaltgroup.com/websites.gif?' + pixelTag;

  return pixelTag;
};

CBLTPixelTag.appendTag = function(pixelTag) {
  var img = new Image();
  img.src = pixelTag;
  img.onload = CBLTPixelTag.empty;
};

// Shrug ... It's the way google does it, for some reason
CBLTPixelTag.empty = function() {};

CBLTPixelTag.readCookie = function(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);
    }
  }
};

CBLTPixelTag.setCookie = function(name, value, exdate) {
  document.cookie=name+ "=" + escape(value) + ";expires="+exdate.toGMTString();
};

CBLTPixelTag.getOrCreateId = function(name, expireSeconds) {
  var value = CBLTPixelTag.readCookie(name);

  if(typeof(value) == 'undefined' || value == '') {
    value = new UUID();
  }

  var expireDate = new Date();
  expireDate.setTime(expireDate.getTime() + (expireSeconds * 1000));
  CBLTPixelTag.setCookie(name, value, expireDate);
  
  return value;
};

CBLTPixelTag.prepareURI = function(str) {
  var uri = parseUri(str);
  
  return {
    domain: uri.host,
    uri: (uri.path ? uri.path : '/') + escape(uri.query ? '?' + uri.query : '')
  };
};

// END cbltpxl.js stuff.  The below is all totally unmodified and legal.

// BEGIN uuid.js
/*
uuid.js - Version 0.2
JavaScript Class to create a UUID like identifier

Copyright (C) 2006-2008, 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
5/22/08 - Updated code to run faster, removed randrange(min,max) in favor of
          a simpler rand(max) function. Reduced overhead by using getTime() 
          method of date class (suggestion by James Hall).

KNOWN ISSUES:
- Still no way to get MAC address in JavaScript
- Research into other versions of UUID show promising possibilities 
  (more research needed)
- Documentation needs improvement

*/

// 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(){
	//
	// 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 = new Date(1582, 10, 15, 0, 0, 0, 0);
	var dc = new Date();
	var t = dc.getTime() - dg.getTime();
	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.rand(4095),0,7);
	var csl = UUID.getIntegerBits(UUID.rand(4095),0,7);

	// since detection of anything about the machine/browser is far to buggy, 
	// include some more random numbers here
	// if NIC or an IP can be obtained reliably, that should be put in
	// here instead.
	var n = UUID.getIntegerBits(UUID.rand(8191),0,7) + 
			UUID.getIntegerBits(UUID.rand(8191),8,15) + 
			UUID.getIntegerBits(UUID.rand(8191),0,7) + 
			UUID.getIntegerBits(UUID.rand(8191),8,15) + 
			UUID.getIntegerBits(UUID.rand(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;
}

// pick a random number within a range of numbers
// int b rand(int a); where 0 <= b <= a
UUID.rand = function(max){
	return Math.floor(Math.random() * max);
}

// END uuid.js

// BEGIN parseUri.js
/*
	parseUri 1.2.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT License
*/

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};
// END parseUri.js
