/* ########################################################################### *
/* ***** DOCUMENT INFO ******************************************************* *
/* ########################################################################### *
 * ##### NAME:  global.js
 * ##### VERSION: v1.5
 * ##### UPDATED: 7 July 2009 (Damian Keeghan, Deloitte's Online Practice)
/* ########################################################################### *

/* ########################################################################### *
/* ***** INDEX *************************************************************** *
/* ########################################################################### *
/* ##### GLOBAL VARIABLES
/* ##### INITIALISATION
/* ##### CLEAR FIELD HINT
/* ##### TOP NAVIGATION
/* ##### SEARCH DOMAIN DROPDOWN
/* ##### PAGE OPTIONS
/* ##### CAPTIONED IMAGE
/* ##### PRODUCT SECTIONS
/* ##### FAQ QUESTIONS
/* ##### SITEMAP
/* ##### TAGS LIST
/* ##### POPUP WINDOW
/* ##### HOME TABS
/* ##### HOMEPAGE LOGIN
/* ##### FLASH BANNER INTERFACE
/* ########################################################################### */

/* ########################################################################### *
/* ##### GLOBAL VARIABLES
/* ########################################################################### */

//If login is successful the page is redirected to the following page.
teg_login_successTarget = "http://www.telstra.com.au/enterprise/yourtelstratools";

//In order to retrieve the password, the page is redirected to a url with the 
// URL variables appended:
//The following URL Variables are added:
//rne_eventType= [teg_login_rne_eventType variable below]
//rne_username= [USERNAME]
//rne_businessId= [BUSINESS ID]
//rne_errorTargetUrl= [CURRENT URL with ?SMAUTHREASON=220 appended]
teg_login_retrievePasswordUrl = "https://register.telstra.com.au/tra/rne";
teg_login_rne_eventType = "sb.sl.credential.event.ForgottenPasswordRequestEvent";

/* ########################################################################### *
/* ##### INITIALISATION
/* ########################################################################### */
$(document).ready(init);

function init()
{
	init_pageOptions();
	init_clearHint();
	init_tagDisplay();
	init_dropDownNav();
	init_searchDropDown();
	init_faqQuestions();
	init_captionedImage();
	init_sitemapDropDown();
	init_checkForLoginError();
	init_homeTabs();
	init_loginTabs();
}



/* ########################################################################### *
/* ##### CLEAR FIELD HINT
/* ########################################################################### */
function init_clearHint()
{
	$(".clearHint").focus(function(){
		$(this).attr("value","");
	});
}



/* ########################################################################### *
/* ##### TOP NAVIGATION
/* ########################################################################### */
function init_dropDownNav()
{
	$("ul.gloNav").superfish();
	$("ul.gloNav > li > a").addClass("dropDown");
	$("ul.topNav")
	.superfish()
	.find(">li:has(ul)")
		.mouseover(function(){
			$("ul", this).bgIframe({opacity:false});
		})
		.find("a")
			.focus(function(){
				$("ul", $("ul.topNav>li:has(ul)")).bgIframe({opacity:false});
			});
}



/* ########################################################################### *
/* ##### SEARCH DOMAIN DROPDOWN
/* ########################################################################### */
function init_searchDropDown()
{
	$('#searchList li').sfHover();
	$('.domTel').click(function() {
		$('#searchDomain').removeClass("web").removeClass("bigpond");
		if ($('.siteSearch').val() == 'Search Telstra' || $('.siteSearch').val() == 'Search The Web' || $('.siteSearch').val() == 'Search Bigpond' || $('.siteSearch').val() == '')
		{
			setTimeout(function(){
				$('#headWrapper input.siteSearch').trigger("focus");
			}, 100);
		}
		$('#searchList li').removeClass("sfHover");
	});
	$('.domWeb').click(function() {
		$('#searchDomain').addClass("web").removeClass("bigpond");
		if ($('.siteSearch').val() == 'Search Telstra' || $('.siteSearch').val() == 'Search The Web' || $('.siteSearch').val() == 'Search Bigpond' || $('.siteSearch').val() == '')
		{
			setTimeout(function(){
				$('#headWrapper input.siteSearch').trigger("focus");
			}, 100);
		}
		$('#searchList li').removeClass("sfHover");
	});
	$('.domBigpond').click(function() {
		$('#searchDomain').removeClass("web").addClass("bigpond");
		if ($('.siteSearch').val() == 'Search Telstra' || $('.siteSearch').val() == 'Search The Web' || $('.siteSearch').val() == 'Search Bigpond' || $('.siteSearch').val() == '')
		{
			setTimeout(function(){
				$('#headWrapper input.siteSearch').trigger("focus");
			}, 100);
		}
		$('#searchList li').removeClass("sfHover");
	});
	
	$('#headWrapper .siteSearch').bind("blur", function(){
		if ($('#headWrapper .siteSearch').val() == ''){		
			if($('#searchDomain').hasClass("bigpond")){
				$('#headWrapper .siteSearch').attr({value:"Search Bigpond"});
			} else if($('#searchDomain').hasClass("web")){
				$('#headWrapper .siteSearch').attr({value:"Search The Web"});
			} else {
				$('#headWrapper .siteSearch').attr({value:"Search Telstra"});
			}
		}
	});
	
	$('.domTel,.domWeb,.domBigpond').hover(
		function () {
			$(this).addClass("over");
		},
		function () {
			$(this).removeClass("over");
		}
	);
}



/* ########################################################################### *
/* ##### PAGE OPTIONS
/* ########################################################################### */

function init_pageOptions()
{
	init_blogsPageOptions();
	
	if($("div#bdPageOptions").parents("table").length>0){
		movePageOptionsDiv();	
	}
	
	var optionsConfig = $("#bdPageOptions").find("span.bmSendLink");
	var sendLink = "form_sendToCol1.htm";
	
	if(optionsConfig.length>0){
		sendLink = optionsConfig.text();
	}
	
	var poList = document.createElement('ul');
	poList.id = 'poContainer';
	var oList1 = document.createElement('li');
	oList1.id = 'poPrint';
	var oLink1 = "<span class='replacement'></span><a href='#' class='printLink'><span class='replacement' title='Print this page'></span>Print this page</a>"
	oList1.innerHTML = oLink1;
	var oList2 = document.createElement('li');
	oList2.id = 'poEmail';
	var oLink2 = "<span class='replacement'></span><a href='"+sendLink+"' class='bmSend'><span class='replacement' title='Email page'></span>Email page</a>"
	oList2.innerHTML = oLink2;
	$(poList).append(oList1,oList2);
	$('#bdPageOptions').append(poList);
	
	$('.printLink').click(function() {
		window.print();
		return false;
	});
}

function movePageOptionsDiv(){
	var pageOptions = $("div#bdPageOptions").parent().html();
	$("div#bdPageOptions").parents("table:first").parents("tr:first").remove();
	
	$("td.ms-pagebreadcrumb").find("span:first").after(pageOptions);
	$("div#bdPageOptions").addClass("blogsPageOptions");
}

function init_blogsPageOptions(){
	$("td.ms-pagebreadcrumb").find("span:first").addClass("breadcrumbsSpan");
	//$("div#bdPageOptions").parents("table:first").addClass("bdPageOptionsTable");
}

/* ########################################################################### *
/* ##### CAPTIONED IMAGE
/* ########################################################################### */
function init_captionedImage()
{
	$('.captioned').hover(function(){
		$(this).children('.imgCaption').animate({marginTop: -10, paddingTop: 20}, "normal");
	},function(){
		$(this).children('.imgCaption').animate({marginTop: 0, paddingTop: 10}, "normal");
	});
	$('.captioned').click(function(){
		$(this).next().click();
	});
}

/* ########################################################################### *
/* ##### FAQ QUESTIONS
/* ########################################################################### */
function init_faqQuestions()
{
	$('.answer').hide();
	$('.faqList li').addClass('expand');
	
	$('.faqList h2').click(function(){
		if ($(this).parent().hasClass('on')) {
			$(this).next('.answer').slideUp();
			$(this).parent().removeClass('on');
		}
		else {
			$('.answer').slideUp();
			$('.answer').parent().removeClass('on');
			$(this).next('.answer').slideDown();
			$(this).parent().addClass('on');
		}
	});
}



/* ########################################################################### *
/* ##### SITEMAP
/* ########################################################################### */
function init_sitemapDropDown()
{
	if($('a.sm_toggle,a.sm_close').length>0){
		$('a.sm_toggle,a.sm_close').click(function() {
			$('.ftSitemap').slideToggle("slow");
			return false;
		});
	}
}



/* ########################################################################### *
/* ##### TAGS LIST
/* ########################################################################### */
function init_tagDisplay()
{
	//Change fifth item comma to elipses and hide the rest of the tags
	$(".tags").each(function(){
		midTag = $(this).contents(":nth-child(6)").html();
		if (midTag) {
			newMidTag = midTag.replace(",","...");
			$(this).contents("dd:nth-child(6)").html(newMidTag);
			$(this).contents("dd:nth-child(6)").nextAll().hide();
		}
	});
		
	//Display hidden tags on rollover
	$(".tags").hover(function(){
		midTag = $(this).contents(":nth-child(6)").html();
		if (midTag) {
			newMidTag = midTag.replace("...",",");
			$(this).contents("dd:nth-child(6)").html(newMidTag);
			$(this).contents("dd:nth-child(6)").nextAll().show();
		}
	},function(){
		midTag = $(this).contents(":nth-child(6)").html();
		if (midTag) {
			newMidTag = midTag.replace(",","...");
			$(this).contents("dd:nth-child(6)").html(newMidTag);
			$(this).contents("dd:nth-child(6)").nextAll().hide();
		}
	});
}



/* ########################################################################### *
/* ##### POPUP WINDOW
/* ########################################################################### */

function popWindow(linkUrl) {
	targetHref = $(linkUrl)[0].href;
	window.open(targetHref,"_blank","height=640,width=700,toolbar=no,menubar=no,location=no,scrollbars=yes,status=no");
	// Return false to prevent the link click navigation occuring.
	return false;
}

/* ########################################################################### *
/* ##### HOME TABS
/* ########################################################################### */

function init_homeTabs(){
	if($("#homeTabs").length>0){
		$("#homeTabs .homeTabs-nav li").each(function(){
			var tab = $(this);
			$(this).find("a").click(function(){
				if(!$(tab).hasClass("homeTabs-selected")){
					homeTabs_switch(tab);
					homeTabs_updateContent($(this).attr("href"), $(this).attr("rel"));
				}
				return false;
			});
		});
		
		$("#tabsContainer div.tabsContent:not(:first)").each(function(){
			$(this).hide();																				  
		});
	}
}

function homeTabs_switch(tab){
	$("#homeTabs .homeTabs-nav li").each(function(){
		if($(this).find("a").text()==$(tab).find("a").text()){
			$(this).addClass("homeTabs-selected");	
		} else {
			$(this).removeClass("homeTabs-selected");	
		}
	});
}

function homeTabs_updateContent(href, rel){
	$("#tabsContainer").addClass("ieBgWhite");
	
	$("#tabsContainer").animate({opacity: 0}, 250, null, function(){
		var mediaHtmlNodes = $(htmlNodes);
		$(mediaHtmlNodes).remove();
		
		$("#tabsContainer div.tabsContent").each(function(){
			if($(this).attr("id")==$(rel).attr("id")){
				$(this).show();
			} else {
				$(this).hide();
			}
			
			$("#tabsContainer").animate({opacity: 1}, 250);	
		});
	});
}

/* ########################################################################### *
/* ##### HOMEPAGE LOGIN
/* ########################################################################### */

//global vars
var CURRENT_LOGIN_TYPE = "#tab_standard"; //[#tab_standard|#tab_certificate]

//setup
function init_loginTabs(){
	if($(".login").length>0){
		$("#loginvia option:selected").each(function(){
			$(this).removeAttr("selected");					 
		});
		
		$("#loginvia").change(function(){
			var id = $(this).find("option:selected").val();	
			switchLoginTab(id);
		});
		
		$("#tab_certificate").hide().animate({opacity: 0}, 1);
		
		setupLogin();
	}
}

function switchLoginTab(id){
	if(CURRENT_LOGIN_TYPE!="#"+id){
		$(CURRENT_LOGIN_TYPE).animate({opacity: 0}, 250, null, function(){
			$(CURRENT_LOGIN_TYPE).hide();
			CURRENT_LOGIN_TYPE = "#"+id;
			$(CURRENT_LOGIN_TYPE).show().animate({opacity: 1}, 250);
		});
	}
}

//functionality
function setupLogin(){
	//Add form to page
	addLoginForm();
	
	$("#login_standard").click(function(e){
		e.preventDefault();
		var id = $(this).attr("id");
		onLoginClick(id);
		return false;
	});
	
	$("#login_certificate").click(function(e){
		e.preventDefault();
		var id = $(this).attr("id");
		onLoginCertClick(id);
		return false;
	});
	
	init_retrievePassword();
}

function addLoginForm(){
	var loginForm = "<form method=\"post\" name=\"logon\" id=\"logon\"><input name=\"user\" type=\"hidden\" value=\"\">";
			loginForm += "<input name=\"password\" type=\"hidden\" value=\"\">";
			loginForm += "<input name=\"smauthreason\" type=\"hidden\" value=\"0\">";
			loginForm += "<input name=\"TARGET\" type=\"hidden\" value=\"\">";
			loginForm += "<input name=\"error_target\" type=\"hidden\" value=\"\">";
			loginForm += "<input name=\"final_target\" type=\"hidden\" value=\"\">";
			loginForm += "<input name=\"postpreservationdata\" type=\"hidden\" value=\"\">";
			loginForm += "<input name=\"generallogondata\" type=\"hidden\" value = \"\">";
    	loginForm += "</form>";
		
	$("body").append(loginForm);
}

function isLoginError(id){
	var isError = false;
	var errorMessage = "<div class='errors'><ul>";
	
	if(id=="login_standard"){
		var uname = $(".login").find("#uname").val();
		var busid = $(".login").find("#busid").val();
		var password = $(".login").find("#password").val();
		
		if(uname==""){
			isError = true;
			errorMessage += "<li>Please enter your Username</li>";
		}
		
		if(busid==""){
			isError = true;
			errorMessage += "<li>Please enter your Business ID</li>";
		}
		
		if(password==""){
			isError = true;
			errorMessage += "<li>Please enter your Password</li>";
		}
		
		if(isError){
			errorMessage += "</ul></div>";
			displayErrorModal("<p>The following require(s) your attention before proceeding:</p>"+errorMessage, "Login Error");
			return true;	
		} else {
			return false;	
		}
		
	} else if(id=="login_certificate"){
		
	} else {
		return true;	
	}
}

function displayErrorModal(errorMessage, title){
	// Display media in modal window
	ecl_launchModalWindow(unescape(title), "570px", function()
  	{ 
		var modalMessage = errorMessage;
		
		$(".title").addClass("loginTitle");
		
		$("#contentContainer #buttonRow.hidden").show();
		
		$("#contentContainer").width("550px");
		$("#contentContainer p").remove();
		$(modalMessage).insertBefore("#contentContainer #buttonRow.hidden");
		
		setModalHeight();	
  	});
}

function onLoginClick(id){
	if(isLoginError(id)==false){
		var uname = $(".login").find("#uname").val();
		var busid = $(".login").find("#busid").val();
		var password = $(".login").find("#password").val();
		
		setGlobalLoginSuccessTarget();
		
		//this works using the telstra.com authentication domain
		//doLogin(uname, password);
		
		//Live Test
		doLogin(uname+"#"+busid, password);
	}
}

function onLoginCertClick(id){
	setGlobalLoginSuccessTarget();
	doCertLogin();
}

function setGlobalLoginSuccessTarget(){
	setSuccessTarget(teg_login_successTarget);	
}

/* ########################################################################### *
/* ##### CHECK FOR LOGIN ERROR
/* ########################################################################### */

function init_checkForLoginError(){
	if($(".login").length>0){
		var href = window.location.href;
		var errorMessage = "";
		var displayModal = false;
		
		if(href.indexOf("?")!=-1){	
			if(href.indexOf("SMAUTHREASON")!=-1){
				var errorStatus = $.query(href);
				
				if(errorStatus.SMAUTHREASON==0){
					errorMessage = "<div class='errors'>Sorry, the Username, Password or Business ID entered is incorrect.<br/>Please check your login details and try again.</div>";
					displayModal = true;
				} else if(errorStatus.SMAUTHREASON==24){
					errorMessage = "<div class='errors'>Sorry, the Username, Password or Business ID entered is incorrect.<br/><br/>Due to security precautions any account which has had three unsuccessful attempts to login will be locked out for three hours.</div>";
					displayModal = true;
				} else if(errorStatus.SMAUTHREASON==10){
					errorMessage = "<div class='errors'>Sorry, the Digital Certificate you supplied is either invalid or has been revoked. Please check your certificate and try again.</div>";
					displayModal = true;
				} else if(errorStatus.SMAUTHREASON==220){
					errorMessage = "Sorry, the Username or Business ID entered is incorrect.<br/>Please check your login details and try again.";
					displayModal = true;
				} else {
					errorMessage = "Sorry, an unknown error has occurred.";
					displayModal = false;
				}
				
				if(displayModal){
					if(errorStatus.SMAUTHREASON==220){
						displayRetrieveModal(errorMessage, "Retrieve password");
					} else {
						displayErrorModal(errorMessage, "Login Error");
					}
				}
			}
		}
	}
}

/* ########################################################################### *
/* ##### RETRIEVE PASSWORD
/* ########################################################################### */

function init_retrievePassword(){
	$("#btn_retrievePassword").click(function(){
		var retrieveErrorMessage = "";
		
		displayRetrieveModal(retrieveErrorMessage, "Retrieve password");
		
		return false;
	});
}

function displayRetrieveModal(errorMessage, title){
	// Display media in modal window
	ecl_launchModalWindow(unescape(title), "570px", function()
  	{ 
		var modalMessage = createRetrieveForm(errorMessage);
		
		$(".title").addClass("loginTitle");
		
		//$("#contentContainer #buttonRow.hidden").show();
		
		$("#contentContainer").width("550px");
		$("#contentContainer p").remove();
		$(modalMessage).insertBefore("#contentContainer #buttonRow.hidden");
		
		setModalHeight();
		
		var modalContainer = $("#modalContainer");
		setupRetrieveForm(modalContainer);
  	});
}

function createRetrieveForm(errorMessage){
	var retrieveMessage = "";
	var hidden = "";
	
	retrieveMessage += "<form id=\"retrievePassword\" action=\"#\">";
		retrieveMessage += "<fieldset>";
			retrieveMessage += "<p class=\"legend\"><em>*</em> Mandatory fields</p>";
			
			if(errorMessage==""){
				hidden = "hidden";
			}
			
			retrieveMessage += "<div class=\"paddedErrors errors "+hidden+"\">"+errorMessage+"</div>";
			retrieveMessage += "<p>To retrieve your password, please enter your Username and Business ID. If you do not have these available, please contact us on 1800 017 353 between 8:30am and 6pm AEST.</p>";
			retrieveMessage += "<div>";
				retrieveMessage += "<label for=\"retrieveUsername\">Username <em>*</em></label>";
				retrieveMessage += "<input type=\"text\" id=\"retrieveUsername\" name=\"retrieveUsername\" tabindex=\"1\" size=\"45\" maxlength=\"50\"/>";
			retrieveMessage += "</div>";
			retrieveMessage += "<div>";
				retrieveMessage += "<label for=\"retrieveBusinessId\">Business ID <em>*</em></label>";
				retrieveMessage += "<input type=\"text\" id=\"retrieveBusinessId\" name=\"retrieveBusinessId\" tabindex=\"2\" size=\"45\" maxlength=\"50\"/>";
			retrieveMessage += "</div>";
		retrieveMessage += "</fieldset>";
		retrieveMessage += "<div style=\"margin-bottom: 10px;\" class=\"buttonrow clearfix\">";
			retrieveMessage += "<button type=\"submit\" class=\"buttStandard send\">Submit</button>";
		retrieveMessage += "</div>";
	retrieveMessage += "</form>";
	
	return retrieveMessage;
}

function setupRetrieveForm(){
	$("#retrievePassword button.send").click(function(){
		$("#retrievePassword div.errors").addClass("hidden");
		
		$("#retrievePassword input").removeClass("error");
		
		var errorMessage = "<ul>"
		var isError = false;
		
		var uname = $("#retrieveUsername").val();
		if(uname==""){
			isError = true;
			errorMessage += "<li>Please enter your Username</li>";
		}
		
		var busid = $("#retrieveBusinessId").val();
		if(busid==""){
			isError = true;
			errorMessage += "<li>Please enter your Business ID</li>";
		}
		
		errorMessage += "</ul>"
		
		if(isError){
			displayRetrieveErrorMessage(errorMessage);
			return false;
		} else {
			setModalHeight();
			window.location.href = teg_login_retrievePasswordUrl+"?&rne_eventType="+teg_login_rne_eventType+"&rne_username=" + uname + "&rne_businessId=" + busid + "&rne_errorTargetUrl=" + getRetrieveErrorUrl()+"&rne_marketSegment=tcorp";
			return false;
		}
	});
}

function displayRetrieveErrorMessage(errorMessage){
	var errors = $("#modalContainer #retrievePassword div.errors");
	$(errors).removeClass("hidden");
	$(errors).html(errorMessage);
	
	setModalHeight();
}

function setModalHeight(){
	var height = $("#modalContainer").height()-20;
	var borderHeight = ($.browser.msie) ? height : height;
	
	$("#modalContainer .border_l, #modalContainer .border_r").height(borderHeight);	
}

function getRetrieveErrorUrl(){
	var currentHref = window.location.href;
	var newHref = "";
	
	var removeQueryString = currentHref.indexOf("?");
	var removeHash = currentHref.indexOf("#");
	
	if(removeQueryString==-1 && removeHash==-1){
		//dont need to do anything to the currentHref
	} else {
		if(removeHash!=-1){
			currentHref = currentHref.substring(0, removeHash);	
		}

		if(removeQueryString!=-1){
			currentHref = currentHref.substring(0, removeQueryString);	
		}
	}
	
	newHref = currentHref + "?SMAUTHREASON=220";

	return newHref;
}

/* ########################################################################### *
/* ##### FLASH BANNER INTERFACE
/* ########################################################################### */

function FlashBanner_LoadInternalLink(url){
	window.location.href = url;
}

function FlashBanner_LoadExternalLink(url){
	window.open(url);	
}

function FlashBanner_LoadMediaPlayer(url, title, description, moreUrl){
	ecl_launchMedia(url+"&description="+description+"&moreUrl="+moreUrl, title);
}