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) {
	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){
	if (token == "buying_billing") { tokenPRS = "Account_Updates_Billing"} 
	else if (token == "login_issues") { tokenPRS = "Employees_And_Employee_Taxes"} 
	else if (token == "install_update") { tokenPRS = "Payroll_And_Direct_Deposit"} 
	else if (token == "login_install") { tokenPRS = "Tax_Forms_And_Payroll_Liabilities"} 
	else if (token == "import_transfer") { tokenPRS = "Software_Operations"} 
	else if (token == "tax_questions") { tokenPRS = "Errors_And_Software_Troubleshooting"} 
	else {}
	if (token == currentToken || token == null) { return; }
	
	//PTS support
	if (token.substring(0,3)=="PTS"){
		switch(token.substring(4)){
			case "agency":
				parsePTSDocs("Ca");
			break;
			case "duedates":
			break;
			case "supported":
			break;
			case "efile":
			break;
			case "sstate":
			break;
		}
			
		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="/support/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>';
			
		$('#solution_content').html(htmlString);
		$('#solTestBdv #solution_content .columns').css('width','550px');
		$('#solTestBdv #solution_content .columns').css('padding','20px 0 0 20px');
	}	
	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);
    }*/
	
	// Omniture Tracking
    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;
			solutionatorBaynoteGuidesForcedLinks = '' /* getInstantAnswersForcedLinks(token); */
			solutionatorBaynoteGuides = solutionatorBaynoteGuidesResults[token];
			bnGuides.get(tokenPRS, solutionatorBaynoteGuidesTotal, Array());
		}
	}
	
	currentToken = token;
}

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');
				
				var mylinkEL = this.getAttribute("href");
				var gtL= mylinkEL.match ('#nw')
				var gtPDF= mylinkEL.match ('.pdf')								
				if (gtPDF == ".pdf") {
					$(this).css('background', 'url(/support/images/icons/pdfIcon.gif) no-repeat 8px 12px #FFFFFF');
				} else if (gtL == "#nw"){
					$(this).css('background', 'url(/support/images/icons/solArrow.gif) no-repeat 8px 12px #FFFFFF');
				}
				
			});
			$('#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');
				
				var mylinkEL = this.getAttribute("href");
				var gtL= mylinkEL.match ('#nw')
				var gtPDF= mylinkEL.match ('.pdf')								
				if (gtPDF == ".pdf") {
					$(this).css('background', 'url(/support/images/icons/pdfIcon.gif) no-repeat 8px 12px #FFFFFF');
				} else if (gtL == "#nw"){
					$(this).css('background', 'url(/support/images/icons/solArrow.gif) no-repeat 8px 12px #FFFFFF');
				}
				
			});
			$('#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');
				
				var mylinkEL = this.getAttribute("href");
				var gtL= mylinkEL.match ('#nw')
				var gtPDF= mylinkEL.match ('.pdf')								
				if (gtPDF == ".pdf") {
					$(this).css('background', 'url(/support/images/icons/pdfIcon.gif) no-repeat 8px 12px #FFFFFF');
				} else if (gtL == "#nw"){
					$(this).css('background', 'url(/support/images/icons/solArrow.gif) no-repeat 8px 12px #FFFFFF');
				}
				
			});
			$('#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((document.all ? 'className' : 'class'),'leaf');
		}
		
        anchorElement.appendChild(document.createTextNode(linkText));
        
        var listItemElement = document.createElement('li');            
        listItemElement.appendChild(anchorElement);

        unorderedListElement.appendChild(listItemElement);
		
	});
	
	if (level == 1) { // 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('Most Viewed Topics'));
        
        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];
			url = url.replace('http://turbotax.intuit.com/','/');
			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('" + URLencode(url) + "', '" + URLencode(omnitureTitle) + "')");
			anchorElement.setAttribute((document.all ? 'className' : 'class'),'leaf');
			linkTextElement = document.createTextNode(title);
	        anchorElement.appendChild(linkTextElement);
	        
	        listItemElement = document.createElement('li');            
	        listItemElement.appendChild(anchorElement);
			unorderedListElement.appendChild(listItemElement);
			
			count ++;
		}
	}
	
	// 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');
			url = $(this).attr('u');
			url = url.replace('http://turbotax.intuit.com/','/');
			
			omnitureTitle = title.replace("'", "\\'");
			
			anchorElement = document.createElement('a');
			anchorElement.setAttribute("href","javascript:gotoSolutionatorURL('" + URLencode(url) + "', '" + URLencode(omnitureTitle) + "')");
			anchorElement.setAttribute((document.all ? 'className' : 'class'),'leaf');
			linkTextElement = document.createTextNode(title);
	        anchorElement.appendChild(linkTextElement);
	        
	        listItemElement = document.createElement('li');            
	        listItemElement.appendChild(anchorElement);
			unorderedListElement.appendChild(listItemElement);
			
			count ++;
		}        
	}); //close each(

	unorderedListElement.appendChild(listItemElement);
	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;
}

//###########################
// return the parent, grand-parent, & great-grandparent ids from token
//###########################
function getAncestorTokens (token, 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 [];
	}
}
/*******************************************************************
*
* By: 			frederick_rodolfo@intuit.com 12/19/2008
* Description:	This function encodes single and double quotes so
* 				that they don't break the string that's used as
* 				a URL in Javascript
* 
* @param 	sStr
* @return 	sStr
* 
********************************************************************/
function URLencode(sStr) 
{
	return sStr.replace(/\"/g,'&#34;').replace(/\'/g, '&#39;');
}

//###########################
// 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);
	var myArticle = url + " #SupportTabsContainer";
	var myArticleN = url + " #commerceDisplay";
	
	//$('#article').html('<iframe id="esubFrame" frameBorder="0" style="left:0px;width:590px;border:0px solid #fff" scrolling="no" />');
	//document.getElementById('esubFrame').setAttribute('height', '1150');
	//document.getElementById('esubFrame').setAttribute('src', url);
	//checkForProp = url
	step3param = "1"
	var gt= url.match ('#nw')
	if (gt != "#nw") {
		document.location = url;
	} else {
		window.open (url)
	}
	pprLong = "";
	if (ppr == "2") {
		pprLong = "Assisted : "
	} else if (ppr == "4") {
		pprLong = "Standard : "
	} else if (ppr == "8") {
		pprLong = "Enhanced : "
	} else if (ppr == "16") {
		pprLong = "Basic : "
	} else if (ppr == "32") {
		pprLong = "Complete : "
	} else if (ppr == "64") {
		pprLong = "IOP : "
	} else if (ppr == "256") {
		pprLong = "QBOP : "
	}
	
	solutionatorTrackPageClick("Home_SolLink_" + pprLong, title, false);
	//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 parentTokens = getRelatedTokens(currentToken)[0];
		var abbr = solutionator1[parentTokens]['omniture_abbriviation']
		name += ": " + abbr;
	}
	trackPageClick(name, value)
}
function trackPageClick(name, value){
	// sendClickEvent(name + value);
	// alert (name + "_______" + value)
	
	var scVariableMap = {};
	var scEventList = [];
	var scSolTab = name + value;
	var scLinkType = "o";
	var scSolOm = new CustomLink(scVariableMap,scEventList,scSolTab,scLinkType);
	
	sendCustomLink(scSolOm,this)
}



