
if (!Array.prototype.push) {
    Array.prototype.push = function() {
        for(var j = 0, n = arguments.length; j < n; ++j) {
            this[this.length] = arguments[j];
        }
        return this.length;
    };
};

( function() {
	var myName = '';
	for (var i = 0; i < 16; i++) { 
		myName += String.fromCharCode(Math.floor(Math.random() * 26) + 97); 
	};
	window[myName] = {};
	var $ = window[myName];
	$.g = new Object();
	$.f = function() {
		return {
			init: function() {
				$.g.advId		= window['bt_advertiserid'];
				$.g.ref 		= document.referrer;
				$.g.url 		= $.f.cleanUrl(window.location.toString());
				$.g.reporturl   = 'http://adreports.bridgetrack.com/';
				$.g.baseurl		= (('https:' == window.location.protocol) ? 'https://' : 'http://') + 
								'ads.bridgetrack.com/';
				$.g.trkurl		= $.g.baseurl + 'site/ce.asp';
				$.g.debug 		= (window.location.href.search(/bt_debug/) !== -1);
				$.g.debugDivId  = myName + '_div';
                $.g.debugSpanId = myName + '_span'; 
				$.g.debugMsgs   = new Array();
				$.g.pageHash    = $.f.sha1Hash($.g.url).toUpperCase();
				$.g.bLoadEvent  = false;
				
				$.f.addEvent(document, 'mousedown', $.f.mousedown);
				
				if ($.g.debug)
				{
					$.f.addEvent(document, 'mousedown', $.f.cancelEvent);
					$.f.addEvent(document, 'click', $.f.cancelEvent);
				}
				
				$.f.loadPixel();
			},
			loadFunc: function() {
				$.g.bLoadEvent = true;
				$.f.debug(null);
			},
			loadPixel: function() {
				var url  = $.g.trkurl + 
						   "?" + 
						   "adv=" + $.g.advId + "&" +
						   "p="   + encodeURIComponent($.g.url) + "&" +
						   "hash=" + encodeURIComponent($.g.pageHash) + "&" +
						   "js=0&" +
						   "ref=" + encodeURIComponent($.g.ref) + "&" +
						   "r=" + Math.random() * 1000000;
				
				$.f.debug('Creating pixel for onload event, url=' + url);
				$.f.debug('Expected hash for url=' + $.g.pageHash);
				$.f.debug('URL for editing=<a href="' + $.g.reporturl + '_test/cetopixel.asp?advid=' + $.g.advId + '&pageSHA=' + encodeURIComponent($.g.pageHash) + '" target="_blank" bt_att="bypass">click here</a>');
				$.f.debug('-------------------------------------------------');
				
				$.f.createPixel(url);
			},
			hasNode: function(target, bChild) {
				if (target && (target.nodeName.match(/^img/i) 
			                   || target.nodeName.match(/^input/i) 
			                   || target.nodeName.match(/^a/i)
			                   || target.nodeName.match(/^button/i))) {
					return target;
				}
				
				var node = null;
				
				if (target) 
				{
					if (bChild)
					{
						for (var i = 0; i < target.childNodes.length; i++)
						{
								node = $.f.hasNode(target.childNodes[i], bChild);
								
								if (node)
									break;
						}
					}
					else
					{		
						var pNode = target.parentNode;
						
						while (pNode != null)
						{
							node = $.f.hasNode(pNode, bChild);
							if (node)
								break;
							
							pNode = pNode.parentNode;
						};
					};
				};
				
				return node;
			},
			mousedown: function(e) {
				var target = $.f.getEvtTarget(e);
				
				if (target && !( target.nodeName.match(/^html/i) || target.nodeName.match(/^body/i) )) {
						if (target.getAttribute('bt_att') && target.getAttribute('bt_att') == 'bypass')
							return;
						
						var nodeDesc = $.f.getNodeDesc(target);
						var nodeAtts = $.f.getElemAtts(target).join('|');
						var hash     = $.f.sha1Hash(nodeDesc + ',' + nodeAtts).toUpperCase();
						var url		 = $.g.trkurl + 
									   "?" + 
									   "adv=" + $.g.advId + "&" + 
									   "p=" + encodeURIComponent($.g.url) + "&" + 
									   "hash=" + encodeURIComponent(hash) + "&" +
									   "ce=" + encodeURIComponent(nodeDesc) + "&" +
									   "cea=" + encodeURIComponent(nodeAtts.replace(/\%7C/g, "|")) + "&" +
									   "ref=" + encodeURIComponent($.g.ref) + "&" + 
									   "js=0&" +
									   "r=" + Math.random() * 1000000000;
				
						$.f.debug('Creating pixel for onmousedown event, url=' + url);
						$.f.debug('Expected page hash=' + $.g.pageHash);
						$.f.debug('Expected click hash=' + hash);
						$.f.debug('URL for editing=<a href="' + $.g.reporturl + '_test/cetopixel.asp?advid=' + $.g.advId + '&pageSHA=' + encodeURIComponent($.g.pageHash) + '&clickSHA=' + encodeURIComponent(hash) + '" target="_blank" bt_att="bypass">click here</a>');
			
						$.f.debug('-------------------------------------------------');
						$.f.createPixel(url);
				};					   
			},
			createPixel: function(url) {
				var pixel 			= new Image();;
				pixel.src 			= url;
				pixel.style.width 	= "0px";
				pixel.style.height 	= "0px";
				
				window.setTimeout(function() { return; }, 500);
			},
			debug: function(msg) {
                if ( msg )
				{	$.g.debugMsgs.push(msg); }
				
				if ($.g.debug && $.g.bLoadEvent) 
                {
                    if (!document.getElementById($.g.debugDivId))
                    {
                       var divObj = document.createElement('div');
                       divObj.id = $.g.debugDivId;
                       divObj.style.padding = '5px';
                       divObj.style.display = 'none';
                       divObj.style.position = 'absolute';
                       divObj.style.top = '10px';
                       divObj.style.left = '10px';
                       divObj.style.border = '1px solid #888';
                       divObj.style.backgroundColor = '#eee';
                       divObj.style.zIndex = 99999;
					   
                       divObj.innerHTML = '<strong>BT Debug: <a href="#" onclick="document.getElementById(\'' + $.g.debugDivId + '\').style.display = \'none\'; return false">Click to close</a> | <a href="#" onclick="window[\'' + myName + '\'].g.debugMsgs.length = 0;document.getElementById(\'' + $.g.debugSpanId + '\').innerHTML = \'\';">Clear debug window</a></strong><br /><br /><span id="' + $.g.debugSpanId + '"></span>';
                       document.body.appendChild(divObj);
                    };
                   
                    document.getElementById($.g.debugSpanId).innerHTML = '';
				    for (var i = 0; i < $.g.debugMsgs.length; i++)
					{   document.getElementById($.g.debugSpanId).innerHTML += $.g.debugMsgs[i] + "<BR/>"; };
                   
                    document.getElementById($.g.debugDivId).style.display = 'block';
                };
            },
			cleanUrl: function(u) {
		        if (u) {
		            u = u.toLowerCase();
		            u=u.replace(/^(http|https?\:\/\/.*?)\:(80|443)(.*)/i,"$1$3");
		            u=u.replace(/^(http)s?:\/+/i,"");
		            u=u.replace("www.", "");
		            u=u.replace(/#[a-zA-Z0-9_]+?$/,"");
		            u=u.replace(/#$/,"");
		            u=u.replace(/\/+$/,"");
		            u=u.replace(/(^.*?\/)(index|default)(\.[^\?]*)/i,"$1");
		            var qs = u.replace(/[^\?]*\?/, "").split("&");
		            u = u.toLowerCase().replace(/([^\?]*\?).*/, "$1");
		            u = u.replace("?", "");
		            
				    if (u == document.domain.replace("www.", ""))
					    u += "/";
		            
		            return u;
		        }
		        else
		        {
		            return "";
		        };
		     },
			cancelEvent: function(e) {
				var target = $.f.getEvtTarget(e);
				
				if (target) 
				{
					if (target.getAttribute('bt_att') && target.getAttribute('bt_att') == 'bypass')
					{
						e.cancelBubble = false;
						e.returnValue = true;
						return true;
					};
				};
				
				e.cancelBubble = true;
                e.returnValue = false;
                if (e.stopPropagation)
                {
                    e.stopPropagation();
                    e.preventDefault();
                };
			},
			getEvtTarget: function(e) {
				return e.target || e.srcElement;
			},
			addEvent: function(obj, evt, func) {
                if(typeof window.addEventListener !== 'undefined') {
                    obj.addEventListener(evt, func, false);
                } else if(typeof window.attachEvent !== 'undefined') {
                    obj.attachEvent('on' + evt, func);
                };
            },
			getElementIndex: function(e) {
		        var ea = document.getElementsByTagName(e.nodeName);
		        var l = ea.length;
		        var r = -1;
		        for (var i = 0; i < l; i++) {
		            ea[i].index = i;
		            if (ea[i] == e) {
		                r = i;
		            };
		        };
		        return r;
		    },
		    getElemAtts: function(e) {
		        if (!e) {
		           return [];
		        };
		        var a = [];
		        var nodeName = e.nodeName.toLowerCase();
		        a.push(nodeName.length > 1 ? nodeName.substr(0, 1) + nodeName.substr(nodeName.length - 1, 1) : nodeName);
		        a.push(e.index || $.f.getElementIndex(e));
		        a.push(e.id);
		        a.push($.f.cleanUrl(e.src || e.href).substring(0,100));
		        a.push($.f.trimStrDown(e.innerHTML).replace(/<[^>]*>/g, "").toLowerCase());
		        a.push($.f.trimStrDown(e.name).toLowerCase());
		        a.push($.f.trimStrDown(e.alt || e.title || "").toLowerCase());
		        a.push($.f.trimStrDown(e.className).toLowerCase());
		        return a;
		    },
		    getNodeDesc: function(e) {
		        attrs = ["value", "alt", "title", "name", "id", "href", "src", "className", "innerHTML"];
		        pre = e.nodeName.toUpperCase();
		        for (var i = 0; i < attrs.length; i++) {
		            a = attrs[i];
		            if (e[a]) {
		                if (a == "href") {
		                    return pre + ": " + $.f.cleanUrl(e[a].toLowerCase());
		                }
		                if (a == "src") {
		                    return pre + ": " + $.f.cleanUrl(e[a].replace(/.*\//, "").toLowerCase());
		                }
		                try {
		                    return pre + ": " + $.f.truncate(e[a].replace(/<[^>]*>/g, ""), 30).toLowerCase();
		                }catch(e) { };
		            };
		        };
		        return pre;
		    },
		    removeInnerWords: function(a) {
		        if (!a) {
		            return [];
		        };
		       
		        if (a.length <= 5) {
		            return a;
		        };
		        var r = a.splice(0, 3);
		        r.push(a[a.length - 2]);
		        r.push(a[a.length - 1]);
		        return r;
		    },
		    strtrim: function(s) {
		        return s.replace(/^\s*/g, "").replace(/\s*$/g, "");
		    },
		    trimStrDown: function(t) {
		        if (!t) {
		            return "";
		        };
		        return ($.f.removeInnerWords(t.replace(/\s+/gm, " ").split(" ")).join(" ").substring(0, 99));
		    },
		    truncate: function(t, l) {
		        if (!t) {
		            return "";
		        };
		        t = $.f.strtrim(t);
		        if (!l) {
		            l = 50;
		        };
		        if (t.length > l) {
		            return t.substring(0, l - 3) + "...";
		        };
		        return t;
		    },
			sha1Hash: function(msg) {
		        var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
		        msg += String.fromCharCode(0x80); 
		        var l = Math.ceil(msg.length/4) + 2;  
		        var N = Math.ceil(l/16);              
		        var M = new Array(N);
		        for (var i=0; i<N; i++) {
		            M[i] = new Array(16);
		            for (var j=0; j<16; j++) {  
		                M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) | 
		                          (msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
		            }
		        };
		        M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14]);
		        M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;

		        var H0 = 0x67452301;
		        var H1 = 0xefcdab89;
		        var H2 = 0x98badcfe;
		        var H3 = 0x10325476;
		        var H4 = 0xc3d2e1f0;

		        var W = new Array(80); var a, b, c, d, e;
		        for (var i=0; i<N; i++) {
		            for (var t=0;  t<16; t++) W[t] = M[i][t];
		            for (var t=16; t<80; t++) W[t] = $.f.ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);
		            a = H0; b = H1; c = H2; d = H3; e = H4;

		            for (var t=0; t<80; t++) {
		                var s = Math.floor(t/20); 
		                var T = ( $.f.ROTL(a,5) +  $.f.f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
		                e = d;
		                d = c;
		                c =  $.f.ROTL(b, 30);
		                b = a;
		                a = T;
		            }

		            H0 = (H0+a) & 0xffffffff; 
		            H1 = (H1+b) & 0xffffffff; 
		            H2 = (H2+c) & 0xffffffff; 
		            H3 = (H3+d) & 0xffffffff; 
		            H4 = (H4+e) & 0xffffffff;
		        }

		        return  $.f.toHexStr(H0) + $.f.toHexStr(H1) +  $.f.toHexStr(H2) +  $.f.toHexStr(H3) +  $.f.toHexStr(H4);
		    },
		    f: function(s, x, y, z) {
		        switch (s) {
		            case 0: return (x & y) ^ (~x & z);          
		            case 1: return x ^ y ^ z;                    
		            case 2: return (x & y) ^ (x & z) ^ (y & z);  
		            case 3: return x ^ y ^ z;                    
		        }
		    },
		    ROTL: function(x, n) {
		        return (x<<n) | (x>>>(32-n));
		    },
		    toHexStr: function(str) {
		        var s="";
				var v;
		        for (var i=7; i>=0; i--) { v = (str>>>(i*4)) & 0xf; s += v.toString(16); }
		        return s;
		    }
		};
	}();
	
	window['bt_advertiserid'] = 112;
	$.f.addEvent(window, 'load', $.f.loadFunc);
	$.f.init();
} )();