var _ASqwsUrl;
var _ASeventId;
var _ASamount;
var _ASeventType;
var _ASsourceId;
var _ASa;
var _ASv;

function randomString() {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 18;
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return randomstring;
}

function isHostName(hostname)
{ 
    var window_name = window.location.hostname.replace('www.', '');
    return hostname == window_name; 
}

function StatTrack() {
    this.cs_init = function(neutron_adid, hit) {
        //neutron_adid = this.getADID(document.URL);
        //this.cs_click();

        if (typeof neutron_adid == 'undefined') {
            neutron_adid = '';
        }

        if (typeof hit == 'undefined') {
            hit = true;
        }

        if (typeof adid == "string"){
            neutron_adid = adid;
        }

        // Let's try 1 last time to get an adid
        if(neutron_adid == ''){
            neutron_adid = this.getADID(document.URL);
        }

        if (typeof affiliate_id == 'undefined') {
            affiliate_id = '0';
        }

        if (typeof sub_campaign == 'undefined') {
            sub_campaign = '';
        }

        i = new Image(1, 1);
        w = screen.width;
        h = screen.height;
        i.src = "http://www.neutronstats.com/track.php?a="+neutron_adid+"&r="+escape(document.referrer)+"&w="+w+"&h="+h+"&p="+escape(document.URL)+"&affiliate_id="+affiliate_id+"&sub_campaign="+sub_campaign+"&hit="+(hit ? "y" : "n");

        if(isHostName("explore-schools.com") || isHostName("collegesurfing.com") || isHostName("earnmydegree.com")) {
            this.track_conversion();
        }
    };

    this.track_conversion = function(conv_value, lead_id) {
        if( undefined == conv_value || '' == conv_value )
            conv_value = undefined;
        if( undefined == lead_id || '' == lead_id )
            lead_id = undefined;

        this.get_hitpagetracking_id(function(hptid) {
            if(isHostName("explore-schools.com") || isHostName("collegesurfing.com")) {
                document.write(unescape("%3Cimg src='https://www.emjcd.com/u?AMOUNT=0&CID=1519710&OID=P-"+hptid+"&TYPE=341916&CURRENCY=USD&METHOD=IMG' height='1' width='20'%3E"));
            } else if (isHostName("earnmydegree.com")) {
                document.write(unescape("%3Cimg src='https://www.emjcd.com/u?AMOUNT=0&CID=1519710&OID=P-"+hptid+"&TYPE=341917&CURRENCY=USD&METHOD=IMG' height='1' width='20'%3E"));
            }
        });

        var ga_conv_value = (undefined == conv_value) ? "1" : conv_value;
        
        // TESTING: Enabling tracking on one dmoain at a time.
        if( isHostName("collegeoverview.com"))
        {
            // Main acct.
            document.write(unescape("%3Cimg height='1' width='1' style='border-style:none;' alt='' src='http://www.googleadservices.com/pagead/conversion/1072511217/?value="+ga_conv_value+"&label=lead&amp;guid=ON&amp;script=0'%2F%3E"));
            // Acct. 4
            document.write(unescape("%3Cimg height='1' width='1' style='border-style:none;' alt='' src='http://www.googleadservices.com/pagead/conversion/1049703532/?value="+ga_conv_value+"&label=XbeKCL6q3AEQ7OjE9AM&amp;guid=ON&amp;script=0'%2F%3E"));
            // Acct. 2
            document.write(unescape("%3Cimg height='1' width='1' style='border-style:none;' alt='' src='http://www.googleadservices.com/pagead/conversion/1037938829/?value="+ga_conv_value+"&label=46UkCKev5QEQjeH27gM&amp;guid=ON&amp;script=0'%2F%3E"));
            // Acct. 3
            document.write(unescape("%3Cimg height='1' width='1' style='border-style:none;' alt='' src='http://www.googleadservices.com/pagead/conversion/1050809176/?value="+ga_conv_value+"&label=boukCOy4xQEQ2KaI9QM&amp;guid=ON&amp;script=0'%2F%3E"));
        }
        // END TESTING

        document.write(unescape("%3Cimg height='1' width='1' style='border-style:none;' alt='' src='http://conv.indeed.com/pagead/conv/7582565760000597/?script=0'%2F%3E"));
        document.write(unescape("%3Ciframe src='http://flex.atdmt.com/mstag/tag/d1d8803f-4e67-4775-b13c-d61f8bdad46e/conversion.html?cp=5050&dedup=1' frameborder='0' scrolling='no' width='1' height='1' style='visibility:hidden; display:none'%3E %3C%2Fiframe%3E"));
        document.write(unescape("%3Cimg src='http://www.exchngtrak.com/adserver/service/ad/conversion/tracker/106?adid=3686' height='1' width='1' border='0'%2F%3E"));
        document.write(unescape("%3Cimg src='http://www.exchngtrak.com/adserver/service/ad/conversion/tracker/2000?adid=3685' height='1' width='1' border='0'%2F%3E"));
        document.write(unescape("%3Cimg src='http://www.clickstax.com/adserver/service/ad/conversion/tracker/2000?adid=3762' height='1' width='1' border='0'%2F%3E"));
        //document.write(unescape("%3Cimg src='https://bidsystem.adknowledge.com/conversion.php?cid=1b9a7f6a-e344-42c8-8ebc-73064bc2c372' height='1' width='1' border='0'%2F%3E")); // Removed as per LAngus 2011-11-11 (elevenses!)

        var rnd=10000000000*Math.random();
        document.write(unescape("%3Cimg src='http://conv.opt.fimserve.com/conv/52164/?rnd="+rnd+"' width='1' height='1' border='0'%2F%3E"));

        document.write(unescape("%3Cimg src='https://tracking.admarketplace.net/tracking?pid=3430&fc=1&cid=7942&eventid=0&orderval=0.00&v=2&orderid=&custominfo=' width='1' height='1' border='0'%2F%3E"));

        if (affiliate_id == "L01YZFJV") {
            var cv = (undefined == conv_value) ? 1.0 : parseFloat(conv_value);
            var _mf_lead_id = (undefined == lead_id) ? ''+Math.ceil(Math.random()*9999999) : lead_id;  
            if (isNaN(cv)) cv = 0.00;
            cv = cv * 0.5;
            cv = cv.toFixed(2);
            var _mfURL='https://tags.mediaforge.com/js/354/?orderNumber='+_mf_lead_id+'&price='+cv;
            document.write('<scr'+'ipt type="text/javascript" '+'src="'+_mfURL+'"></scr'+'ipt>');
        }

        // Inject Adobe Test+Target conversion mBox. 
        try {
            document.write('<scr'+'ipt type="text/javascript" src="http://neutronstats.com/js/mbox.js"></scri'+'pt>');
            document.write('<div class="mboxDefault">&nbsp;</div><scr'+'ipt type="text/javascript">mboxCreate("confirmationMbox", "lead_id='+lead_id+'");</scr'+'ipt>');
        } catch(err) {}

        // Inject AdCylinder conversion tracking
        try{
            document.write('<img src="http://www.AdCylinder.com/adserver/service/ad/conversion/tracker/3000?adid=3912" height="1" width="1" border="0" />');
            document.write('<img src="http://www.AdCylinder.com/adserver/service/ad/conversion/tracker/3000?adid=3967" height="1" width="1" border="0" />');
            document.write('<img src="http://www.AdCylinder.com/adserver/service/ad/conversion/tracker/3000?adid=3918" height="1" width="1" border="0" />');
            document.write('<img src="http://www.AdCylinder.com/adserver/service/ad/conversion/tracker/3000?adid=3913" height="1" width="1" border="0" />');
        } catch(err) {}

        // Inject Adblade conversion tracking
        try{
            document.write('<img src="http://web.adblade.com/orders.php?id=12795" height="1" width="1" border="0" />');
        } catch(err) {}

        // Inject Google Analytics conversion tracking
        try {
            if( undefined !== lead_id ) {
                var _gaq = _gaq || [];
                var _gaq_accts = ['UA-2392727-37'];
                var _gaq_conv_val = (undefined == conv_value) ? 0.00 : conv_value;
                var _gaq_lead_id = lead_id.toString();

                for( var i in _gaq_accts ) {
                    _gaq.push(
                            ['_setAccount', _gaq_accts[i]], 
                            ['_trackPageview'], 
                            ['_addTrans', _gaq_lead_id, '', _gaq_conv_val],
                            ['_trackTrans']
                            );
                }
                (function() {
                    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
                })();
            }
        } catch(err) {}

        // Inject AOL adsonar conversion tracking
        try {
            var as_conv_value = (undefined == conv_value) ? "1" : conv_value;
            _ASeventId = (lead_id == undefined) ? " " : lead_id;
            _ASamount=as_conv_value;
            _ASeventType="Sale";
            _ASsourceId="your-source-id";
            _ASqwsUrl=(location.protocol=="https:" ? "https://roi.adsonar.com/process" : "http://roi.adsonar.com/process");
            _AShostedUrl=(location.protocol=="https:" ? "https://secure-js.adsonar.com/process" : "http://js.adsonar.com/process");
            _ASa="TLpkb8nC%2Fdc4R7HCPYA%3D";
            _ASv="1.16";
            document.write('<scr'+'ipt type="text/javascript" src="'+_AShostedUrl+'/roi/roi.js?t='+new Date().getTime()+'"></scr'+'ipt>');
        }
        catch(err){}

        // Remarket beacons
        try {
            document.write('<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1072511217/?label=db39CKTVsAIQ8fG0_wM&amp;guid=ON&amp;script=0"/>');
            document.write('<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1072511217/?label=nlW6CLTTsAIQ8fG0_wM&amp;guid=ON&amp;script=0"/>');
            document.write('<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1072511217/?label=arbuCMzQsAIQ8fG0_wM&amp;guid=ON&amp;script=0"/>');
            document.write('<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1072511217/?label=7eT6CNzOsAIQ8fG0_wM&amp;guid=ON&amp;script=0"/>');
            document.write('<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1072511217/?label=U6B9CPTLsAIQ8fG0_wM&amp;guid=ON&amp;script=0"/>');
            document.write('<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1072511217/?label=m4WqCJTIsAIQ8fG0_wM&amp;guid=ON&amp;script=0"/>');
        }
        catch(err) {}

        // Adknowledge Conversion Tag 
        try {
            var adk = document.createElement('script');
            adk.type = 'text/javascript';
            adk.async = true;
            adk.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'bidsystem.adknowledge.com/conversion.js?cid=1b9a7f6a-e344-42c8-8ebc-73064bc2c372';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(adk, s);
        }
        catch(err) {}
    };

    this.getADID = function(str) {
        // find all adid=XXX patterns in provided string
        var matches = (str+'').match(/adid=([A-Z0-9]*)/gi);

        if (matches && matches.length > 0) { // found some
            var len = matches.length;

            // scan from end to first, finding first non-empty adid
            for (var i = len-1; i >= 0; i--) {
                str = matches[i].replace(/^adid=/i, '');
                if (str.replace(/\s+/, '') != '') return str;
            }
        }

        return '';
    };

    this.store_school_page_view = function(s2_id,pd_id) {
        i = new Image(1, 1);
        w = screen.width;
        h = screen.height;
        i.src = "http://www.neutronstats.com/store_school_page_view.php?s2_id="+s2_id+"&pd="+pd_id;
    };

    this.store_search_page_view = function(pd_id,type,postal) {
        i = new Image(1, 1);
        w = screen.width;
        h = screen.height;
        i.src = "http://www.neutronstats.com/store_search_page_view.php?type="+type+"&pd="+pd_id+"&postal="+postal;
    };

    this.associate = function(neutron_adid, lid) {
        var img = new Image(1,1);
        img.src = "http://www.neutronstats.com/associate.php?ld="+lid;
    };

    this.get_hittracking_id = function(callback) {
        var has_cb = (typeof callback == 'function'), _this = this;

        // checked for cached value
        if (typeof this._hittracking_id != 'undefined') {
            if (has_cb) callback(this._hittracking_id);
        }

        var process = function() {
            $.getJSON('http://www.neutronstats.com/get_hittracking_id.php?callback=?', function(data) {
                var ht_id = data.hitTrackingId || 0;  
                if (ht_id) _this._hittracking_id = ht_id;
                callback(ht_id);
            });
        };

        ( function() {    
            if (typeof jQuery == 'undefined') { 
                var script = document.createElement('script');
                script.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js');
                var head = document.getElementsByTagName("head")[0]; 
                script.onload= process;
                head.appendChild(script);
            } else { 
                process();
            }
        })();
    };

    this.get_hitpagetracking_id = function(callback) {
        var has_cb = (typeof callback == 'function'), _this = this;

        // checked for cached value
        if (typeof this._hitpagetracking_id != 'undefined') {
            if (has_cb) callback(this._hitpagetracking_id);
        }

        var process = function() {
            $.getJSON('http://www.neutronstats.com/get_hitpagetracking_id.php?callback=?&p='+escape(document.URL)+'&r='+escape(document.referrer), function(data) {
                var hpt_id = data.hitPageTrackingId || 0;  
                if (hpt_id) _this._hitpagetracking_id = hpt_id;
                callback(hpt_id);
            });
        };

        ( function() {
            if (typeof jQuery == 'undefined') { 
                var script = document.createElement('script');
                script.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js');
                var head = document.getElementsByTagName("head")[0]; 
                script.onload= process;
                head.appendChild(script);
            } else { 
                process();
            }
        })();
    };
}


