try {
  document.execCommand('BackgroundImageCache', true, true);
} catch(e) {}

$(document).ready(function(){
	$('#solutionator_shell').css('display','block');
	$('.solution_button a').each(function(i){
		var token = $(this).attr('id').substring(4);
		$(this).hoverIntent(function(){
			loadRequest(token, 1);
		},
		function(){ });
	});
});

var loadDialogBallon = false;
var currentToken = null;
var solutionatorHeight = 284;
var solutionatorBaynoteGuides = null;			// will contain the baynote guide xml once a topic is selected
var solutionatorBaynoteGuidesResults = {};		// Will contain all the guides returned from the ajax request to prevent duplicate requests
var solutionatorBaynoteGuidesForcedLinks = [];	// Will contain the links to force to the top of the baynote guides for each topic
var solutionatorBaynoteGuidesTotal = 5;			// Total number of results to return from Baynote

//###########################
// load the solutionator with this selection on page load
//###########################
function preLoad (token, showDialogBalloon) {
	//console.log(token);
	if (token == '') { return; }
	var tokens2Load = Array();
	var bn_request = token.substring(0,9) == 'bn_guides';
	var abbr = null;
	// get all tokens for this path
	if (bn_request) {
		abbr = token.substring(10);
		tokens2Load[0] = abbr_map[abbr];
		tokens2Load[1] = 'bn_guides_'+abbr_map[abbr];
	} else {
    	tokens2Load = getAncestorTokens(token, []);
    }
	// check if token node doesn't exists for this platform
	if($.find('#btn_'+tokens2Load[0]).length == 0)  { return; }

	var nodeParentCategory = null;
	var dialogTitle = null;
	var dialogDescription = null;

	if (tokens2Load[0] == 'tax_questions') {
		dialogTitle = 'Have a question about your taxes?';
	} else {
		if (bn_request) {
			dialogTitle = 'Have a question about '+$('#'+abbr_map[abbr]).siblings('a').html().replace(/&amp;/gi, "&")+'?';
		} else {
			dialogTitle = 'Have a question about '+$('#'+token).siblings('a').html().replace(/&amp;/gi, "&")+'?';
		}
	}

	dialogDescription = 'If so, click on a link to get your answer. If not, you can choose another tab or use search to get your answer.';

	if (tokens2Load.length>1) {
		$('#dialog_ballon .content .title').html(dialogTitle);
		$('#dialog_ballon .content .description').html(dialogDescription);
		$('#dialog_ballon .bottom').html('<a href="javascript:;">Close</a>');
		if (tokens2Load.length == 2) {
			$('#dialog_ballon').css('left','418px');
		}  else { // three
			$('#dialog_ballon').css('left','645px');
		}
		var verticalOffset = parseInt($('#dialog_ballon').height()) - 15;
		$('#dialog_ballon').css('top',-verticalOffset+'px');
		$('#dialog_ballon .bottom a').click( function () {
			toggleDialogBallon();
		});
		loadDialogBallon = (showDialogBalloon ? true : false);
	}

	// set the tab on state
	$('#btn_'+tokens2Load[0]).addClass('on');
	// load each of these tokens
	for (var i=0; i<tokens2Load.length; i++) {
        loadRequest(tokens2Load[i], i+1);
    }
    currentToken = tokens2Load[tokens2Load.length-1];
}

function loadRequest (token, clickLevel){
	//console.log(token);
	if (token == currentToken || token == null) { return; }

	// set the on state
	if (clickLevel == 1) {
		$('#btn_'+token).parent('li').parent('ul').children('li').children('a').removeClass('on');
		$('#btn_'+token).addClass('on');
	} else {
		$('#lnk_'+token).parent('li').parent('ul').children('li').children('a').removeClass('on');
        $('#lnk_'+token).addClass('on');
	}

	// get the new html
	// If the top 10 answers (baynote guides) was selected, load the baynote guides instead)
	if (token.substring(0,9) == "bn_guides") {
		var newHTML = createGuidesHTML(token);
		var trackText = $('#'+token.substring(10)).siblings('a').html().replace(/&amp;/gi, "&");
	} else {
		var newHTML = getLinksHTML(token, clickLevel);
		var trackText = $('#'+token).siblings('a').html().replace(/&amp;/gi, "&");
	}

	 // swap inital hero image and then load the new content
	if (currentToken == null) {
		var htmlString = '<div id="ie7fix"><img src="/common/images/1pxl.gif" width="1" height="220" border="0" align="right" /><div id="column_1" class="columns"></div><div id="column_2" class="columns"></div><div id="column_3" class="columns"></div><div class="clear_div"></div></div>';
		$('#blank_bg').hide();
		$('#solution_content').html(htmlString);
	}
		
	if (newHTML != '') {
		loadNewColumnHTML(clickLevel, newHTML);
	} else {
		return;
	}

    /*if (arguments.length>2 && clickLevel != 'tab') { // delayed if page load request, but not tab click
        setTimeout("setOnState('"+token+"', '"+clickLevel+"')", 500);
    } else {
        setOnState(token, clickLevel);
    }*/

	/* MP: Commented out because all the tracking is specific to Turbotax
	 *
	//Omniture Tracking
	switch (clickLevel) {
		case 1:
			solutionatorTrackPageClick("Home Topic", trackText, false);
		break;
		case 2:
			solutionatorTrackPageClick("Cat 1", trackText, true);
		break;
		case 3:
			solutionatorTrackPageClick("Cat 2", trackText, true);
		break;
	}*/

	if (clickLevel == 1) {
		// Populate the "solutionatorBaynoteGuides" variable with the baynote guides xml
		solutionatorBaynoteGuides = solutionatorBaynoteGuidesResults[token];
		if (solutionatorBaynoteGuides == null) {
			bnGuides.callback = "populate_guides";
			bnGuides.callbackParams = token;
			//MP: commented out since it was causing javascript issues...check with Kshitij if this is even needed
			//solutionatorBaynoteGuidesForcedLinks = getInstantAnswersForcedLinks(token);
			solutionatorBaynoteGuides = solutionatorBaynoteGuidesResults[token];
			bnGuides.get(token, solutionatorBaynoteGuidesTotal, Array());
		}
	}
	currentToken = token;
}


function loadGuide(token){
	// Populate the "solutionatorBaynoteGuides" variable with the baynote guides xml
	solutionatorBaynoteGuides = solutionatorBaynoteGuidesResults[token];
	if (solutionatorBaynoteGuides == null) {
		bnGuides.callback = "populateIA";
		bnGuides.callbackParams = token;
		//MP: commented out since it was causing javascript issues...check with Kshitij if this is even needed
		//solutionatorBaynoteGuidesForcedLinks = getInstantAnswersForcedLinks(token);
		solutionatorBaynoteGuides = solutionatorBaynoteGuidesResults[token];
		bnGuides.get(token, solutionatorBaynoteGuidesTotal, Array());
	}
	else{
		displayIA();
	}
}

function loadNewColumnHTML(clickLevel, newHTML) {
	switch (clickLevel) {
		case 1: // clicked top tabs
			$('#column_3, #column_2').empty();
			$('#column_1').html(newHTML);
			// turn off the leaf dividers
			$('#column_1').children('ul').children('li').children('a.leaf').each(function(){
				$(this).parent().css('border-bottom', 'solid 1px #fff');
			});
			$('#column_1').show();

			if ($('#dialog_ballon').css('visibility') == 'visible') {
				$('#dialog_ballon').css('visibility', 'hidden');
			}
		break;

		case 2: // clicked first column
			$('#column_3').empty();
			$('#column_2').html(newHTML);
			// turn off the leaf dividers
			$('#column_2').children('ul').children('li').children('a.leaf').each(function(){
				$(this).parent().css('border-bottom', 'solid 1px #fff');
			});
			$('#column_2').show();
			if (loadDialogBallon) {
				setTimeout("toggleDialogBallon();", 200);
				loadDialogBallon = false;
			}
		break;

		case 3: // clicked second column
			$('#column_3').html(newHTML);
			// turn off the leaf dividers
			$('#column_3').children('ul').children('li').children('a.leaf').each(function(){
				$(this).parent().css('border-bottom', 'solid 1px #fff');
			});
			$('#column_3').show();
			if (loadDialogBallon) {
				setTimeout("toggleDialogBallon();", 200);
				loadDialogBallon = false;
			}
		break;
	}
}

//###########################
// create html list column for requested node
//###########################
function getLinksHTML(node, level) {
	var childrenFound = false;

	// ul to place links in
	var unorderedListElement = document.createElement('ul');
	unorderedListElement.setAttribute('id','btn_'+node);

	$('ul#'+node+' li a').not($('ul#'+node+' li ul li a')).each(function (i, ele) {
		childrenFound = true;
		//  create category elements inside-out
        var anchorElement = document.createElement('a');
        //anchorElement.setAttribute('id',node);

		var linkText = $(this).html().replace(/&amp;/gi, "&");
		//linkText = linkText.replace(/\'/gi, "\'");

		if (ele.href == 'javascript:;') {
			var linkNode = $(this).siblings('ul').attr('id');

			anchorElement.setAttribute("href","javascript:;");
			anchorElement.setAttribute('id','lnk_'+linkNode);

			$(anchorElement).hoverIntent(function(){
				loadRequest(linkNode, parseInt(level+1));
			}, function(){});

		} else {
			anchorElement.setAttribute('href','javascript:gotoSolutionatorURL("' + ele.href + '", "' + linkText + '")');
			anchorElement.setAttribute((beforeIE8() ? 'className' : 'class'),'leaf');
		}

        anchorElement.appendChild(document.createTextNode(linkText));

        var listItemElement = document.createElement('li');
        listItemElement.appendChild(anchorElement);

        unorderedListElement.appendChild(listItemElement);

	});

	if ((level == 1)&&(showBN)) { // add "Most Viewed Topics" - baynote guides
		var anchorElement = document.createElement('a');
		anchorElement.setAttribute("href","javascript:;");
		anchorElement.setAttribute('id','lnk_bn_guides_'+node);
		$(anchorElement).hoverIntent(function(){
			loadRequest('bn_guides_'+node, parseInt(level+1));
		}, function(){});
        anchorElement.appendChild(document.createTextNode(mostViewed));

        var listItemElement = document.createElement('li');
        listItemElement.appendChild(anchorElement);

        unorderedListElement.appendChild(listItemElement);
	}


	return childrenFound ? unorderedListElement : '';
}

//###########################
// Load the baynote guides and create the html from the xml returned
//###########################
function createGuidesHTML() {
	// Timer used to to break out of while loop if 5 seconds has passed
	var timer = {
		time: 0,
		now: function(){ return (new Date()).getTime(); },
		start: function(){ this.time = this.now(); },
		since: function(){ return this.now()-this.time; }
	}
	timer.start();

	// To test the timeout function uncomment the following line
	//solutionatorBaynoteGuides = null;

	// Break out of the loop after 5 seconds
	while (solutionatorBaynoteGuides == null) {
		// do nothing
		if ((timer.since()/1000) > 5) {
			// Return a default 5 incase error occurs
			solutionatorBaynoteGuidesForcedLinks = getDefaultBaynoteGuides(5);
			//solutionatorBaynoteGuides = "";
			break;
		}
	}

	var unorderedListElement = document.createElement('ul');
	var anchorElement, url, faq, attr, title, omnitureTitle, linkTextElement, listItemElement, count = 0, found = false;
	// Add the hard-coded values
	if (solutionatorBaynoteGuidesForcedLinks.length > 0) {
		for (i=0; i<solutionatorBaynoteGuidesForcedLinks.length; i++) {
			url = solutionatorBaynoteGuidesForcedLinks[i][0];
			faq = solutionatorBaynoteGuidesForcedLinks[i][1];
			title = solutionatorBaynoteGuidesForcedLinks[i][2];
			omnitureTitle = title.replace("'", "\\'");

			// Create the anchor and append it to a list element the add it to the unordered list element for each hard-coded value
			anchorElement = document.createElement('a');
			anchorElement.setAttribute("href","javascript:gotoSolutionatorURL('" + url + "', '" + omnitureTitle + "')");
			anchorElement.setAttribute((beforeIE8() ? 'className' : 'class'),'leaf');
			linkTextElement = document.createTextNode(title);
	        anchorElement.appendChild(linkTextElement);

	        listItemElement = document.createElement('li');
	        listItemElement.appendChild(anchorElement);
			unorderedListElement.appendChild(listItemElement);

			count ++;
		}
	}
	//MP: added to avoid javascript errors
	/*else{
		listItemElement = document.createElement('li');
	}*/

	// Loop through all the r nodes
	$(solutionatorBaynoteGuides).find('r').each(function(){
		found = false;
		faq = "";

		if (count >= solutionatorBaynoteGuidesTotal) return false;

		// Get the FAQ
		$(this).find('a').each(function(){
			attr = $(this).attr('n');
         	if (attr == "content-id") {
				faq = $(this).attr('v');
			}
		});

		// Check if the FAQ exists in the hard coded values and if so, ignore it!
		if (solutionatorBaynoteGuidesForcedLinks.length > 0) {
         	for (i=0; i<solutionatorBaynoteGuidesForcedLinks.length; i++) {
         		if (faq == solutionatorBaynoteGuidesForcedLinks[i][1]) {
         			found = true;
         		}
         	}
         }

		if (!found) {
			title = $(this).attr('t');
			if(title != null)
				omnitureTitle = title.replace("'", "\\'");

			// use the actual FAQ URL instead of GO URL
			url = $(this).attr('u');

			anchorElement = document.createElement('a');
			anchorElement.setAttribute("href","javascript:gotoSolutionatorURL('" + url + "', '" + omnitureTitle + "')");
			anchorElement.setAttribute((beforeIE8() ? 'className' : 'class'),'leaf');
			linkTextElement = document.createTextNode(title);
	        anchorElement.appendChild(linkTextElement);

	        listItemElement = document.createElement('li');
	        listItemElement.appendChild(anchorElement);
			unorderedListElement.appendChild(listItemElement);

			count ++;
		}
	}); //close each(

	if(count > 0)
		unorderedListElement.appendChild(listItemElement);
	else
		unorderedListElement = null;
	
	return unorderedListElement;
}
//###########################
// This is the callback function that the baynote guides will use to populate the "solutionatorBaynoteGuides" variable with the guides
//###########################
function populate_guides(xml){
	solutionatorBaynoteGuides = xml;
	solutionatorBaynoteGuidesResults[arguments[1]] = xml;
}

// Call back function for baynote guides in the instant answers section
function populateIA(xml){
	solutionatorBaynoteGuides = xml;
	solutionatorBaynoteGuidesResults[arguments[1]] = xml;

	displayIA();
}

function displayIA(){
	var html = createGuidesHTML();
	$('.instant_answers_container').html(html);
}

//###########################
// return the parent, grand-parent, & great-grandparent ids from token
//###########################
function getAncestorTokens (token, tokensAry) {
    //console.log('token: '+token+', tokenAry: '+tokensAry);
	if (token.substring(0,9) == 'bn_guides') {
		return [token.substring(10)];
	}

	var parentUlId = null;

	tokensAry.unshift (token);
	if (parentUlId = $('#'+token).parent('li').parent('ul').attr('id')) {
		if (parentUlId == 'sol') {
			return tokensAry;
		} else {
			return getAncestorTokens (parentUlId, tokensAry);
		}
	} else {
		alert('ERROR - token not found: '+token);
		return [];
	}
}

//###########################
// This function is used to navigate to the provided url from any of the solutionator links.
// Adding this function to the href instead of the actual url allows us to add any additional javascript necessary.
//###########################
function gotoSolutionatorURL(url, title){
	var cm = new TTSCookieMgr();
	cm.setCookie("loadNode", currentToken);

	//solutionatorTrackPageClick("Sol", title, true);
	document.location = url;
}

//###########################
// This function is used to append the top level topic abbreviation to the tracked page value
//###########################
function solutionatorTrackPageClick(name, value, appendAbbreviation) {
	if (appendAbbreviation) {
		// Need to track the abbreviation of the top level element (topics)
		var tabSelected = getAncestorTokens(currentToken, [])[0];
		name += ": " + omniture_abbreviation[tabSelected];
	}
	trackPageClick(name, value);
}
var omniture_abbreviation = {
	'buying_billing' : 'BB',
	'login_install' : 'LIN',
	'install_update' : 'IU',
	'login_issues' : 'LIS',
	'import_transfer' : 'IT',
	'doing_your_taxes' : 'DYT',
	'tax_questions' : 'TQ',
	'printing_e-filing' : 'PE'
};
var abbr_map = {
	'bb' : 'buying_billing',
	'li' : 'login_install', //
	'iu' : 'install_update',//
	'lis' : 'login_issues',
	'it' : 'import_transfer',
	'dyt' : 'doing_your_taxes',
	'tq' : 'tax_questions',
	'pe' : 'printing_e-filing'
};
