var mainDisplayBanners = true;

if($("#mswlsite").length)
{
	mainDisplayBanners = false;
}

if(mainDisplayBanners)
{
	// VCL Cross Site Banners.
	function getSiteRefererCookie(check_name)
	{
		// first we'll split this cookie up into name/value pairs
		// note: document.cookie only returns name=value, not the other components
		var a_all_cookies = document.cookie.split( ';' );
		var a_temp_cookie = '';
		var cookie_name = '';
		var cookie_value = '';
		var b_cookie_found = false; // set boolean t/f default f
	
		for ( i = 0; i < a_all_cookies.length; i++ )
		{
			// now we'll split apart each name=value pair
			a_temp_cookie = a_all_cookies[i].split( '=' );
	
	
			// and trim left/right whitespace while we're at it
			cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
			// if the extracted name matches passed check_name
			if ( cookie_name == check_name )
			{
				b_cookie_found = true;
				// we need to handle case where cookie has no value but exists (no = sign, that is):
				if ( a_temp_cookie.length > 1 )
				{
					cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
				}
				// note that in cases where cookie is initialized but no value, null is returned
				return cookie_value;
				break;
			}
			a_temp_cookie = null;
			cookie_name = '';
		}
		if ( !b_cookie_found )
		{
			return false;
		}
	}
	
	function getElementsByClassName(classname, node)
	{
		if(!node) node = document.getElementsByTagName("body")[0];
		var a = [];
		var re = new RegExp('\\b' + classname + '\\b');
		var els = node.getElementsByTagName("*");
		for(var i=0,j=els.length; i<j; i++)
		if(re.test(els[i].className))a.push(els[i]);
		return a;
	}
	
	// The ID of the contaier for the banners.
	var bannersContainer = "vcl-site-banners";
	
	// This is incase there are multiple banner locations.
	var multipleBannerLocations = false;
	
	// Any element with the class stored in bannersContainer will be stored here.
	var bannerLocations = getElementsByClassName(bannersContainer);
	
	if(bannerLocations.length > 0)
	{
		multipleBannerLocations = true;
	}
	
	// Make sure that there is a container in the HTML for the banners.
	if(document.getElementById(bannersContainer) || multipleBannerLocations == true)
	{
		if(multipleBannerLocations == true)
		{
			for(var i = 0; i < bannerLocations.length; i++)
			{
				var thisLocationId = bannerLocations[i].id;
				document.getElementById(thisLocationId).style.overflow = "hidden";
			}
		}
		else
		{
			document.getElementById(bannersContainer).style.overflow = "hidden";
		}
		
		// This is where we will store the site reference or 'type'.
		var currentDomain = "";
		
		// Is this an affinity site?
		var affinityFlag = false;
		
		// Which element holds the affinity info?
		var affinityKey = -1;
		
		// As we will be hosting on affinities we need to add them to this array for discovery.
		var affinitySites = new Array();
		
		// Each affinity is stored with the domain for matching and the reference for tracking.
		affinitySites[0] = new Array()
		affinitySites[0]["domain"] = "idealworld.mobileshop.com";
		affinitySites[0]["ref"]    = "ideal";
		
		affinitySites[1] = new Array()
		affinitySites[1]["domain"] = "ideal.mobileshop.com";
		affinitySites[1]["ref"]    = "idealdev";
		
		// Then establish which array we do not want to include.
		var currentDomainFull = document.domain;
		
		for(var i = 0; i < affinitySites.length; i++)
		{
			if(affinitySites[i]["domain"] == currentDomainFull)
			{
				currentDomain = "mobileshop";
				affinityFlag  = true;
				affinityKey   = i;
				break;
			}
		}
		
		// Set the location of all the banners.
		var bannerHost = "http://www.mobileshop.com/images/banners/cross-site/";
		
		if(currentDomain == "")
		{
			currentDomain = currentDomainFull.split(".")
		
			// Uncomment this to use banner images from dev.
			// bannerHost = bannerHost.replace("www", "dev");
		
			currentDomain = currentDomain[1];
		}
		
		// This contains all the cookie names for referer info for all the different sites.
		var refererCookies = new Array();
		refererCookies["mobileshop"] = "referer";
		refererCookies["shoplaptop"] = "clickref";
		refererCookies["laptopshop"] = "pclickaffiliate";
		
		// Still awaiting this.
		//refererCookies["comparebroadbanduk"] = "";
		
		// Sites and what GA call must be used.
		var googleTrackingCalls = new Array();
		googleTrackingCalls["mobileshop"] = "urchinTracker";
		googleTrackingCalls["shoplaptop"] = "pageTrackerSL._trackPageview";
		googleTrackingCalls["laptopshop"] = "urchinTracker";
		googleTrackingCalls["laptopshop"] = "urchinTracker";
		
		// Fetch the value of the referer cookie.
		var userReferer = getSiteRefererCookie(refererCookies[currentDomain]);
		
		// Set up arrays that contains all the banners for looping.
		var vclBanners = new Array();
		
		var siteTrackingReference = currentDomain;
		
		if(affinityFlag == true)
		{
			siteTrackingReference = currentDomain + "-" + affinitySites[affinityKey]["ref"];
		}
	
		
		// Mobileshop banners.
		vclBanners[0] = new Array();
		vclBanners[0]["src"]  = "mobileshop-1.gif";
		vclBanners[0]["href"] = "http://www.mobileshop.com/tracker.php/tag/" + siteTrackingReference + "-vcl-banners-" + userReferer + "/page/http://www.mobileshop.com/";
		vclBanners[0]["alt"]  = "Mobile Phone Deals";
		vclBanners[0]["id"]   = "ms-1";
		
		vclBanners[1] = new Array();
		vclBanners[1]["src"]  = "mobileshop-2.gif";
		vclBanners[1]["href"] = "http://www.mobileshop.com/tracker.php/tag/" + siteTrackingReference + "-vcl-banners-" + userReferer + "/page/http://www.mobileshop.com/";
		vclBanners[1]["alt"]  = "Mobile Phone Deals";
		vclBanners[1]["id"]   = "ms-2";
		
		// Shoplaptop banners.
		vclBanners[2] = new Array();
		vclBanners[2]["src"]  = "shoplaptop-1.gif";
		vclBanners[2]["href"] = "http://www.shoplaptop.co.uk/tracker.php?p=http://www.shoplaptop.co.uk/&idaffiliates=1004&clickref=" + siteTrackingReference + "-vcl-banners-" + userReferer;
		vclBanners[2]["alt"]  = "Shoplaptop - Compare the whole UK laptop market in one place";
		vclBanners[2]["id"]   = "sl-1";
		
		vclBanners[3] = new Array();
		vclBanners[3]["src"]  = "shoplaptop-2.gif";
		vclBanners[3]["href"] = "http://www.shoplaptop.co.uk/tracker.php?p=http://www.shoplaptop.co.uk/&idaffiliates=1004&clickref=" + siteTrackingReference + "-vcl-banners-" + userReferer;
		vclBanners[3]["alt"]  = "Shoplaptop - Compare the whole UK laptop market in one place";
		vclBanners[3]["id"]   = "sl-2";
		
		// Laptopshop banners.
		vclBanners[4] = new Array();
		vclBanners[4]["src"]  = "laptopshop-1.gif";
		vclBanners[4]["href"] = "http://www.laptopshop.co.uk/pclick/url/?aff=" + siteTrackingReference + "-" + userReferer + "&cam=vcl-banners&url=/";
		vclBanners[4]["alt"]  = "Laptopshop - Price Guarantee on all new laptops. We won&rsquo;t be beaten on price!";
		vclBanners[4]["id"]   = "ls-1";
		
		vclBanners[5] = new Array();
		vclBanners[5]["src"]  = "laptopshop-2.gif";
		vclBanners[5]["href"] = "http://www.laptopshop.co.uk/pclick/url/?aff=" + siteTrackingReference + "-" + userReferer + "&cam=vcl-banners&url=/";
		vclBanners[5]["alt"]  = "Laptopshop - Price Guarantee on all new laptops. We won&rsquo;t be beaten on price!";
		vclBanners[5]["id"]   = "ls-2";
		
		/* NOT TO BE SHOWN UNTIL A REFERER CAN BE TRACED */
		// Compare broadband banners.
		//vclBanners[6] = new Array();
		//vclBanners[6]["src"]  = "comparebroadbanduk-1.gif";
		//vclBanners[6]["href"] = "http://www.comparebroadbanduk.com/?campaign=" + siteTrackingReference + "-vcl-banners-" + userReferer;
		//vclBanners[6]["alt"]  = "Compare Broadband Deals";
		//vclBanners[6]["id"]   = "cbuk-1";
		
		//vclBanners[7] = new Array();
		//vclBanners[7]["src"]  = "comparebroadbanduk-2.gif";
		//vclBanners[7]["href"] = "http://www.comparebroadbanduk.com/?campaign=" + siteTrackingReference + "-vcl-banners-" + userReferer;
		//vclBanners[7]["alt"]  = "Compare Broadband Deals";
		//vclBanners[7]["id"]   = "cbuk-2";
		/* NOT TO BE SHOWN UNTIL A REFERER CAN BE TRACED */
		
		// Any exclusions for any of the sites are stored here.
		var bannerExclusions = new Array();
		
		// An array for any type stores all the exclusions for that site.
		bannerExclusions["laptopshop"] = new Array();
		
		// Exclude Shoplaptop banners from Laptopshop.
		bannerExclusions["laptopshop"][0] = "shoplaptop";
		
		// Create the temp array that will hold site names of valid banner types.
		var validBannerTypes = new Array();
		
		// Current index of banner types.
		var currentType = 0;
		
		// Keep a track of the banner number.
		var currentTypeSet = 1;
		
		// How many banner sets per type?
		var totalTypeSets = 2;
		
		// Banners are not excluded by default.
		var bannerExcluded = false;
		
		/********** Create the array that will hold all the banners that are to loop on this domain **********/
		for(var i = 0; i < vclBanners.length; i++)
		{
			// Make a regular expression to match the current domain in the image names.
			var matchDomain = new RegExp(currentDomain);
			
			// Is this banner to be excluded?
			bannerExcluded = false;
			
			// Check for an exclusion record.
			if(bannerExclusions[currentDomain])
			{
				// If there is an exclusion record for this domain then check for this banner.
				for(var c = 0; c < bannerExclusions[currentDomain].length; c++)
				{
					if(vclBanners[i]["src"].match(bannerExclusions[currentDomain][c]))
					{
						bannerExcluded = true;
					}
				}
			}
			
			// Exclude any images that are banners for the current domain.
			if(!vclBanners[i]["src"].match(matchDomain) && bannerExcluded == false)
			{
				// Create the name of the banner type.
				var bannerType = vclBanners[i]["src"].split("-");
				bannerType = bannerType[0];
					
				// How many banner types have been approved already.
				var totalValidBanners = validBannerTypes.length;
				
				// If this is the first banner type to be valid then just add it in.
				if(totalValidBanners == 0)
				{
					validBannerTypes[0] = bannerType;
				}
				else
				{
					// Is this type already stored?
					var alreadySet = false;
					
					// Loop around validBannerTypes and check that the current sitename is not already in the array, we do not want duplicates.
					for(var c = 0; c < totalValidBanners; c++)
					{
						if(validBannerTypes[c] == bannerType)
						{
							alreadySet = true;
						}
					}
					
					// If this type is not already stored that add it in.
					if(alreadySet == false)
					{
						validBannerTypes[totalValidBanners] = bannerType;
					}
				}
			}
		}
		
		// A final total of valid banners.
		var totalValidBanners = validBannerTypes.length;
		/********** Create the array that will hold all the banners that are to loop on this domain end **********/
		
		/********** Functions to change the banner **********/
		var bannerContainerHidden = true;
		
		function changeBanner()
		{
			var toSetSrc      = "";
			var toSetHref     = "";
			var toSetAlt      = "";
			var toSetId       = "";
			var toSetIdSecond = "";
			
			var allVclBanners = getElementsByClassName("vcl-site-banner-elements");
			
			for(var i = 0; i < allVclBanners.length; i++)
			{
				document.getElementById(allVclBanners[i].id).style.display = "none";
			}
			
			// Find the vclBanners element that hold the current banner info.
			for(var i = 0; i < vclBanners.length; i++)
			{
				// Use the set number and type name to match with the src of the banner.
				var matchSrcName = new RegExp(validBannerTypes[currentType] + "-" + currentTypeSet);
				
				if(vclBanners[i]["src"].match(matchSrcName))
				{
					toSetId = vclBanners[i]["id"];
					
					if(multipleBannerLocations == true)
					{
						toSetIdSecond = vclBanners[i]["id"] + "-duplicate";
					}
				}
			}
			
			document.getElementById(toSetId).style.display = "block";
			
			if(multipleBannerLocations == true)
			{
				document.getElementById(toSetIdSecond).style.display = "block";
			}
			
			if(bannerContainerHidden == true)
			{
				// Are there more than one banner location?
				if(multipleBannerLocations == true)
				{
					// Loop around unhiding the locations.
					for(var i = 0; i < bannerLocations.length; i++)
					{
						var thisLocationId = bannerLocations[i].id;
						document.getElementById(thisLocationId).style.display = "block";
					}
				}
				else
				{
					// Show the banner container.
					document.getElementById(bannersContainer).style.display = "block";
				}
				
				bannerContainerHidden = false;
			}
		}
		
		function triggerChange()
		{
			if(currentType == (totalValidBanners - 1))
			{
				// Start from the first banner.
				currentType = 0;
				
				// Change type set.
				if(currentTypeSet == totalTypeSets)
				{
					currentTypeSet = 1;
				}
				else
				{
					currentTypeSet++;
				}
			}
			else
			{
				// Go to the next type.
				currentType++;
			}
			
			// Change the banner.
			changeBanner();
		}
		/********** Functions to change the banner end **********/
		
		/********** Start the banner rotation **********/
		if(totalValidBanners > 0)
		{
			// Build the main banner html.
			var bannerMainHtml  = "";
			var bannerReference = "";
			
			// Find the vclBanners element that hold the current banner info.
			for(var i = 0; i < vclBanners.length; i++)
			{	
				if(!vclBanners[i]["src"].match(matchDomain))
				{
					toSetSrc  = vclBanners[i]["src"];
					toSetHref = vclBanners[i]["href"];
					toSetAlt  = vclBanners[i]["alt"];
					toSetId   = vclBanners[i]["id"];
					
					bannerMainHtml += '<a onclick="javascript:' + googleTrackingCalls[currentDomain] + '(\'/vcl-site-banners/' + toSetId + '\');" class="vcl-site-banner-elements" id="' + toSetId + '" href="' + toSetHref + '" title="' + toSetAlt + '"><img src="' + bannerHost + toSetSrc + '" alt="' + toSetAlt + '" /></a>';
				}
			}
			
			// Do we loop around multiple locations or just work with one.
			if(multipleBannerLocations == true)
			{
				var bannerMainHtmlDuplicate = "";
				
				// Find the vclBanners element that hold the current banner info.
				for(var i = 0; i < vclBanners.length; i++)
				{	
					if(!vclBanners[i]["src"].match(matchDomain))
					{
						toSetSrc  = vclBanners[i]["src"];
						toSetHref = vclBanners[i]["href"];
						toSetAlt  = vclBanners[i]["alt"];
						toSetId   = vclBanners[i]["id"];
					
						bannerMainHtmlDuplicate += '<a onclick="javascript:' + googleTrackingCalls[currentDomain] + '(\'/vcl-site-banners/' + toSetId + '\');" class="vcl-site-banner-elements" id="' + toSetId + '-duplicate" href="' + toSetHref + '" title="' + toSetAlt + '"><img src="' + bannerHost + toSetSrc + '" alt="' + toSetAlt + '" /></a>';
					}
				}
				
				// Loop around the multiple locations getting the ID for the elements and inserting the new banner.
				for(var i = 0; i < bannerLocations.length; i++)
				{
					if(i == 0)
					{
						var thisLocationId = bannerLocations[i].id;
						document.getElementById(thisLocationId).innerHTML = bannerMainHtml;
					}
					
					if(i == 1)
					{
						var thisLocationId = bannerLocations[i].id;
						document.getElementById(thisLocationId).innerHTML = bannerMainHtmlDuplicate;
					}
				}
			}
			else
			{
				// There is just one location so just insert the new banner.
				document.getElementById(bannersContainer).innerHTML = bannerMainHtml;
			}
			
			// Call the changeBanner function to show the initial banner.
			changeBanner();
		
			// Start the interval that will loop the banners.
			var bannerInterval = setInterval("triggerChange()", 6000);
		}
		/********** Start the banner rotation end **********/
	}
}
