/**
 * The base object that is used for any Dance Bracket related JSON processing.
 *
 * @type {Object}
 */
function NBADanceBracket(strInstance,strJsonPath,strJsonFile) {

	this.name = "NBADanceBracket";
	this.instanceName = strInstance;
	
	//Set the JSON path and file name
	this.jsonPath = "/multimedia/dancebracket/2009/";
	this.jsonFile = "dancebracket.html";

	//Set up the image server.
	var strServer = window.location.toString();

	if (strServer.indexOf("http://nba-webdev-preview") > -1) {
		this.imgPrefix = "http://nba-webdev-preview.nba.com";
		this.pagePrefix = this.imgPrefix;
	} else if (strServer.indexOf("http://nba-ref-preview") > -1) {
		this.imgPrefix = "http://nba-ref-preview.nba.com";
		this.pagePrefix = this.imgPrefix;
	} else {
		this.imgPrefix = "http://i.cdn.turner.com/nba/nba";
		this.pagePrefix = "http://www.nba.com";
	}

	//Set some additional internal values
	this.domDanceBracketReturn = "nbaDanceBracketCSIReturn";
	this.detailPage = "/dancebracket/2009/detail.html?matchup=";
	this.redirectPage = "https://audience.nba.com/services/msib/flow/registerOrAuthenticate?url=" + this.pagePrefix + this.detailPage;
	this.galleryDefault = "/.element/img/1.0/dancebracket/2009/center.png";
	this.currentBracket = 0;
	this.currentBracketName = "";
	this.currentConference = "";
	this.currentDate = "";
	this.activeBrackets = new Array();

	//If a different JSON path was passed in, override the default.
	if (strJsonPath) {
		this.jsonPath = strJsonPath;
	}

	//If a different JSON file was passed in, override the default.
	if (strJsonFile) {
		this.jsonFile = strJsonFile;
	}	
	
	/**
	 * Load the JSON using the standard CSI Manager.
	 *
	 * @method
	 */
	this.load = function(strMode) {

		//Get the Query String
		var strQueryString = window.location.search.substring(1);
		
		//Parse the Query String if it exists.
		if (strQueryString) {
			this.queryString = strQueryString.toQueryParams();
		}

		//Do this ugly process to pass in the parent
		var configData = CSIManager.getInstance().getConfigForId(this.domDanceBracketReturn);
		configData.parent = this;
		configData.mode = strMode;
		CSIManager.getInstance().setConfigForId(this.domDanceBracketReturn,configData);
		
		//Load the JSON and call a callback function.
		CSIManager.getInstance().call(this.jsonPath + this.jsonFile,null,this.domDanceBracketReturn,this.loadJson);

	} 

	/**
	 * The function used by the CSI Manager as a callback.
	 * Used to take all of the JSON assign it to a property.
	 *
	 * @method
	 */
	this.loadJson = function(objJson,strDomId,objConfig) {
	
		//Set the object parent
		var objParent = objConfig.parent;
		var strMode = objConfig.mode;

		//Copy the JSON if you need the details later, that way we don't have to go back to the CSIManager again.
		if (objJson.conference) {
			objParent.conference = objJson.conference;
		}

		//Decide which function to call.
		switch(strMode) {
			case 'brackets':
				objParent.loadBrackets();
			break;
			case 'matchup':
				objParent.loadMatchup();
			break;
		}
	}

	/**
	 * Load all of the brackets for the Dance Bracket home page.
	 *
	 * @method
	 */
	this.loadBrackets = function() {

		//Populate all brackets for all conferences.
		if (this.conference) {
			for (var i = 0; i < this.conference.length; i++) {
				for (var j = 0; j < this.conference[i].round.length; j++) {

					//Set the current conference.
					this.currentConference = this.conference[i].name;

					for (var k = 0; k < this.conference[i].round[j].bracket.length; k++) {
						//Populate a bracket.
						this.loadBracket(this.conference[i].round[j].bracket[k]);
					}	
				}
			}
		}
	}

	/**
	 * Load an individual bracket.
	 *
	 * @method
	 */
	this.loadBracket = function(objBracket) {

		for (var i = 0; i < objBracket.team.length; i++) {
			//Set the current match-up date.
			this.currentBracketName = objBracket.id;
			this.currentDate = objBracket.begins;
			this.loadTeam(objBracket.status,objBracket.id,objBracket.team[i]);
		}

	}

	/**
	 * Load an individual team.
	 *
	 * @method
	 */
	this.loadTeam = function(strStatus,strId,objTeam) {

		//If there is a team id
		if (objTeam.id) {

			//Set the grid values
			var domTeam = document.getElementById(objTeam.gridid);
			var domTeamPercent = document.getElementById(objTeam.gridid + 'p');
	
			//Create a new image.
			var domImage = new Image(35,35);
			domImage.src = this.imgPrefix + objTeam.logourl;
			domImage.alt = objTeam.name;
			domImage.title = objTeam.name;
			domImage.id = objTeam.gridid + 'i'; //Give the image an ID
			domImage.className = 'nbaDBIcon';

			//Cache the gallery image
			if (objTeam.galleryphoto) {

				//Get the image so that it is cached.
				var objImage = new Image(550,550);
				objImage.src = objTeam.galleryphoto;
				objImage.alt = objTeam.name;
				objImage.title = objTeam.name;

				domTeam.onmouseover = function() {
					
					var domImage = new Image(230,230);
					domImage.src = objImage.src;
					domImage.alt = objImage.alt;
					domImage.title = objImage.title;
					domImage.id ="frimgfade";
					
					domParent = document.getElementById("frimg");
					domParent.childNodes[0].id="frimgfade";
					setOpacity("frimgfade",0);
					window.domOldImage = domParent.replaceChild(domImage,domParent.childNodes[0]);
					fadeIn("frimgfade",20);
				}
				domTeam.onmouseout = function() {
					window.domOldImage.id ="frimgfade";
					domParent.replaceChild(window.domOldImage,domParent.childNodes[0]);
					setOpacity("frimgfade",100);
				}
			}
			
			//Remove the image if it exists
			var domTeamImages = domTeam.getElementsByTagName('IMG');
			if (domTeamImages.length > 0) {
				domTeam.removeChild(domTeamImages[0]);
			}
	
			//Remove any links that exist.
			var domTeamLinks = domTeam.getElementsByTagName('A');
			if (domTeamLinks.length > 0) {
				domTeam.removeChild(domTeamLinks[0]);
			}	
	
			//Set the percentage if there is a value to set.
			if (objTeam.percent && strStatus != 'pending') {

				//Set the percent text
				var domPercentText = document.createElement('span');
				domPercentText.appendChild(document.createTextNode(objTeam.percent + '%'));

				//If they have more than 50% of the vote, then bold it.
				if (objTeam.percent) {
					if (objTeam.percent > 50) {
						domPercentText.className = 'nbaDBHigh';
					} else {
						domPercentText.className = 'nbaDBLow';
					}
				}

				domTeamPercent.appendChild(domPercentText);

			} else if (strStatus != 'pending') {

				//Set the percent text
				var domPercentText = document.createElement('span');
				domPercentText.appendChild(document.createTextNode('0%'));	
				domPercentText.className = 'nbaDBLow';
				domTeamPercent.appendChild(domPercentText);

			}
	
			//Set all the values
			if ((strStatus == 'open' || strStatus == 'closed') || (strStatus == 'pending' && this.currentBracketName.length == 6)) {
	
				//Create a new link.
				var domLink = document.createElement('a');
				domLink.setAttribute('href',this.detailPage + strId);
	
				//Add the child to the image.
				domLink.appendChild(domImage);
	
				//Append the new link back.
				domTeam.appendChild(domLink);

			} else {
				domTeam.appendChild(domImage);
			}

			//If the current conference is the final conference, put the winner's image in the center.
			if (this.currentConference == 'finals' && strStatus == 'closed' && objTeam.percent > 50) {

				var domImage = new Image(230,230);
				domImage.src = objTeam.galleryphoto;
				domImage.alt = "Winner: " + objTeam.name;
				domImage.title = "Winner: " + objTeam.name;
				domImage.id ="frimgfade";
				
				domParent = document.getElementById("frimg");
				domParent.childNodes[0].id="frimgfade";
				setOpacity("frimgfade",0);
				window.domOldImage = domParent.replaceChild(domImage,domParent.childNodes[0]);
				fadeIn("frimgfade",20);	
			}
	
			//Set the opacity correctly
			if (strStatus == 'pending' || strStatus == 'closed') {
				setOpacity(objTeam.gridid + 'i',40);
			}
		}

		//If the competition is in the "pending" status, then output the date.
		if ((objTeam.order == 1 || this.currentConference  == 'finals') && strStatus == 'pending') {

			var domTeamPercent = document.getElementById(objTeam.gridid + 'p');			

			//Set the percent text
			var domPercentText = document.createElement('span');
			domPercentText.appendChild(document.createTextNode(this.currentDate));
			domPercentText.className = 'nbaDBHigh';
			domTeamPercent.appendChild(domPercentText);

		}
	}

	/**
	 * Load a match-up.
	 *
	 * @method
	 */
	this.loadMatchup = function(strBracketId) {

		var strMatchUp = '';

		//Clear this array
		this.activeBrackets = [];
		this.currentBracket = 0;

		//Set the current match-up information.
		if (strBracketId) {
			strMatchUp = strBracketId;
		} else if (this.queryString) {
			strMatchUp = this.queryString.matchup;
		}

		//Populate all brackets for all conferences.
		if (this.conference) {

			for (var i = 0; i < this.conference.length; i++) {
				for (var j = 0; j < this.conference[i].round.length; j++) {

					//Set the current conference.
					this.currentConference = this.conference[i].name;

					for (var k = 0; k < this.conference[i].round[j].bracket.length; k++) {

						//Set the current bracket to a variable.
						var objBracket = this.conference[i].round[j].bracket[k];

						//Set an array of active brackets
						if (objBracket.id.length == 6) {
							this.activeBrackets.push(objBracket.id);
						}

						//If the current bracket matches the current match-up passed in.
						if (objBracket.id == strMatchUp) {

							//Set the current bracket.
							this.currentBracket = this.activeBrackets.length - 1;

							//Load the galleries.
							this.loadGalleries(objBracket);

							//Load the poll.
							this.loadPoll(objBracket);
						}
					}	
				}
			}
		}

		//Set the bottom links
		this.loadPreviousLink();
		this.loadNextLink();
	}

	/**
	 * Load a match-up and refresh ads.
	 *
	 * @method
	 */
	this.reloadMatchup = function(strBracketId) {

		//Refresh the ads on the page.
		cnnad_refreshAds();

		//Load the match-up.
		this.loadMatchup(strBracketId);

	}

	/**
	 * Load both match-up galleries.
	 *
	 * @method
	 */
	this.loadGalleries = function(objBracket) {
		for (var i = 0; i < objBracket.team.length; i++) {
			var objTeam = objBracket.team[i];

			//Set the correct gallery based on the team order.
			if (objTeam.order == 1) {

				//Set the header.
				$$('#nbaLeftDancePhotoGalleryHeader span')[0].innerHTML = objTeam.name;

				//Set the gallery.
				window.objLeftGallery = new NBAPhotoGallery(objTeam.galleryurl + objTeam.galleryjson,"objLeftGallery");
				window.objLeftGallery.imageSize = "305";
				window.objLeftGallery.domCaption = "#nbaLeftPhotoContent .nbaPhotoCaption";
				window.objLeftGallery.domParagraph = "#nbaLeftPhotoContent .nbaPhotoPara";
				window.objLeftGallery.domParagraphText = "#nbaLeftPhotoContent .nbaPhotoPara span";
				window.objLeftGallery.domGalleryHeader = "#nbaLeftPhotoHeader .nbaPhotoAll a";
				window.objLeftGallery.domGalleryReturn = "nbaLeftPhotoCSIReturn";
				window.objLeftGallery.domImage = "nbaLeftPhotoImage";
				window.objLeftGallery.domLeftButton = "#nbaLeftPhotoContent .nbaPhotoLeftBtn a";
				window.objLeftGallery.domRightButton = "#nbaLeftPhotoContent .nbaPhotoRightBtn a";
				window.objLeftGallery.galleryURL = "";
				window.objLeftGallery.load();

				if (objTeam.galleryjson == 'defaultGallery.html') {
					$$('#nbaLeftTeamLink a')[0].style.visibility = "hidden";
					$$('#nbaLeftGalleryLink a')[0].style.visibility = "hidden";
				} else {
					$$('#nbaLeftTeamLink a')[0].style.visibility = "visible";
					$$('#nbaLeftGalleryLink a')[0].style.visibility = "visible";
				}

				//Set the team gallery link.
				$$('#nbaLeftGalleryLink a')[0].replaceChild(document.createTextNode('View the Fullsize Gallery'),$$('#nbaLeftGalleryLink a')[0].childNodes[0]);
				$$('#nbaLeftGalleryLink a')[0].href = objTeam.galleryurl + objTeam.galleryfile;

				//Set the team website link.
				$$('#nbaLeftTeamLink a')[0].replaceChild(document.createTextNode(objTeam.name + ' on ' + objTeam.websitename),$$('#nbaLeftTeamLink a')[0].childNodes[0]);
				$$('#nbaLeftTeamLink a')[0].href = objTeam.website;

			} else {

				//Set the header.
				$$('#nbaRightDancePhotoGalleryHeader span')[0].innerHTML = objTeam.name;

				//Set the gallery.
				window.objRightGallery = new NBAPhotoGallery(objTeam.galleryurl + objTeam.galleryjson,"objRightGallery");
				window.objRightGallery.imageSize = "305";
				window.objRightGallery.domCaption = "#nbaRightPhotoContent .nbaPhotoCaption";
				window.objRightGallery.domParagraph = "#nbaRightPhotoContent .nbaPhotoPara";
				window.objRightGallery.domParagraphText = "#nbaRightPhotoContent .nbaPhotoPara span";
				window.objRightGallery.domGalleryHeader = "#nbaRightPhotoHeader .nbaPhotoAll a";
				window.objRightGallery.domGalleryReturn = "nbaRightPhotoCSIReturn";
				window.objRightGallery.domImage = "nbaRightPhotoImage";
				window.objRightGallery.domLeftButton = "#nbaRightPhotoContent .nbaPhotoLeftBtn a";
				window.objRightGallery.domRightButton = "#nbaRightPhotoContent .nbaPhotoRightBtn a";
				window.objRightGallery.galleryURL = "";
				window.objRightGallery.load();

				if (objTeam.galleryjson == 'defaultGallery.html') {
					$$('#nbaRightTeamLink a')[0].style.visibility = "hidden";
					$$('#nbaRightGalleryLink a')[0].style.visibility = "hidden";
				} else {
					$$('#nbaRightTeamLink a')[0].style.visibility = "visible";
					$$('#nbaRightGalleryLink a')[0].style.visibility = "visible";
				}				

				//Set the team gallery link.
				$$('#nbaRightGalleryLink a')[0].replaceChild(document.createTextNode('View the Fullsize Gallery'),$$('#nbaRightGalleryLink a')[0].childNodes[0]);
				$$('#nbaRightGalleryLink a')[0].href = objTeam.galleryurl + objTeam.galleryfile;

				//Set the team website link.
				$$('#nbaRightTeamLink a')[0].replaceChild(document.createTextNode(objTeam.name + ' on ' + objTeam.websitename),$$('#nbaRightTeamLink a')[0].childNodes[0]);
				$$('#nbaRightTeamLink a')[0].href = objTeam.website;
			}
		}
	}

	/**
	 * Load the previous match-up link.
	 *
	 * @method
	 */
	this.loadPreviousLink = function() {

		var objImage;
		var objText;

		if ($$('#nbaMatchupPreviousLink a').length) {
			objImage = $$('#nbaMatchupPreviousLink a')[0].childNodes[0];
			objText = $$('#nbaMatchupPreviousLink a')[0].childNodes[1];

			$('nbaMatchupPreviousLink').removeChild($$('#nbaMatchupPreviousLink a')[0]);
		} else {
			objImage = $('nbaMatchupPreviousLink').childNodes[0];
			objText = $('nbaMatchupPreviousLink').childNodes[1];	
		}

		if (this.currentBracket > 0) {
			var objLink = document.createElement('a');
			objLink.href = 'javascript:' + this.instanceName + ".reloadMatchup('" + this.activeBrackets[this.currentBracket - 1] + "')";
			objLink.appendChild(objImage);
			objLink.appendChild(objText);
			$('nbaMatchupPreviousLink').appendChild(objLink);

		} else {
			$('nbaMatchupPreviousLink').appendChild(objImage);
			$('nbaMatchupPreviousLink').appendChild(objText);
		}
	}

	/**
	 * Load the next match-up link.
	 *
	 * @method
	 */
	this.loadNextLink = function() {

		var objImage;
		var objText;

		if ($$('#nbaMatchupNextLink a').length) {
			objText = $$('#nbaMatchupNextLink a')[0].childNodes[0];
			objImage = $$('#nbaMatchupNextLink a')[0].childNodes[1];
			
			$('nbaMatchupNextLink').removeChild($$('#nbaMatchupNextLink a')[0]);
		} else {
			objText = $('nbaMatchupNextLink').childNodes[0];
			objImage = $('nbaMatchupNextLink').childNodes[1];	
		}		

		if ((this.currentBracket + 1) < this.activeBrackets.length) {
			var objLink = document.createElement('a');
			objLink.href = 'javascript:' + this.instanceName + ".reloadMatchup('" + this.activeBrackets[this.currentBracket + 1] + "')";
			objLink.appendChild(objText);
			objLink.appendChild(objImage);
			$('nbaMatchupNextLink').appendChild(objLink);

		} else {
			$('nbaMatchupNextLink').appendChild(objText);
			$('nbaMatchupNextLink').appendChild(objImage);
		}
	}

	/**
	 * Load the match-up poll.
	 *
	 * @method
	 */
	this.loadPoll = function(objBracket) {

		//If the status is closed, then display the results.
		//Should convert to a switch sometime.

		var strStatus = "";

		//Check if the All-Access cookie has been set, if not, then display log-in box.
		if (document.cookie.indexOf("TSid=G") != -1) {
			strStatus = objBracket.status;
		} else {
			strStatus = "login";
		}

		switch(strStatus) {

			case 'closed':

				var domMainDiv = document.createElement('div');
				this.frame = $('nbaDancePoll').replaceChild(domMainDiv,$('nbaDancePollFrame'));
				domMainDiv.id = 'nbaDancePollFrame';
				domMainDiv.style.height = "95px";

				var domSubDiv = document.createElement('div');
				domMainDiv.appendChild(domSubDiv);
				domSubDiv.style.height = "94px";

				var domH1 = document.createElement('h1');
				domSubDiv.appendChild(domH1);
				domH1.appendChild(document.createTextNode('VOTING'));

				var domTeam1 = document.createElement('h3');
				domSubDiv.appendChild(domTeam1);
				domTeam1.className = 'pollResults';
				domTeam1.appendChild(document.createTextNode(objBracket.team[0].name + ': ' + objBracket.team[0].percent + '%'));

				var domTeam2 = document.createElement('h3');
				domSubDiv.appendChild(domTeam2);
				domTeam2.className = 'pollResults';
				domTeam2.appendChild(document.createTextNode(objBracket.team[1].name + ': ' + objBracket.team[1].percent + '%'));

				var domStatus = document.createElement('h2');
				domSubDiv.appendChild(domStatus);
				domStatus.style.position = "absolute";
				domStatus.style.top = "77px";
				domStatus.appendChild(document.createTextNode('CLOSED'));

			break;

			case 'pending':

				var domMainDiv = document.createElement('div');
				this.frame = $('nbaDancePoll').replaceChild(domMainDiv,$('nbaDancePollFrame'));
				domMainDiv.id = 'nbaDancePollFrame';
				domMainDiv.style.height = "120px";

				var domSubDiv = document.createElement('div');
				domMainDiv.appendChild(domSubDiv);
				domSubDiv.style.height = "119px";

				var domH1 = document.createElement('h1');
				domSubDiv.appendChild(domH1);
				domH1.appendChild(document.createTextNode('VOTING'));

				var domTeam1 = document.createElement('h3');
				domSubDiv.appendChild(domTeam1);
				domTeam1.className = 'pollResults';
				domTeam1.appendChild(document.createTextNode(objBracket.team[0].name));

				var domVs = document.createElement('h3');
				domSubDiv.appendChild(domVs);
				domVs.className = 'pollResults';
				domVs.appendChild(document.createTextNode('VS.'));

				var domTeam2 = document.createElement('h3');
				domSubDiv.appendChild(domTeam2);
				domTeam2.className = 'pollResults';
				domTeam2.appendChild(document.createTextNode(objBracket.team[1].name));

				var domStatus = document.createElement('h2');
				domSubDiv.appendChild(domStatus);
				domStatus.style.position = "absolute";
				domStatus.style.top = "102px";
				domStatus.appendChild(document.createTextNode('OPENS ON ' + objBracket.begins));

			break;

			case 'login':

				var domMainDiv = document.createElement('div');
				this.frame = $('nbaDancePoll').replaceChild(domMainDiv,$('nbaDancePollFrame'));
				domMainDiv.id = 'nbaDancePollFrame';
				domMainDiv.style.height = "131px";

				var domSubDiv = document.createElement('div');
				domMainDiv.appendChild(domSubDiv);
				domSubDiv.style.height = "130px";

				var domH1 = document.createElement('h1');
				domSubDiv.appendChild(domH1);
				domH1.appendChild(document.createTextNode('PLEASE'));

				var domText = document.createElement('h3');
				domSubDiv.appendChild(domText);
				domText.className = 'pollResults';
				domText.appendChild(document.createTextNode('You must be an All-Access member in order to vote.'));

				var domLink = document.createElement('a');
				domSubDiv.appendChild(domLink);
				domLink.href = this.redirectPage + objBracket.id;
				domLink.className = 'pollLink';
				domLink.appendChild(document.createTextNode('Sign Up or Log In to All-Access'));

				var domStatus = document.createElement('h2');
				domSubDiv.appendChild(domStatus);
				domStatus.style.position = "absolute";
				domStatus.style.top = "113px";
				domStatus.appendChild(document.createTextNode('LOGIN'));

			break;

			default:

				var domMainDiv = document.createElement('div');
				this.frame = $('nbaDancePoll').replaceChild(domMainDiv,$('nbaDancePollFrame'));
				domMainDiv.setAttribute('id','nbaDancePollFrame');
				domMainDiv.style.height = "184px";
	
				var domSubDiv = document.createElement('div');
				domMainDiv.appendChild(domSubDiv);
				domSubDiv.style.height = "183px";
	
				var domH1 = document.createElement('h1');
				domSubDiv.appendChild(domH1);
				domH1.appendChild(document.createTextNode('VOTING'));
	
				var domFrame = document.createElement('iframe');
				domFrame.frameBorder = "no";
				domFrame.setAttribute('id','nbaDancePollFrameContent');
				domFrame.src = 'about:blank';
				domFrame.setAttribute('scrolling','no');
				domSubDiv.appendChild(domFrame);
				domFrame.src = objBracket.pollurl;
				domFrame.style.visibility='visible';
	
				var domStatus = document.createElement('h2');
				domSubDiv.appendChild(domStatus);
				domStatus.appendChild(document.createTextNode('OPEN'));

		}
	}
}