$(document).ready(function(){

	// check if template requires liveperson code
	var livepersonEnabled = (1 == $(':hidden#liveperson_enabled').val());
	
	// if the affiliate cookie is set, disable liveperson
	if ($.cookie('AFFILIATE_ID')) {
		lpAddVars('session', 'AffiliateName', $.cookie('AFFILIATE_ID'));
	}

	// check to see if a user is logged in to the portal
	var portalLoggedIn = $(':hidden#liveperson_portalloggedin').val();

	// if a user is logged in to the portal, disable liveperson
	if (portalLoggedIn == 1) {
		livepersonEnabled = false;
	}

	// load liveperson code
	if (livepersonEnabled) {

		// define room identifier - this is already set in mtagconfig.js but can be overridden
		if (typeof(lpUnit)=='undefined') {
			 lpUnit = 'plusnet-broadband';
		}

		// run liveperson
		lpAddMonitorTag();

		// pick up any section and page variables
		var livepersonSection = $(':hidden#liveperson_section').val();
		var livepersonPage = $(':hidden#liveperson_page').val();

		// get all hidden field vars and send them to live person
		$(':hidden.liveperson_var').each(

			function() {

				var livepersonVarName = $(this).attr('id');
				var livepersonVarVal = $(this).val();
				var scope = 'page';

				if ($(this).hasClass('session')) {
					scope = 'session';
				}
				else if ($(this).hasClass('visitor')) {
					scope = 'visitor';
				}

				lpAddVars(scope, livepersonVarName, livepersonVarVal);

				// these final variables need sending again with a prefixed name
				if (livepersonVarName == 'Identifier' || 
				    livepersonVarName == 'ConversionDetails' || 
					livepersonVarName == 'OrderTotal') {
					lpAddVars('session', lpUnit + '_' + livepersonVarName, livepersonVarVal);
				}

			}

		)

		// add behaviour to thickbox links
		if (livepersonSection == 'sales' && livepersonPage == 'home') {

			$('a.more_info.value').click(
				function () {
					lpAddVars('session', 'HasVisitedValueBroadbandInfo', 'Yes');
				}
			);

			$('a.more_info.unlimited').click(
				function () {
					lpAddVars('session', 'HasVisitedUnlimitedBroadbandInfo', 'Yes');
				}
			);

		}

		// add hover state to chat button
		$('#buttonDIV').hover(

			function(event) {
				setChatButtonHoverState(event);
			},
			function(event) {
				setChatButtonHoverState(event);
			}

		);

	}

});

// add hover state to chat button
function setChatButtonHoverState(event) {

	var target = $(event.target);

	if (target.is('img')) {

		var buttonSrc = target.attr('src');
		var buttonSrcArray = buttonSrc.split('/');
		var buttonFileName = buttonSrcArray[(buttonSrcArray.length - 1)];

		if ('reponline.gif' == buttonFileName) {
			target.attr('src', '/liveperson/images/button1/reponline_hover.gif');
		}
		else if ('reponline_hover.gif' == buttonFileName) {
			target.attr('src', '/liveperson/images/button1/reponline.gif');
		}

	}

}
