var abTests = Array();
var searchDefault = "Search Support";
$(document).ready(
    function(){
		// ######################
		// setup header search		
		if (!($('#header_search_form').css('display') != 'block')) { // make sure this element exists
			updateSearchEvents("header_search_form", "search_text", "Search");
		}
		// ######################
		// setup mini header search		
		if (!($('#mini_header_search_form').css('display') != 'block')) { // make sure this element exists
			updateSearchEvents("mini_header_search_form", "mini_search_text", searchDefault);
		}
		
		// ######################
		// setup mini title search		
		if (!($('#mini_title_search_form').css('display') != 'block')) { // make sure this element exists
			updateSearchEvents("mini_title_search_form", "mini_title_search_text", searchDefault);
		}
		
		// ######################
		// setup mini body search		
		if (!($('#top_search_lg_form').css('display') != 'block')) { // make sure this element exists
			updateSearchEvents("top_search_lg_form", "search_text_big", searchDefault);
		}
		
		// ######################
		// setup body search
		if (!($('#top_search_form').css('display') != 'block')){ // make sure this element exists
			// Make searchInput the big search input field if exists

			if ($('#top_search_form #search_text_big').css('display') != null) {
				updateSearchEvents("top_search_form", "search_text_big", searchDefault);

			} else {
				updateSearchEvents("top_search_form", "search_text1", searchDefault);
			}
		}
		
		// ######################
		// setup home AB test body search		
		if (!($('#home_search_form').css('display') != 'block')) { // make sure this element exists
			updateSearchEvents("home_search_form", "search_text_big", "Find Answers Here");
		}
		
		// ######################
		// add arrows to right side module links
		//$('ul.list_links li a').append('&nbsp;&nbsp;<img src="/support/images/modules/link_arrow.gif" style="vertical-align: -0.3em;"/>');
		
	}
);
function updateSearchEvents(formID, inputID, searchDefault){
	var form = $("#" + formID);
	var searchInput = $("#" + formID + " #" + inputID);

	if (searchInput.val() == '') {
		searchInput.val(searchDefault);
	}
	searchInput.focus(function(){
		searchFocus(searchInput, searchDefault);
	});
	searchInput.blur(function(){
		searchBlur(searchInput, searchDefault);
	});		
	form.submit(function() {
		return searchSubmit(searchInput.val(), searchDefault, false);
    });	
}
function searchFocus(searchInput, searchDefault){
	var searchInputText = $.trim(searchInput.val());
	if (searchInputText == searchDefault) {
		searchInput.val("");
		searchInput.removeClass("srch-light");
	}
}
function searchBlur(searchInput, searchDefault){
	var searchInputText = $.trim(searchInput.val());
	if (searchInputText == "") {
		searchInput.val(searchDefault);
		searchInput.addClass("srch-light");
	}
}
function searchSubmit(searchTerm, searchDefault, ignoreAlert){
	searchTerm = $.trim(searchTerm);

	if (searchTerm == searchDefault || searchTerm == "") {
		if (!ignoreAlert) alert('Please enter a search term');
		return false;
	}
	return true;
}
/////////////// ASA launch /////////////////////
function launchASA (){
	var topic = '';
	if (arguments.length>0) {
		topic = arguments[0];
	} else if (typeof(contactTopic) != 'undefined' && contactTopic != null) {
		topic = contactTopic;
	}
	OpenCenteredWindow('/support/asa/mainpage.jsp?topic='+topic,'tina', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes','600','525',true)
}

/////////////// CONTAINMENT FORM launch /////////////////////
function launchContainment(params){
	window.open("/support/containment/signup.jsp" + params, "containment_form", "resizable,scrollbars=yes,width=505,height=450");
}

/////// Session Id Functions Begin ////////////////////
function getSessionId(){
	// Get a sessionid, cookie, qs, generate
	var ttsid = "";	// Omniture session id
	// check cookie
	ttsid = getCookie("ttsid");
	if ((ttsid == "") || (ttsid == null)){
		// check url querystring
		var fullPageUrl = window.location.search;
		ttsid = getQueryStringValue(fullPageUrl, "ttsid");
	}
	if ((ttsid == "") || (ttsid == null)){
		// generate sessionid from guid
		ttsid = getGuid(20);
	}
	return ttsid;
}
function storeSessionId(ttsid){
	var expireDays = 220;
	var expireStamp = new Date(new Date().getTime() + expireDays * 24 * 3600 * 1000);
	setCookie("ttsid", ttsid, expireStamp, "/",sessionDomain);
}
function initSessionId(){
	var ttsid = getSessionId();
	storeSessionId(ttsid);
	return ttsid;
}
function getGuid(n){
	var t = new Date().getTime()+""; //milliseconds since 1 January 1970
	n = n - t.length;
	var g = t;
	for(var i = 0; i < n; i++) {
		g += Math.floor(Math.random() * 0xF).toString(0xF) + (i == 8 || i == 12 || i == 16 || i == 20 ? "-" : "");
	}
	return g;
}
/////// Session Id Functions End /////////////////
/////// Session Id Main Start ////////////////////
var sessionDomain=".intuit.com";
var ttsid = initSessionId();
var today = new Date();
var timeString = today.getTime();
var s_prop8 = ttsid;
/////// Session Id Main End ////////////////////

function getQueryStringValue(sourceUrl, key) {
  var u = sourceUrl;
  var parmValue = "";
  u = u.slice(1);
  parms = u.split("&");
  var parmArray = [];
  for ( var i = 0; i < parms.length; i++){
    parmArray.push(parms[i].split("="));
  }
  for (var i=0;i<parmArray.length; i++) {
    if (parmArray[i][0] == key) {
      parmValue = parmArray[i][1];
    }
  }
  return parmValue;
}

// Cookie management
function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
	document.cookie = curCookie;	
}
// get the query string parameter
function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
function OpenCenteredWindow(theURL,winName,features, myWidth, myHeight, isCenter) { //v3.0
	if (document.winName) { alert('exists'); }
  if(window.screen)if(isCenter)if(isCenter==true){
    var myLeft = (screen.width-myWidth)/2;
    var myTop = (screen.height-myHeight)/2;
    features+=(features!='')?',':'';
    features+=',left='+myLeft+',top='+myTop;
  }
  return window.open(theURL,winName,features+((features!='')?',':'')+'width='+myWidth+',height='+myHeight);
}
function trim (str){
	return str.replace(/^\s+|\s+$/g, '') ;
}
function windowSize() {
	// Get the visible width / height of the browser
	wAvail = window.innerWidth ? window.innerWidth : document.body.clientWidth;
	hAvail = window.innerHeight ? window.innerHeight : document.body.clientHeight;
	
	// Make sure we account for the scroll bar
	w = document.body.scrollWidth + document.body.scrollTop;
	h = document.body.scrollHeight + document.body.scrollTop;
	//alert(h);
	//alert(hAvail);
	// If the available width and height is more than the width/height, use them!
	if (wAvail > w) w = wAvail;
	if (hAvail > h) h = hAvail;

	// Now we need to get the available width and height of the window
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return Array(myWidth, myHeight);
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

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

// This function is used to capture click events within Omniture
// The sendClickEvent function is insed of the s_code_remote.js file
function trackPageClick(name, value){
	sendClickEvent(name + ": " + value);
}
// This function is primarily used for Omniture
// This will associate a page section with the path of the url
function getPageSection(){
	var sections =	[
						["/ag/", "AG"],
						["/agent/", "Agent"],
						["/amt/", "AMT"],
						["/ar/", "AR"],
						["/asa/", "ASA"],
						["/contact/", "Contact"],
						["/containment/", "Containment"],
						["/detail/", "FAQ"],
						["/kb/", "FAQ"],
						["/ecr/", "ECR"],
						["/fip/", "FIP"],
						["/internal/ops/", "Agent"],
						["/lta/", "LTA"],
						["/winback/", "Winback"],
						["/search.jsp", "Search"]
					];
	var pageSection = "Home";
	var location = document.location.href;

	for (var i=0; i<sections.length; i++) {
		if (location.indexOf(sections[i][0]) != -1) {
			pageSection = sections[i][1];
			break;
		}
	}

	return pageSection;
}

var baynoteDefaultGuides = {
	"forced_links" : {
		0 : {
			"url" : "/support/go/1086",
			"faq" : "1086",
			"title" : "2007 State Forms for Personal Returns"
		},
		1 : {
			"url" : "/support/go/3365",
			"faq" : "3365",
			"title" : "TurboTax 2007 Update Notes (Win/Mac)"
		},
		2 : {
			"url" : "/support/go/3662",
			"faq" : "3662",
			"title" : "Error 9107: TurboTax is having trouble accessing your updates"
		},
		3 : {
			"url" : "/support/kb/e-file/ef/5261.html",
			"faq" : "",
			"title" : "Processing Details for Your Return"
		},
		4 : {
			"url" : "/support/go/5069",
			"faq" : "5069",
			"title" : "What is the Alternative Minimum Tax (AMT)?"
		},
		5 : {
			"url" : "/support/go/35",
			"faq" : "35",
			"title" : "How to Update TurboTax"
		},
		6 : {
			"url" : "/support/go/3650",
			"faq" : "3650",
			"title" : "Manually Update TurboTax (Windows)"
		},
		7 : {
			"url" : "/support/go/113",
			"faq" : "113",
			"title" : "Configure Your Firewall Software"
		},
		8 : {
			"url" : "/support/go/601",
			"faq" : "601",
			"title" : "E-filing in TurboTax"
		},
		9 : {
			"url" : "/support/kb/tax-content/tax-tips/AMT.html",
			"faq" : "",
			"title" : "AMT Update: Will Your Refund Be Delayed This Year?"
		}
	}
}

function getDefaultBaynoteGuides(numLinksToReturn) {
	var defaultLinks = [];
	var count = 0;
	for (var o in baynoteDefaultGuides["forced_links"]) {
		var obj = baynoteDefaultGuides["forced_links"][o];
		defaultLinks.push(new Array(obj["url"], obj["faq"], obj["title"]));
		count++;
		if (count == numLinksToReturn) break;
	}
	return defaultLinks;
}
function printThis () {
	// open this page in another smaller window and add print=1 to url
	var hasQues = window.location.href.indexOf('?') != -1;
	OpenCenteredWindow(window.location.href+(hasQues?'&':'?')+'printIt=1','previewVersion', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes','700','800');	
}
function printIt () {
	if(window.print)	{
		window.print();
	} else {
		alert("Your browser does not support this functionality.  Try using Ctrl-P (Command-P on a Macintosh)");
	}
}
// ab test
function convertMbox (mboxName) {
	frames['mbox_convert'].location.href = '/support/fragments/ab/mbox_convert_click.jsp?mboxName='+mboxName;
}
function addABTest (test, recipe) {
	abTests.push(Array(test, recipe));
}
function stringToXML(xmlString)
{
	// Trim the string
	xmlString = $.trim(xmlString);
	
	xmlString = xmlString.replace(/&quot;/g, '"');
	xmlString = xmlString.replace(/&amp;quot;/g, '&quot;');
	xmlString = xmlString.replace(/&lt;/g, '<');
	xmlString = xmlString.replace(/&gt;/g, '>');
	
	var xml = xmlString;

	if (window.ActiveXObject) { // IE
		xml = new ActiveXObject("Microsoft.XMLDOM");
		xml.async = "false";
		xml.loadXML(xmlString);
		
	} else if (document.implementation && document.implementation.createDocument) { // Practically everyone else
		// Basically just Opera needs this
		var xmlParser = new DOMParser();
		xml = xmlParser.parseFromString(xmlString, "text/xml");
	}
	return xml;
}
