if(typeof(Array.map) != 'function') {
	Array.prototype.map = function(fn) {
		var r = [];
		var l = this.length;
		for(i=0;i<l;i++)
		{
			r.push(fn(this[i]));
		}
		return r; 
	};
}

// global vars
var flashMovie;
var runCount = 0;
var maxRunCount = 100;
var t;
var artistImageLoaded = false;
var playerLoaded = false;
var initialTagCloudXML = '';

//artist pages create their own headers. This will be switched to true on those pages.
var override_header = false;
   
//initialization methods   
function init(xmlurl) {
	initialTagCloudXML = xmlurl;
	loadTagCloud();
}

//this is called by the tag cloud flash file when fully loaded
function onTagcloudInit() {
	updateXML(initialTagCloudXML);
}
  
function loadTagCloud() {
	//	Edit - Moving to flash based tag cloud
	// Load the flash file initially
	flashMovie = document.getElementById('warnerTagCloudDOM');
	if (flashMovie) {
		 
		 //this is the loading code for swfobject 2.x
		 //It breaks the brightcove player, so falling back to 1.5
		// var flashvars = {
		// };
		// var params = {
		  // allowscriptaccess: "always",
		  // wmode: "transparent",
		  // bgcolor: "#000000"
		// };
		// var attributes = {
		// };
		// var swf = swfobject.embedSWF("/sites/all/themes/warner/tagcloud.swf", "warnerTagCloudDOM", "310", "270", "9.0.0", "", flashvars, params, attributes);
		
		//direct writing out code to the DOM
		//var obj = $(document.createElement('object')).attr('class', 'tagcloud').attr('codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0').attr('id', 'TagCloud').attr('height', '270').attr('width', '310').attr('classid', 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000');  
		//var param1 = document.createElement('param').attr('allowscriptaccess', 'always');
		//var param2 = document.createElement('param').attr('wmode', 'transparent');
		//param1.appendTo(obj);
		//param2.appendTo(obj);
		//obj.appendTo('warnerTagCloudDOM');
		//alert($('#warnerTagCloudDOM').html());
		
		//Swfobject 1.5 embed code
		var so = new SWFObject("/sites/all/themes/warner/tagcloud.swf", "TagCloud", "310", "270", "9", "#000000");
		so.addParam("allowscriptaccess", "always");
		so.addParam("wmode", "transparent");
		so.write("warnerTagCloudDOM");

	}
}
  
  function updateXML(txt) {
	var newtxt = txt;
	
	//flashMovie = document.getElementById('warnerTagCloudDOM');
	//v1.5 of swf object puts it in a div
	flashMovie = document.getElementById('TagCloud');
	if (flashMovie) {
		if (!txt) {
			newtxt = "xml/tagcloudfeaturedartists.xml";
		}
			flashMovie.updateXML(txt);
			return;
	}
  }
 

$(document).ready(function(){
	var is_nz = false;
	var override = false;
	var defaultTagCloudXML = "xml/tagcloudfeaturedartists.xml";

	// we need to grab the URL to enable switching to 'NZ' mode. including refs to dev and staging sites	
	// and then run masthead randomiser JS on page load
	var siteurl = window.location.href;
	var neil_young_pos=siteurl.indexOf('neil-young');
    var eric_hutch_pos=siteurl.indexOf('eric-hutchinson');
	
	//$('#tabs div').hide(); // hide all divs
	
	if (neil_young_pos > -1) {  
		$('#tabs ul li.tab-4').addClass('active'); // set the class of the first tab-control to active
		override = true;
		defaultTagCloudXML = 'xml/tagcloudiconic.xml';
		//updateXML('xml/tagcloudiconic.xml');
	} else if (eric_hutch_pos > -1) {
        $('#tabs ul li.tab-2').addClass('active'); // set the class of the first tab-control to active
		override = true;
		defaultTagCloudXML = 'xml/tagcloudnewmusic.xml';
		//updateXML('xml/tagcloudnewmusic.xml');
    } else {
        $('#tabs ul li.tab-1').addClass('active'); // set the class of the first tab-control to active
		
    }

	if (
		siteurl.match(/nz.wma.hothouse.com.au/) ||
		siteurl.match(/nz.wma.hhi.net.au/) ||
		siteurl.match(/warnermusic.co.nz/)
	) {
		is_nz = true;
		// Initialize the NZ tag cloud
		if (!override) {
			defaultTagCloudXML = "xml/nz/tagcloudnewzealand.xml";
			//init("xml/nz/tagcloudnewzealand.xml");
		}
		// Set up random NZ masthead
	    masthead_randomiser_nz(null,1);
	} else {
		// Initialize the AU tag cloud
		if (!override) {
			defaultTagCloudXML = "xml/tagcloudfeaturedartists.xml";
			//init("xml/tagcloudfeaturedartists.xml");
		}
		// Set up random AU masthead
	    masthead_randomiser(null,1);
	}
	
	init(defaultTagCloudXML);
	$('#tabs div').show();


    //run masthead randomiser for artist-thumb clicks
    $('ul#artist-thumb li img').click(function(){ // when artist-thumb img is clicked on
        var artistLinkRef = $(this).parent().attr('href').replace(/.*?#/,""); // get href and strip everything up to and including # character
		
		//simon b edited
		//if (siteurl == 'http://nz.wma.hothouse.com.au' || siteurl == 'http://nz.wma.hhi.net.au/' || siteurl == 'http://www.warnermusic.co.nz/') {
		if (is_nz) {
    	    masthead_randomiser_nz(artistLinkRef,0); // send artist name to masthead randomiser for switch
    	} else {
    	    masthead_randomiser(artistLinkRef,0); // send artist name to masthead randomiser for switch
    	}
        return false;
    });


	$('#tabs ul#tab-control li a').click(function(){ // when any tab-control is clicked
		$('#tabs ul#tab-control li').removeClass('active'); // remove active class from all links
		$(this).parent('li').addClass('active'); // set clicked tab-control class to active
		
		var currentXML = $(this).attr('rel'); // set variable currentXML to value of href attribute of clicked link
		updateXML(currentXML);
		return false;
	});

    // IE Hover Fix on tag cloud tabber
    $('#tab-control li').hover(function() {
        $(this).addClass('tab-control-li-hover');
        $("a", this).addClass('tab-control-a-hover');
    },function(){
        $(this).removeClass('tab-control-li-hover');
        $("a", this).removeClass('tab-control-a-hover');
    });
	
	$("div.promo ul#buy-music li").each(function(c,b) {
		$(c).find('a.btn-buy-album').hover(
		  function () {
			$(c).find('#buy-album').show();
		  }, 
		  function () {
			$(c).find('#buy-album').hide();
		  }
		);
		$(c).find('#buy-album').hover(
		  function () {
			$(c).find('#buy-album').show();
		  }, 
		  function () {
			$(c).find('#buy-album').hide();
		  }
		);
	});	
	
});


// Masthead Artist Randomisers (initially the same for AU & NZ but this will change)
// randomises artist specific masthead elements on page reload
function masthead_randomiser(artistLinkRef, pageLoad) {
	if (override_header == true) {
		return;
	}

    // set array of artists
	var artist = ['rob-thomas', 'lisa-mitchell', 'muse', 'michael-buble', 'paramore']; // set array of artists
    var artistTarget = artist.map(function(e) {
		return e;
	});
	var artistHref = artist.map(function(e) {
		switch(e) {
			case 'lisa-mitchell':
				return 'http://www.lisamitchell.com.au/';
			case 'muse':
				return 'http://muse.mu/';
			case 'michael-buble':
				return 'http://www.warnermusic.com.au/michael-buble';
			default:
				return 'http://www.warnermusic.com.au/' + e;
		}
	});
	// set array of album images that correspond to artists
	var artistAlbumImg = artist.map(function(e) {
		return 'album-img-' + e + '.jpg';
	});
	// background image of the main header
	var artistBgImage = artist.map(function(e) {
		return 'hdr-bg-' + e + '.jpg';
	});
	//the main background image running across the whole page
	var artistHeaderBgImage = artist.map(function(e) {
		return 'masthead-bg-' + e + '.jpg';
	});
	//the thumbnail images
	var artistThumbImage = artist.map(function(e) {
		return 'thumb-' + e + '.jpg';
	});
	// set array of videos that correspond to artists - note this is the OLD video player from brightcove
	var artistVideoURL = artist.map(function(e) {
		return '';
	});

	//there are currently 2 versions of the brightcove player,
	//use this array if the artist is using the new version of the player and mark the array value above as empty to use the new player
	//the value stored is the @videoPlayer flash parameter
	var artistV2VideoPlayer = [
		'44502130001',
		'58612717001',
		'40801482001',
		'46102276001',
		'52495926001'
	];

    // set array of artists jb hifi
	var artistJBHifi = [
		'http://www.jbhifionline.com.au/Product/429251',
		'http://www.jbhifionline.com.au/support.aspx?post=1&results=10&order=1&q=lisa+mitchell&searchtype=all&bnSearch=Go!',
		'http://www.jbhifionline.com.au/MUSE.HTM',
		'http://www.jbhifionline.com.au/music/pop-rock/crazy-love-cd-dvd/461112',
		'http://www.jbhifionline.com.au/music/pop-rock/brand-new-eyes-bonus-bag/449672'
	];

    // set array of artists bigpond
	var artistBigpond = [
		'http://bigpondmusic.com/Artist/Rob-Thomas.aspx',
		'http://bigpondmusic.com/Artist/Lisa-Mitchell.aspx',
		'http://bigpondmusic.com/Artist/Muse.aspx',
		'http://bigpondmusic.com/album/michael-buble/crazy-love2',
		'http://bigpondmusic.com/Artist/Paramore.aspx'
	]; 

    // set array of artists itunes
	var artistITunes = [
		'http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewArtist?id=217178',
		'http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewAlbum?id=311525096&s=143460',
		'http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewPreorder?id=326691732&s=143460',
		'http://itunes.apple.com/au/album/crazy-love/id332365917',
		'http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewPreorder?id=322980798&s=143460'
	];

    // generate random number
	var randNum = Math.floor(Math.random() * artist.length);

    if(pageLoad){
        var x;
        //loop through all artist names
		for(x in artist) {
            // if current artist name in list appears in page url
			if (window.location.href.split(artist[x]).length > 1) {
                // ovverrid the random number to number for that artist
				randNum = x;
            }
        }
    }

    // if masthead randomiser is being called from an artist-thumb link
	if(artistLinkRef) {
        x=0; 
        // loop through all the artist names
		for(x in artist) {
            // if artist name equals an artist name in our artists list
			if (artist[x] == artistLinkRef) {
				// override random number to number for that artist
				randNum = x;
            }
        }
    }
	
	//load the other artists
	if (!artistImageLoaded) {
		var ul = $(document.createElement('ul'));
		ul.attr('id', 'artist-thumb');
		for (x in artist) {
			//ie does some weird thing where it adds the map function to the artist array in IE. ignore it.
			if (x == 'map') {
				continue;
			}
			
			var li = $(document.createElement('li')).addClass('thumb-' + artist[x]);
			var a = $(document.createElement('a'));
			a.attr('href', '#' + artist[x]);
			var img = $(document.createElement('img')).attr('src', '/sites/all/themes/warner/images/' + artistThumbImage[x]);
			img.attr('width', '69');
			img.attr('height', '52');
			img.attr('alt', artist[x]);
			
			$(a).append(img);
			$(li).append(a);
			$(ul).append(li);
		}
		
		$('#other_artists').append(ul);
		
		artistImageLoaded = true;
	}
	
	var bgimage = 'url(/sites/all/themes/warner/images/' + artistBgImage[randNum] + ')';
	var headerbgimage = 'url(/sites/all/themes/warner/images/' + artistHeaderBgImage[randNum] + ')';
	
	$('div#masthead-area-c').css({'background-image': bgimage, 'background-repeat':'no-repeat'});
	$('div#masthead').css({'background-image': headerbgimage, 'background-repeat':'repeat-x'});
    $('div#masthead').removeClass().addClass(artist[randNum]); //replace #masthead div class with current artist class
    if (artistAlbumImg[randNum].length > 0) {
		$('img.masthead-album-img').show();
		$('img.masthead-album-img').attr("src","/sites/all/themes/warner/images/"+artistAlbumImg[randNum]); //change album image src to random artist album image
    }
	else
	{
		$('img.masthead-album-img').hide();
	}
	$('ul#artist-thumb li').css("display","inline"); // set all see other artists list entires to normal display
    $('li.thumb-'+artist[randNum]).css("display","none"); // hide current random artist from see other artists list
 
    $('div.promo a.btn-d').attr("href",artistHref[randNum]); // set visit artist site button to artist url
    $('div.promo a.btn-d').attr("target",artistTarget[randNum]); // set target window
    $('div.promo a.buy-jb ').attr("href",artistJBHifi[randNum]); // set buy jb hifi link
    $('div.promo a.buy-bigpond ').attr("href", artistBigpond[randNum]); // set buy bigpond link
    $('div.promo a.buy-itunes ').attr("href", artistITunes[randNum]); // set buy itunes link
    $('div.promo a.buy-jb ').attr("target","_buy-jb"); // set buy jb hifi link
    $('div.promo a.buy-bigpond ').attr("target", "_buy-bigpond"); // set buy bigpond link
    $('div.promo a.buy-itunes ').attr("target", "_buy-itunes"); // set buy itunes link
	
	//new logic for the new header video player
	var vid_holder = $('#videoholder');
	if (vid_holder.length > 0) {
		
		if (artistVideoURL[randNum].length > 0) { 
			//then its an original video player, add an iframe
			var iframe = $(document.createElement('iframe'));
			if (iframe) {
				iframe.addClass('masthead-video-player');
				iframe.attr('src', artistVideoURL[randNum]);
				iframe.attr('width', '321');
				iframe.attr('height', '253');
				iframe.attr('frameborder', '0');
				iframe.attr('scrolling', 'no');
				vid_holder.append(iframe);
			}
		} else {
			//its a new player. Add it to the page
			//first, make sure the placeholder is there

			if (!playerLoaded) {
				createBrightCoveVideo('videoholder', 'myExperience22002380001', '17939730001', artistV2VideoPlayer[randNum]);
				
				playerLoaded = true;
			} else {
				loadBrightCoveVideo('myExperience22002380001', artistV2VideoPlayer[randNum]);
			}
			
		}
	}

    $('div#masthead').show(); // show the masthead
}

function masthead_randomiser_nz(artistLinkRef,pageLoad){ //randomises artist specific masthead elements on page reload
	if (override_header == true) { return; }

    var artist = ['kirsten-morrell','dane-rumble','j-williams','nathan-haines','shihad']; // set array of artists
    var artistTarget = ['kirsten-morrell','dane-rumble','j-williams','nathan-haines','shihad']; // window targets
    var artistHref = ['/kirsten-morrell','/dane-rumble','/j-williams','/nathan-haines','/shihad']; // set array of artists
    var artistAlbumImg = ['kirsten-morrell.jpg','dane-rumble.jpg','j-williams.jpg','nathan-haines.jpg','shihad.jpg']; // set array of album images that correspond to artists
    var artistBgImage = ['hdr-bg-kirsten-morrell.jpg', 'hdr-bg-dane-rumble.jpg', 'hdr-bg-j-williams.jpg', 'hdr-bg-nathan-haines.jpg', 'hdr-bg-shihad.jpg']; // background image of the main header
    var artistHeaderBgImage = ['masthead-bg-kirsten-morrell.jpg', 'masthead-bg-dane-rumble.jpg', 'masthead-bg-j-williams.jpg', 'masthead-bg-nathan-haines.jpg', 'masthead-bg-shihad.jpg']; //the main
    var artistThumbImage = ['thumb-kirsten-morrell.jpg', 'thumb-dane-rumble.jpg', 'thumb-j-williams.jpg', 'thumb-nathan-haines.jpg', 'thumb-shihad.jpg']; //the thumbnail images

		var artistVideoURL = [
	    '',
	    '',
	    '',
	    '',
	    ''
	    ]; // set array of videos that correspond to artists - note this is the OLD video player from brightcove

		//there are currently 2 versions of the brightcove player,
		//use this array if the artist is using the new version of the player and mark the array value above as empty to use the new player
		//the value stored is the @videoPlayer flash parameter
		var artistV2VideoPlayer = [
			'81562764001',
			'81497676001',
			'71246872001',
			'85521727001',
			'78350106001'
		];


    //var artistJBHifi = [
	var artistDigirama = [
    'http://www.digirama.co.nz/searchsummary.aspx?AuthorID=338712&AffiliateID=14',
    'http://www.digirama.co.nz/AlbumDetails.aspx?MediaID=1087147&AffiliateID=14',
    'http://www.digirama.co.nz/albumdetails.aspx?MediaID=1177472&AffiliateID=14',
    'http://www.digirama.co.nz/SearchSummary.aspx?SearchString=nathan+haines&AffiliateID=14',
    'http://www.digirama.co.nz/artistdetails.aspx?AuthorID=4972'
	]; // set array of artists jb hifi

    //var artistBigpond = [
	var artistMarbecks = [
    'http://www.marbecks.co.nz/search/moreByArtist.lsd?searchTerm=kirsten+morrell&an=warner',
    'http://www.marbecks.co.nz/detail/index.lsd?catalogID=568253',
    'http://www.marbecks.co.nz/search/moreByArtist.lsd?searchTerm=j+williams&an=warner',
    'http://www.marbecks.co.nz/search/moreByArtist.lsd?searchTerm=nathan+haines&an=warner',
    'http://www.marbecks.co.nz/search/moreByArtist.lsd?searchTerm=shihad&an=warner'
	]; // set array of artists bigpond

    var artistITunes = [
    'http://www.s2d6.com/x/?x=c&z=s&v=1837881&t=http%3A%2F%2Fitunes.apple.com%2Fnz%2Fartist%2Fkirsten-morrell%2Fid329941830%3Fuo%3D6%26partnerId%3D1002',
    'http://itunes.apple.com/nz/album/the-experiment/id362120540',
    'http://www.s2d6.com/x/?x=c&z=s&v=1837881&t=http%3A%2F%2Fitunes.apple.com%2FWebObjects%2FMZStore.woa%2Fwa%2FviewArtist%3Fid%3D191923798%26uo%3D6%26partnerId%3D1002',
    '',
    'http://itunes.apple.com/nz/album/sleepeater/id365033487?i=365033493&uo=6']; // set array of artists itunes

    var randNum = Math.floor(Math.random() * artist.length); // generate random number

    if(pageLoad){
        var x;
        for(x in artist){ //loop through all artist names
            if (window.location.href.split(artist[x]).length > 1){ // if current artist name in list appears in page url
                randNum = x; // ovverrid the random number to number for that artist
            }
        }
    }

    if(artistLinkRef){ // if masthead randomiser is being called from an artist-thumb link
        x=0; 
        for(x in artist){ // loop through all the artist names
            if (artist[x] == artistLinkRef){ // if artist name equals an artist name in our artists list
                randNum = x; // override random number to number for that artist
            }
        }
    }

  //load the other artists
	if (!artistImageLoaded) {
		var ul = $(document.createElement('ul'));
		ul.attr('id', 'artist-thumb');
		for (x in artist) {
			//ie does some weird thing where it adds the map function to the artist array in IE. ignore it.
			if (x == 'map') {
				continue;
			}
			
			var li = $(document.createElement('li')).addClass('thumb-' + artist[x]);
			var a = $(document.createElement('a'));
			a.attr('href', '#' + artist[x]);
			var img = $(document.createElement('img')).attr('src', '/sites/all/themes/warner/images/' + artistThumbImage[x]);
			img.attr('width', '69');
			img.attr('height', '52');
			img.attr('alt', artist[x]);
			
			$(a).append(img);
			$(li).append(a);
			$(ul).append(li);
		}
		
		$('#other_artists').append(ul);
		
		artistImageLoaded = true;
	}

	var bgimage = 'url(/sites/all/themes/warner/images/' + artistBgImage[randNum] + ')';
	var headerbgimage = 'url(/sites/all/themes/warner/images/' + artistHeaderBgImage[randNum] + ')';
	
	$('div#masthead-area-c').css({'background-image': bgimage, 'background-repeat':'no-repeat'});
	$('div#masthead').css({'background-image': headerbgimage, 'background-repeat':'repeat-x'});

    $('div#masthead').removeClass().addClass(artist[randNum]); //replace #masthead div class with current artist class
    $('img.masthead-album-img').attr("src","/sites/all/themes/warner/images/album-img-"+artistAlbumImg[randNum]); //change album image src to random artist album image
    $('ul#artist-thumb li').css("display","inline"); // set all see other artists list entires to normal display
    $('li.thumb-'+artist[randNum]).css("display","none"); // hide current random artist from see other artists list
    $('iframe.masthead-video-player').attr("src",artistVideoURL[randNum]); // change video player src to random from list
    $('div.promo a.btn-d').attr("href",artistHref[randNum]); // set visit artist site button to artist url
    $('div.promo a.btn-d').attr("target",artistTarget[randNum]); // set target window
    $('div.promo a.buy-digirama ').attr("href",artistDigirama[randNum]); // set buy jb hifi link
    $('div.promo a.buy-marbecks ').attr("href", artistMarbecks[randNum]); // set buy bigpond link
    $('div.promo a.buy-itunes ').attr("href", artistITunes[randNum]); // set buy itunes link
    $('div.promo a.buy-digirama ').attr("target","_buy-digirama"); // set buy jb hifi link
    $('div.promo a.buy-marbecks ').attr("target", "_buy-marbecks"); // set buy bigpond link
    $('div.promo a.buy-itunes ').attr("target", "_buy-itunes"); // set buy itunes link

	//edit - add tracking
	$('div.promo a.buy-digirama').click(function() {
		pageTracker._trackEvent('Homepage Buy Now', artist[randNum], 'Digirama');
	});
	
	$('div.promo a.buy-marbecks').click(function() {
		pageTracker._trackEvent('Homepage Buy Now', artist[randNum], 'Marbecks');
	});
	
	$('div.promo a.buy-itunes').click(function() {
		pageTracker._trackEvent('Homepage Buy Now', artist[randNum], 'iTunes');
	});
	
	//new logic for the new header video player
	var vid_holder = $('#videoholder');
	if (vid_holder.length > 0) {
		
		if (artistVideoURL[randNum].length > 0) { 
			//then its an original video player, add an iframe
			var iframe = $(document.createElement('iframe'));
			if (iframe) {
				iframe.addClass('masthead-video-player');
				iframe.attr('src', artistVideoURL[randNum]);
				iframe.attr('width', '321');
				iframe.attr('height', '253');
				iframe.attr('frameborder', '0');
				iframe.attr('scrolling', 'no');
				vid_holder.append(iframe);
			}
		} else {
			//its a new player. Add it to the page
			//first, make sure the placeholder is there

			if (!playerLoaded) {
				createBrightCoveVideo('videoholder', 'myExperience22002380001', '17939730001', artistV2VideoPlayer[randNum]);
				
				playerLoaded = true;
			} else {
				loadBrightCoveVideo('myExperience22002380001', artistV2VideoPlayer[randNum]);
			}
			
		}
	}
	
    $('div#masthead').show(); // show the masthead
}



//creates a video on the page
function createBrightCoveVideo(locID, objectID, playerID, videoID) {
	var params = {};
	params.playerID = playerID;
	params.videoId = videoID;
	params.autoStart = "true";
	params.bgcolor = "#FFFFFF";
	params.width = "321";
	params.height = "253";
	params.isVid = "true";
	
	var player = brightcove.createElement("object");
	player.id = objectID;
	var parameter;
	for (var i in params) {
	     parameter = brightcove.createElement("param");
	     parameter.name = i;
	     parameter.value = params[i];
	     player.appendChild(parameter);
	}

	var playerContainer = document.getElementById(locID);
	brightcove.createExperience(player, playerContainer, true);
	

}

function loadBrightCoveVideo(experienceID, video) {
	bcExp = brightcove.getExperience(experienceID);		     
	modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
	modVP.loadVideo(video);
}