/*

 This file contains click tracking functionality for the internal
 applegate statistics modules.

 */

// Add more to array (lower cased) as necessary (just include domain)
    var exclusionList = ['babcock-wanson.co.uk',
    'nordairniche.co.uk','haigh.co.uk','reznor.co.uk','binderuk.com','airbloc.co.uk','lindenmanagement.org.uk','amarinth.com','djsresearch.co.uk','hphydraulics.co.uk','ott-hydrometry.co.uk','gpegint.com','jmlengineering.co.uk','bucks-metalworkers.co.uk','ArcticStore.co.uk','strainsense.co.uk','kedon.co.uk','emerson.com','yorkshirebusinesssystems.co.uk','habia.com','mainco.co.uk','tayco.co.uk','agrimin.com','flaktwoods.com','indexplastics.co.uk','holztechnik-machinery.co.uk','keesafety.com','dek.com','kurz.co.uk','martinairltd.com','escalatorrepairs.co.uk','mul-t-lock.co.uk','docscanning.co.uk','flight-cases.biz','mkprofiles.co.uk','kmf.co.uk','ambirad.co.uk','parker.com','corintech.com','bostik.co.uk','walker-rubber.co.uk','interform-uk.com','keysplease.co.uk','timcal.com','abbfab.co.uk','home-phones.co.uk','feredaycylinder.co.uk','ukplasticrecycling.co.uk','brydianplasticcards.co.uk','theforge-iw.co.uk','basiliskdata.co.uk','foodmc.co.uk','phoenix-components.com','receiptbook.co.uk','boulting.co.uk','meech.com','fibrestar.co.uk','norfolkwater.co.uk','solarpanelinstallersuk.co.uk','airsupplyne.com','tandlengineering.co.uk','catalysts.basf.co.uk','uk.endress.com','protoelect.co.uk','networkscientific.co.uk','stormsaver.com','google.co.uk'];

 // Send inline log request from this page if a traceUrl available.

if(window.traceUrl) {
	recordLog('/log.php'+window.traceUrl,"PI");
}

function recordLog(url, logType, forwardToUrl) {
	var xmlhttp;
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if(forwardToUrl) {
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				window.location=forwardToUrl;
			}
		}
	}
	
	if(window.pageCategory!== undefined && window.pageCategory.length > 0) {
		url += "&pageCategory=" + window.pageCategory;
	}							
	xmlhttp.open("GET",url+"&event="+logType,true);
	xmlhttp.send();		
}

function isInExclusionList(url) {
   url = url.toLowerCase();
   var i = 0;
   while(i <= exclusionList.length) {
      if(url.indexOf(exclusionList[i])!==-1) {
         return true;
      }
      i++;
   }
   return false;
}

function appendCampaignParameters(url) {
   if(url.indexOf('applegate.co.uk') === -1 && url.indexOf('/') != 0 && !isInExclusionList(url)) {
   	if(url.indexOf('?') === -1) {
      	    return url + '?utm_campaign=applegate.co.uk&utm_medium=referral&utm_source=applegate.co.uk';
   	} else {
            return url + '&utm_campaign=applegate.co.uk&utm_medium=referral&utm_source=applegate.co.uk';
        }
   }
   return url;
}
 
 
/**
 *
 * This method can be called by any page in order to record a GET request
 * to the apache logs.
 *
 * If any kind of error occurs it is just ignored and 'true' is always returned.
 *
 * The format of the request will be:
 *
 *  'http://www.applegate.co.uk/stats/recordClick.html?<type>[&<name>=<value>]
 *
 * Where the variables are populated with parameter data as described below.
 *
 * @param type  This should be a string value that distinguishes the type
 * of statistic that is being regarded.  For example, for an SOL item
 * link the type might be 'SOLITEM'
 *
 * @param args This is a string array of name value pairs using a simillar
 * syntax to request parameters.  Each pair should be a string and
 * follow the '<name>=<value>' syntax, for example: ['name=joe','age=27'].
 * Each item in the array will in fact be added as a parameters to the request
 * made to the statistics servlet.
 */
function recordClick(type, args, forwardToUrl, openInNewWindow) {  
	
    var newWindow = openInNewWindow === undefined ? false : openInNewWindow;
    if(forwardToUrl !== undefined) {
        forwardToUrl = appendCampaignParameters(forwardToUrl);
    }

	// If a new window is requested for the forward-to url then open it immediately.
	// It can't be called on the call-back as this will cause the pop-up to be blocked
	// by most browsers since it isn't user-initiated. If the forward url is in
	// the same window then the redirect can only occur once the click has been logged
	// as it may not happen before the page redirects (since it's asynchronous), so this
	// happens in the callback handler in this case.
	if (forwardToUrl !== undefined && newWindow) {
		window.open(forwardToUrl);
	}
	
	var link = "/stats/recordClick.html";
	varlinkParams = "?type=" + type;
	
        if(args != null){
			for (i = 0; i < args.length; i++) {
			varlinkParams += "&" + args[i];
			}
		}
	// If trace URL is available
	if(window.traceUrl){
		var newLink = '/log.php';
		recordLog(newLink+varlinkParams,'CLICK');
            }


    if (forwardToUrl !== undefined && !newWindow) {
	recordLog(link+varlinkParams, 'CLICK', forwardToUrl);
    } else {
	recordLog(link+varlinkParams,'CLICK');
    }
}

/*
 *   Click stat recording.
 */
var stats = stats;
var agstat_global = stats || {}; // page global stat value, m1 - m8, they will be overridden by values passed to the rc call.
var agstat = (function() {

    var mergeWithGlobals = function(stats) {
        var params = [ 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9', 'm10' ];
        var s = {};
        for(var i=params.length-1; i>=0; i--) {
            s[params[i]] = _overrideGlobalStat(params[i], stats)
        }
        return s;
    }

    /*
        Record click.
        Parameters:
            stats: associative array of the m1-m8 parameters e.g. {m1: 'Company', m2: 'Page', ... }
    */
    var rc = function(stats) {
        var s = mergeWithGlobals(stats.metrics);

        switch(stats.linkType) {
            case 'PARABODY'      :   logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7 }]});
                                     recordClick(stats.linkType, ['companyid='+s.m5, 'sectionid='+s.m6,'m1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7,'website='+stats.url],stats.url,true);
                                     break;
            case 'PARAIMAGE'      :  logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7 }]});
                                     recordClick(stats.linkType, ['companyid='+s.m5, 'sectionid='+s.m6,'m1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7,'website='+stats.url],stats.url,true);
                                     break;
            case 'PARAHEADER'      : logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7 }]});
                                     recordClick(stats.linkType, ['companyid='+s.m5, 'sectionid='+s.m6,'m1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7,'website='+stats.url],stats.url,true);
                                     break;
            case 'SOLITEM'      :   logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7, m8:s.m8 }]});
                                    if(stats.url) {
                                        recordClick(agstat_global.linkType, ['solpartcode='+agstat_global.partCode,'companyid='+s.m5,'m1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7,'m8='+s.m8],stats.url,true);
                                    } else {
                                        recordClick(agstat_global.linkType, ['solpartcode=' + agstat_global.partCode,'companyid=' + s.m5,'m1=' + s.m1,'m2=' + s.m2,'m3=' + s.m3,'m4=' + s.m4,'m5=' + s.m5,'m6=' + s.m6,'m7=' + s.m7,'m8=' + s.m8]);
                                    }
                                    break;
            case 'VIDEOITEM'      :   logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7, m8:s.m8 }]});
                                    if(stats.url) {
                                        if (stats.metrics.m7 == 'Internal'){
                                            recordClick(agstat_global.linkType, ['companyid='+s.m5,'m1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7,'m8='+s.m8],stats.url,false);
                                        }   else {
                                            recordClick(agstat_global.linkType, ['companyid='+s.m5,'m1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7,'m8='+s.m8],stats.url,true);
                                        }
                                    } else {
                                        recordClick(agstat_global.linkType, ['companyid=' + s.m5,'m1=' + s.m1,'m2=' + s.m2,'m3=' + s.m3,'m4=' + s.m4,'m5=' + s.m5,'m6=' + s.m6,'m7=' + s.m7,'m8=' + s.m8]);
                                    }
                                    break;
            case 'NAV'          :   
									logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7, m8:s.m8, m9:s.m9, m10:s.m10 }]});
                                    recordClick(stats.linkType, ['m1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7,'m8='+s.m8,'m9='+s.m9,'m10='+s.m10], stats.url, false);								
                                    break;
									
            case 'HYPER'        :  	logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:'External' }]});
                                    recordClick(stats.linkType, ['companyid='+s.m5, 'sectionid='+s.m6, 'm1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7=External'], stats.url, true);
                                    break;
            case 'FROMNAVBAR'   :   logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7, m8:s.m8, m9:s.m9, m10:s.m10 }]});
                                    recordClick(stats.linkType, ['from=Become_a_partner', 'm1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7,'m8='+s.m8,'m9='+s.m9,'m10='+s.m10]);
                                    break;
            case 'NAVBAR'       :   logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7, m8:s.m8, m9:s.m9, m10:s.m10 }]});
                                    recordClick(stats.linkType, ['from=Our_Partners', 'm1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7,'m8='+s.m8,'m9='+s.m9,'m10='+s.m10]);
                                    break;
            case 'APPLY_JOB'    :   logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:'Internal', m8:s.m8 }]});
                                    recordClick(stats.linkType, ['m1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7=Internal','m8='+s.m8 ], '/account/applyForJob.html?jobId='+s.m8 );
                                    break;
            case 'FROMCOMPANYJOBINDEX' :
    								logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7, m8:s.m8 }]});
	                                recordClick(stats.linkType, ['jobid='+s.m8, 'userid=', 'm1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7,'m8='+s.m8 ], url, false );
                                    break;

            case 'ENQUIRY_FORM' :   logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7 }]});
	                                recordClick(stats.linkType, ['m1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7]);
                                    break;
								
            case 'SOCIAL_MEDIA' :   logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:'Social_Media' }]});
	                                recordClick(stats.linkType, ['m1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7=Social_Media']);
                                    break;

            case 'VIDEOLIBRARY' :	logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7 }]});
                                    recordClick(stats.linkType, ['companyid='+s.m5, 'sectionid='+s.m6, 'm1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7], stats.url, false);
                                    break;
            case 'VIDEOSEARCH' :	logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7 }]});
                                    recordClick(stats.linkType, ['companyid='+s.m5, 'sectionid='+s.m6, 'm1='+s.m1,'m2='+s.m2,'m3='+s.m3,'m4='+s.m4,'m5='+s.m5,'m6='+s.m6,'m7='+s.m7], stats.url, false);
                                    break;
            default             :   logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:s.m1, m2:s.m2, m3:s.m3, m4:s.m4, m5:s.m5, m6:s.m6, m7:s.m7, m8:s.m8 }]});
                                    recordClick(s.m4, ['m1=' + s.m1,'m2=' + s.m2,'m3=' + s.m3,'m4=' + s.m4,'m5=' + s.m5,'m6=' + s.m6,'m7=' + s.m7,'m8=' + s.m8]);
    }
}

    var _overrideGlobalStat = function(name, s) {
        if (typeof(s[name]) !== 'undefined') {
            return s[name];
        } else {
            return agstat_global[name];
        }
    }

    /*
        convert a stat list to a url string of the parameters, includes the global overrides if present.
    */
    var toParams = function(stats) {
        stats = mergeWithGlobals(stats);
        var statParams = "";
        for (param in stats) {
            if (stats.hasOwnProperty(param) && (typeof stats[param] !== 'undefined') ) {
                statParams = statParams + '&' + param + '=' + encodeURIComponent(stats[param]);
            }
        }
        return statParams;
    }

    // exported methods
    return {
        rc: rc,
        toParams: toParams
    }
})();

function clickMapLink(m4, m5, m6, website) {   
	logOCSale({isconv:'1',saleitems:[{itemcount:1, itemvalue:0.00, m1:'Directory', m2:'company', m3:'Company_Map_Page', m4:m4, m5:m5, m6:m6, m7:'External'}]});   
	
	recordClick('HYPER', 
		['companyid='+m5, 'sectionid='+m6, 'm1=Directory', 'm2=company', 'm3=Company_Map_Page', 'm4='+m4, 'm5='+m5, 'm6='+m6,'m7=External'],
		'http://'+ website +'?utm_campaign=applegate.co.uk&amp;utm_medium=referral&amp;utm_source=applegate.co.uk', 
		true 
	);

}



/*
    Hotlink stats.
*/
// namespacing: http://blog.stannard.net.au/2011/01/14/creating-namespaces-in-javascript/
var hlstat = (function() {

    /*
        Pages plus hotlink click - opens company wensite in new window.

        m2 = page type ()
        m3 = page ()
        m5 = company id
        m6 = section id 
        m8 = ()
        haswebsite = 0 or 1, does the company have a website
    */
    var pp = function(m2, m3, m5, m6, m8, haswebsite)
    {
        _cH('PagesPlus', m2, m3, m5, m6, 'INT_EXT', m8);
        _open(m5,haswebsite);
    };

    /*
        Directory hotlink click - opens company wensite in new window.

        m2 = page type ()
        m3 = page ()
        m5 = company id
        m6 = section id 
        m8 = ()
        haswebsite = 0 or 1, does the company have a website
    */
    var dir = function(m2, m3, m5, m6, m8, haswebsite)
    {
        _cH('Directory', m2, m3, m5, m6, 'INT_EXT', m8);
        _open(m5,haswebsite);
    };

    /*
     *   Stock online hotlink click - opens company wensite in new window.
     *
     *   m2 = page type (index, stock item)
     *   m3 = page (root, stock item, search)
     *   m5 = company id
     *   m6 = section id 
     *   m8 = (Item ID, Orderlineitemsid, PartCode)
     *   haswebsite = 0 or 1, does the company have a website
    */
    var sol = function(m2, m3, m5, m6, m8, haswebsite)
    {
        _cH('Stock', m2, m3, m5, m6, 'INT_EXT', m8);
        _open(m5,haswebsite);
    };

    /*
    *    Company page hotlink click - opens company website in new window.
    *    Accepts as few parameters as possible so that we can keep the size of the company pages as small as possible.
    *
    *    m2 = page type (index, stock item)
    *    m3 = page (root, stock item, search)
    *    m5 = company id
    *    m6 = section id 
    *    m8 = (Item ID, Orderlineitemsid, PartCode)
    *    haswebsite = 0 or 1, does the company have a website
    */
    var co = function(m5, m6, m8, haswebsite)
    {
        _cH( 'Directory','company','Company_Page', m5, m6, 'INT_EXT', m8);
        _open(m5,haswebsite);
    }

    /*
     *   Call the click hotlink code.
    */
    var _cH = function(m1, m2, m3, m5, m6, m7, m8)
    {
    	logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:m1, m2:m2, m3:m3, m4:'HOTLINK', m5:m5, m6:m6, m7:m7, m8:m8 }]});
    	recordClick('HOTLINK', ['m1='+m1,'m2='+m2,'m3='+m3,'m4=HOTLINK','m5='+m5,'m6='+m6,'m7=' + m7,'m8='+m8]);
    };
    
    /*
     *   Open the website in a new window centered on the screen.
     *   haswebsite = 0 or 1, does the company have a website
    */
    var _open = function(companyid,haswebsite)
    {
        if (haswebsite){
            var sw = screen.width;
            var sh = screen.height;
            var width = sw - Math.round(sw * .2);
            var height = sh - Math.round(sh * .2);
            var left   = Math.round((sw  - width)/2);
            var top    = Math.round((sh - height)/2);

		    if (jQuery) {
			    var first = true;
				$.ajax({
					type: 'GET',
					url: '/advertising/',
                    cache: false,
					async: false,
					complete: function(obj,text){
					   if (first){
							if(obj.status!=404){
							   window.open('/advertising/hotlinkRedirect.html?companyId='+companyid, 'company' + new Date().getTime(), 'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left+', scrollbars=1');
        }
						}
						first = false;
					}

				});
			}


        }
    };

    // exported methods
    return {
        dir: dir,
        sol: sol,
        co: co,
        pp: pp
    };
})();


/*
    Flash banner stats.
        used only for company external link
*/
function fbstats(m1, m2, m3, m5, m6, m7, m8, oliId) {

    logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:m1, m2:m2, m3:m3, m4:'BANNER', m5:m5, m6:m6, m7:m7, m8:m8 }]});
    recordClick('BANNER', ['m1='+m1,'m2='+m2,'m3='+m3,'m4=BANNER','m5='+m5,'m6='+m6,'m7=' + m7,'m8='+m8]);

    window.open('/advertising/flashBannerRedirect.html?oliId='+oliId, 'company' + new Date().getTime());

}

/*
    Universal banner stats.
        Used only for company external link.
*/
function ubstats(m1, m2, m3, m5, m6, m8, bannerId, bannerImageId, external, internalUrl) {

    if(external) {
        logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:m1, m2:m2, m3:m3, m4:'UNIVERSAL_BANNER', m5:m5, m6:m6, m7:'EXTERNAL', m8:m8 }]});
        recordClick('BANNER', ['m1='+m1,'m2='+m2,'m3='+m3,'m4=UNIVERSAL_BANNER','m5='+m5,'m6='+m6,'m7=EXTERNAL','m8='+m8]);
        var sw = screen.width;
        var sh = screen.height;
        var width = sw - Math.round(sw * .2);
        var height = sh - Math.round(sh * .2);
        var left   = Math.round((sw  - width)/2);
        var top    = Math.round((sh - height)/2);
        window.open('/advertising/universalBannerRedirect.html?bannerId='+bannerId+'&bannerImageId='+bannerImageId, 'company' + new Date().getTime(), 'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left+', scrollbars=1');
        return true;
    }

    logOCSale({isconv:'1', saleitems:[{itemcount:1, itemvalue:0.00, m1:m1, m2:m2, m3:m3, m4:'UNIVERSAL_BANNER', m5:m5, m6:m6, m7:'INTERNAL', m8:m8 }]});
    recordClick('BANNER', ['m1='+m1,'m2='+m2,'m3='+m3,'m4=UNIVERSAL_BANNER','m5='+m5,'m6='+m6,'m7=INTERNAL','m8='+m8]);
    location.href = internalUrl;
}

