// JavaScript Document

// Begin on ready events
$(document).ready(function() {
	
	var currentLocation = location.pathname;
	var newLocation = "";
	var contentid = $("#hdn_contentid").attr("value");
	var siteareaid = $("#hdn_siteareaid").attr("value");
	var myTimer = {};
	
	function reloadPublic() 
	{		
		if(currentLocation.indexOf("/public/") > -1)
		{
			newLocation = currentLocation.replace("public","private");
			window.lcoation = newLocation;
		}
	}
	
	
	/////////////////////// Homapage and Landing page display attributes //////////////////////////////
	
	// Set Body class for Homepage and perform show / hide for breadcrumbs and the "online services" dropdown list
	if(currentLocation.indexOf("/home") > -1) {
		if(currentLocation.indexOf("/home/!") > -1 || (currentLocation.indexOf("/home") > -1 && currentLocation.indexOf("/home/") <= -1)) {
			$('body').addClass('home'); 
			$("#breadcrumbs").hide();
			//myTimer = $.timer(100,function(){
				//delayedLoad('body','bkg-homepage.jpg');
			//});	
		} else {
			$("#body").addClass("offsettop2");
			if($.browser.msie && parseInt(jQuery.browser.version) == 6.0){
				$("#right-column").addClass("offsettop2");
				if($("#hdn_contentid").attr("value").toLowerCase().indexOf("individual investors") > -1){
					$("#right-column").addClass("offsettop3");
				}
			}
		}
		$('form.jumpmenu').hide();
	} else if(currentLocation.indexOf("/myhome") > -1){
		$('body').addClass('customer'); 
		$("#breadcrumbs").hide();
		//myTimer = $.timer(100,function(){
				//delayedLoad('body','bkg-secondary-page.jpg');
		//});
	} else if($("#hdn_contentid").attr("value").indexOf("Customers") > -1 || $("#hdn_contentid").attr("value").indexOf("Investors")  > -1 || $("#hdn_contentid").attr("value").indexOf("About QTC")  > -1 || $("#hdn_contentid").attr("value").indexOf("Individual investors")  > -1)
	{
		$('body').addClass('landing'); 
		//myTimer = $.timer(100,function(){
				//delayedLoad('body','bkg-homepage.jpg');
		//});	
		$("#breadbrumbs").show();
	} 
	else if(currentLocation.indexOf("/secure/") > -1) {
		$('body').addClass('customer'); 
		//myTimer = $.timer(100,function(){
				//delayedLoad('body','bkg-secondary-page.jpg');
		//});	
		$("#breadbrumbs").show();
		//$('form.jumpmenu').hide();
	} else {
		$('body').addClass('inner'); 
		$("#breadbrumbs").show();
	}
	
	// Hide Individual Investors
	if(currentLocation.indexOf("/more-tools/individual-investors/!") > -1 ){
		$("body").addClass("landing");
		//myTimer = $.timer(100,function(){
			//delayedLoad('body','bkg-secondary-page.jpg');
		//});	
	}	
	//$("ul.navlist li").each(function(){
		//if($(this).find("a").attr("title").toLowerCase() ==  "individual investors"){
			//$(this).hide();
		//}								
	//});
	//$(".sectionnavlist li a").each(function(){
		//if($(this).attr("title") ==  "Individual Investors"){
			//$(this).hide();
		//}											
	//});
	
	function delayedLoad(strElement, strImage){
		$(strElement).css("background-image", "url(/qtc/themes/html/qtc_default/images/"+ strImage +")");			// This is to load this image at the end		
		$.clearTimer(myTimer);
	}
	
	
	
	// Customize search widget
	if (gup("search_query") != ""){
		$("#txt_searchquery").attr("value", gup("search_query"));
		$("#txt_bannersearchquery").attr("value", gup("search_query"));
	}

	if(currentLocation.indexOf("/public/") <= -1) {
		$("#fm_bannersearch").attr("action", $("#fm_bannersearch").attr("action").replace("public","private"));
	}
	
	if(document.getElementById("ibm_portal_search_widgets_ScopeSearchWidget_0_textBox")){
		document.getElementById("ibm_portal_search_widgets_ScopeSearchWidget_0_textBox").className="query";
		document.getElementById("ibm_portal_search_widgets_ScopeSearchWidget_0_textBox").value="";
		$("input.searchIcon").attr("style","float:left");
		$("#dijit_SearchDropDownButton_0").hide();
	}

	
	/////////////////////////// Public to Private link handling ////////////////////////
	
	// Replace Public links to private in the theme as required
	if (currentLocation.indexOf("/public/") > -1){
		$("a.homelink").attr("href","/qtc/public/web/home");
		$("a.contactlink").attr("href","/qtc/public/web/aboutqtc/contact/");
	} else if (currentLocation.indexOf("/private/") > -1){
		$("a.homelink").attr("href","/qtc/private/web/home");
		$("a.signinlink").parent().hide();
		$("a.contactlink").attr("href","/qtc/private/web/aboutqtc/contact/");
		if(currentLocation.indexOf("/secure/") > -1) {
			$("a.contactlink").attr("href","/qtc/private/secure/resources/contact/");
		}
	}		
		
	//Footer Navigation context
	$("#footernav li.footerlink a").each( function() {			
		if(currentLocation.indexOf("/public/") <= -1) {
			$(this).attr("href", $(this).attr("href").replace("public","private"));
		} else {
			$(this).attr("href", $(this).attr("href").replace("private","public"));
		}
	});	




	/////////////////////////// Content Styles ////////////////////////

	// Assigning table styles
	$("div.text-images table").each(function(){
		$(this).addClass("tblqtc");								   
	});
	

	// Hide preview div
	$("div.inner").each( function(){
		if ($(this).find("div.preview").html() == ""){
			$(this).find("div.preview").hide();
		}
	});



	//////////////// Navigation Adjustments /////////////////////
	
	// Set the Level 2 Navigation's WCM path
	if(currentLocation.indexOf("/aboutqtc/") > -1) {
		
		$("#subnavlist li a").each(function(){
			switch($(this).attr("title")){
				case "Corporate Overview":		
				$(this).attr("href","/qtc/poc/?urile=wcm:path:/Content/QTC+Website/About+Us/Corporate+Overview");
				break;
				
				case "Policies":		
				$(this).attr("href","/qtc/poc/?urile=wcm:path:/Content/QTC+Website/About+Us/Policies"); 
				break;
				
				case "News":		
				$(this).attr("href","/qtc/poc/?urile=wcm:path:/Content/QTC+Website/About+Us/News");
				break;
				
				case "Careers":		
				$(this).attr("href","/qtc/poc/?urile=wcm:path:/Content/QTC+Website/About+Us/Careers");
				break;
				
				case "Contact Us":		

				$(this).attr("href","/qtc/poc/?urile=wcm:path:/Content/QTC+Website/About+Us/Contact+Us");
				break;
			} 
		});
		
	} else if(currentLocation.indexOf("/investors/") > -1) { 
		$("#subnavlist li a").each(function(){
			switch($(this).attr("title")){
				case "Credit Rating":		
				$(this).attr("href","/qtc/poc/?urile=wcm:path:/Content/QTC+Website/Investors/Credit+Rating");
				break;
				
				case "Funding":		
				$(this).attr("href","/qtc/poc/?urile=wcm:path:/Content/QTC+Website/Investors/Funding");
				break;
				
				case "Reports and Publications":		
				$(this).attr("href","/qtc/poc/?urile=wcm:path:/Content/QTC+Website/Investors/Reports+and+Publications");
				break;
			}
		});
	
		$("#subnavlist li a").each(function(){
			switch($(this).attr("title")){
				case "Borrowing":		
				$(this).attr("href","/qtc/mypoc/?urile=wcm:path:/Content/QTC+Customer+Website/Products+and+Services/Borrowing");
				break;
				
				case "Investing":		
				$(this).attr("href","/qtc/mypoc/?urile=wcm:path:/Content/QTC+Customer+Website/Products+and+Services/Investing");
				break;

				case "Advisory":		
				$(this).attr("href","/qtc/mypoc/?urile=wcm:path:/Content/QTC+Customer+Website/Products+and+Services/Advisory");
				break;
				
				case "Risk Management":		
				$(this).attr("href","/qtc/mypoc/?urile=wcm:path:/Content/QTC+Customer+Website/Products+and+Services/Risk Management");
				break;
				
				case "Training":		
				$(this).attr("href","/qtc/mypoc/?urile=wcm:path:/Content/QTC+Customer+Website/Products+and+Services/Training");
				break;
			}
		});
	}
	
	// Maintain highlighting of tertiary navigation items
	function tertiarynavselection(){
		$("#tertiary-nav ul.sectionnavlist li").each(function(){
			if($(this).find("a").html() == siteareaid){
				$(this).addClass("active");
			}		
		});
	}


	// Navigation highlight when in level 2
	var navlist;
	var navlistitem;
	for (i=0; i<document.getElementsByTagName("ul").length; i++){
		if(document.getElementsByTagName("ul")[i].className == "navlist"){
			navlist = document.getElementsByTagName("ul")[i];
			for(var j=0; j<navlist.getElementsByTagName("li").length; j++){
				if(navlist.getElementsByTagName("li")[j].getAttribute('class') != null && navlist.getElementsByTagName("li")[j].getAttribute('class') != 'first-child'){
					navlist.getElementsByTagName("li")[j].setAttribute('class','active');
					if($.browser.msie && parseInt(jQuery.browser.version) == 6.0){
						alert(navlist.getElementsByTagName("li")[j].getAttribute('class'));
					}
				}
				//alert(navlist.getElementsByTagName("li")[j].getAttribute('class'));
				if(currentLocation.indexOf("/secure/") < 0) {
					if (j >= 4 && navlist.getElementsByTagName("li")[j].getAttribute('class') != null && navlist.getElementsByTagName("li")[j].getAttribute('class') != 'first-child'){
						navlist.getElementsByTagName("li")[3].setAttribute('class','active');
					}
				}
			}
		}
	}




	//////////////// Product Pages ////////////////////////////	
		
	// Handle links from public customer area to the individual product pages
	if(currentLocation.indexOf("/customers/borrowing/!ut") > -1 || currentLocation.indexOf("/customers/investing/!ut") > -1 || currentLocation.indexOf("/customers/advisory/!ut") > -1 ||  currentLocation.indexOf("/customers/risk-management/!ut") > -1 ||  currentLocation.indexOf("/customers/training/!ut") > -1) { 
		$(".text-images a").each(function(){
			$(this).addClass("privatelink");
		});
		$("ul.document-links").hide();
	}

	$("a.privatelink").each(function(){
		var basepath = "/qtc/mypoc/?urile=wcm:path:/Content/QTC+Customer+Website/";
		if(currentLocation.indexOf("borrowing") > -1){
			$(this).attr("href", basepath+"Products+and+Services/Borrowing/"+$(this).attr("title"));
		}
		else if (currentLocation.indexOf("investing") > -1){
			$(this).attr("href", basepath+"Products+and+Services/Investing/"+$(this).attr("title"));
		}
		else if (currentLocation.indexOf("advisory") > -1){
			$(this).attr("href", basepath+"Products+and+Services/Advisory/"+$(this).attr("title"));
		}
		else if (currentLocation.indexOf("risk-management") > -1){
			$(this).attr("href", basepath+"Products+and+Services/Risk+management/"+$(this).attr("title"));
		}	
		else if (currentLocation.indexOf("training") > -1){
			$(this).attr("href", basepath+"Products+and+Services/Training/"+$(this).attr("title"));
		}	
	});

	

	////////////////////// Landing Pages ///////////////////////////

	// Hide panel partition if less than 2 links exist
	$(".feature-links").each(function(){
		if($(this).find("li.left > a").attr("href") != undefined){
			$(this).find("li.centre").hide();
		}
	});

	$("ul.document-links").each(function(){
		if($(this).find("li > a").attr("href") == ""){
			$(this).find("li > a").hide();
		} else { 
			$(this).find("li > a").show();
		}
	});



	// Provide top margin for standalone portlets
	$('.portletwrapper').each( function(){
		if(currentLocation.indexOf("/myhome") > -1 || currentLocation.indexOf("/myaccount") > -1 || currentLocation.indexOf("/myaccount/overview") > -1) {  
			if($(this).find("div.complementary").attr("class") != undefined){
				$(this).addClass('offsetleft'); 	
				$("#breadbrumbs").show();
			}
		}	
	});	
	
	

	// Customize Breadcrumbs display
	$("#breadcrumbs li.first-child").each( function(){
		if(currentLocation.indexOf("/myaccount") > -1){			
			$(this).find("a").html("My Account");
		}
	});

	// Four Column display on landing pages
	$(".four-column").each(function(idx) {
		if(	idx == 3){
			$(this).addClass("last");
		}							
	});

	$(".four-column").equalHeights();    
		$(".service-listing").each( function(){
		if($(this).find("h3").html() == ""){
			$(this).hide();
		}
	});
	$(".service-listing").equalHeights();
	

	$("input.button").each(function(){
		var newclass = $(this).attr("class");									
		$(this).wrap('<span class="'+newclass+'"><span class="btn-image"></span></span>');
		$(this).attr("value","");
	});

	// Add first-child and last-child classes for ie6+ie7
	$("li:first-child").addClass("first-child");
	$("#footer ul li:first-child").addClass("first-child");
	$(".document-links li:first-child").addClass("first-child");
	$(".tab_area.ntab .tabs li:first-child").addClass("first-child");



		
	//Font Resize
	$('#page-tools .font-increase').click(function(){
		 $("body").css("font-size","90%");
		return false;
	});

	$('#page-tools .font-decrease').click(function(){
		 $("body").css("font-size","80%");
		return false;
	});
	
	
	
	//Print //
	
	$(".print-page").click(function() {
		var popurl;
		if (location.href.indexOf("?") != -1) {
			popurl = location.href+"&print=true";
		} else {
			popurl = location.href+"?print=true";		
		}
		window.open(popurl,"Print","toolbar=0,scrollbars=1,menubar=0,location=1,resize=yes,status=1,links=0,width=630,height=560,left=0,top=0");
		return false;
	});


	if (location.href.indexOf("print=true") > -1) {
		$("head").append('<link rel="stylesheet" type="text/css" href="/qtc/themes/html/qtc_default/styles/print.css">');
		$("#header").append('<div style="position: absolute; top:55px; left:80%; width: 100px;"><input type="button" id="btn_print" value="Print" class="button" onClick="window.print();"/> <input type="button" id="btn_close" value="Close" class="button" onClick="self.close();"/></div>');
		
		$("a").each(function() {
			$(this).attr("href","#");
		}); 
		
		$(".site-tools").hide();
		$("#primarynav").hide();
		$("#left-column").hide();
		$("#wptheme-pageAreaToolbar").hide();
		$("#page-tools").hide();
		$("#right-column").hide();
		$(".complementary").hide();
		$("#footer").hide();
		
		// Resize all iframes
		$("iframe").each( function(){
			$(this).attr("style","width:550px");
		});
				
		//print dialog box
		$("a").attr("href","#");
		$("body").append('<script type="text/javascript">print();</script>');
	}


	
	//////////////////////// Feedback //////////////////////

	// Feedback Categories
		$("a").each(function () {
			if($(this).attr("class") == "ask-question"){
				$(this).attr("href", $(this).attr("href") +"?enquiry="+ $("#hdn_cats").attr("value"));	
			}
		});
		
		var feedbackCats;
		if(document.getElementById("feedbackCategory")){
			feedbackCats = document.getElementById("feedbackCategory");	
			var enquiry = document.getElementById("enquiry").value;
			for (var i=0; i < feedbackCats.length ; i++){
				if(enquiry == "") enquiry = gup("enquiry").replace("+"," ");
				if(enquiry.indexOf(feedbackCats.options[i].value) > -1){
						feedbackCats.options[i].selected = true;
					break;
				}
			}
		}
		
		
    
	
	//////////////////////// Content Tabs ///////////////////////
	
	// tabs
		if($("ul.tabs > li") && currentLocation.indexOf("/rates/") == -1){
				$("ul.tabs > li").each(function () {
					if($(this).find("a.tab span").html().toLowerCase() == "none"){
						$(this).hide();
					}
				});
		}
				
		$("a.tab").click(function () {
        	
		     // switch all tabs off
		     $(".active").removeClass("active");
        			
		     // switch this tab on
		     $(this).addClass("active");
        			
		     // slide all content up
		     $(".content").hide();
        			
		     // slide this content up
		     var content_show = $(this).attr("rel");
			 $("#"+content_show).show();
			 
			 tertiarynavselection();
		});


		// Panel Getting Started click handling
		
		$("li.email a.poster").click( function(){
			if(currentLocation.indexOf("/public/") > -1 || currentLocation.indexOf("/investors/") > -1){
				$(this).attr("href","/qtc/public/web/aboutqtc/contact?enquiry=Customers");
			} else {
				$(this).attr("href","/qtc/private/secure/resources/contact?enquiry=Customers");
			}
		});


		//Tree View //   
		$("#qtctree").treeview();


		//Economic Updates Listing on Eco Updates pages
		$("ul.update-link").each( function() {
			$(this).hide();
			return false;
		});
		
		
	// Handle Summary links in generic file resource listings
	$("ul.list-link").each( function() {
		if( $(this).find("input.hdn_summary").val() == "" || $(this).find("input.hdn_summary").val() == "<p></p>" || $(this).find("input.hdn_summary").val() == "<p><!-- --></p>") {
			$(this).find("li.no-image").hide();
			$(this).find("li").addClass("no-line");
		}
	});
	
	
	// Feedback form category lists
	function resetFeedbackForm(){
		$("#enquiry_products").hide();
		$("#enquiry_general").hide();
	}	
	switch(gup("enmode")){
		case "products":
			resetFeedbackForm();
			$("#enquiry_products").show();
			break;
	
		default:
			resetFeedbackForm();
			$("#enquiry_general").show();		
	} 
	
	// Handle enquiry form post submission
	if(gup("enquiry") == "success"){
		$("#commentForm").hide();
		$("#commentNotice").show();
	}



	// Statements - Append Organization name for default view
	var paramOrg;
	var iframeSrc;
	$("span.noshow").each( function() {
		if($(this).find("a").attr("class") == "statements"){
			paramOrg = $("#PortalOrgName").attr("value");
			iframeSrc = $(this).find("iframe").attr("src");
			if(iframeSrc.indexOf("org") == -1){
				iframeSrc += "&org="+paramOrg;	
				$(this).find("iframe").attr("src",iframeSrc);
			}	
		}
	});
	
	
	// Hide the Customer Profile Iframe if the logged in user is not a valid customer
	if($("#PortalCFTeam").attr("value") == ""){
		$("iframe").each( function() {  
			if($(this).attr("src") == "/ecv/external_customer_profile.html"){
				$(this).hide();
			}
		});
	}
	
	
	$("iframe").each( function() {  
		if($(this).attr("src") == ""){
			$(this).attr("src","javascript:false;");
			$(this).hide();	
		}
		if($(this).attr("src") == "/pkmspasswd"){
			$(this).removeClass("autoHeight");
			$(this).attr("height","400");
		}
		if($(this).attr("src").indexOf("OLSA") > -1 && currentLocation.indexOf("/statements") > -1){
			$(this).removeClass("autoHeight");
			//$(this).attr("height","1050");
		}
	});

	removeDuplicates();
	
	// Fixing multiple IFrame rendering issue
	function removeDuplicates(){
		$('[id]').each(function(){
	  	var ids = $('[id='+this.id+']');
	  	if(ids.length>1 && ids[0]==this)
			$("#"+this.id).hide();
		});
	}

	
	// Removing sectitle headings if where it needs to be hidden
	$("h2.sectitle").each( function() {
		if($(this).text().toLowerCase().indexOf("iframe_") > -1){
			$(this).hide();	
		}
	});


	// designated Inestments
	$("#desigForm").validationEngine();
	$("#commentForm").validationEngine();
	


	// Customize Search Results
	$("#fm_search_results a").each( function(){
		//alert($(this).attr("href"));
		if($(this).attr("href").toLowerCase().indexOf("qtc%20website") > -1){
			$(this).attr("href", $(this).attr("href").replace("mypoc","poc"));			
		}
	});


	//Home page Slider //  
	(function($) {
		$.fn.slide = function(options) {
			var defaults = {
				slideWidth: 728,
				autoplay: true,
				duration: 10000,
				showNavigator: true,
				showSlideIndex: true
			};
			var options = $.extend(defaults, options);
			return this.each(function() {
				var slideshow = $(this);
				var o = options;
				var currentPosition = 0;
				var slides = $('.slide');
				var numberOfSlides = slides.length;
				var t;
	
				// Remove scrollbar in JS
				$('#slidesContainer').css('overflow', 'hidden');
	
				// Wrap all .slides with #slideInner div
				slides.wrapAll('<div id="slideInner"></div>')
	
				// Float left to display horizontally, readjust .slides width
				.css({
					'float': 'left',
					'width': o.slideWidth
				});
	
				// Insert a clone of first slide 
				$('.slide:first').clone().appendTo('#slideInner');
	
				// Set #slideInner width equal to total width of all slides
				$('#slideInner').css('width', o.slideWidth * (numberOfSlides + 1));
	
				// Insert controls in the DOM
				if (o.showNavigator) {
					slideshow
						//.prepend('<span class="control" id="leftControl">Clicking moves left</span>')
						//.append('<span class="control" id="rightControl">Clicking moves right</span>');
	
					// Create event listeners for .controls clicks
					//$('#leftControl').click(function() { prev(); return false; });
					//$('#rightControl').click(function() { next(); return false; });
				}
				// Insert slides index
				if (o.showSlideIndex == true) {
					slideshow.append('<div id="slideIndex"></div>');
					for (var i = 1; i <= numberOfSlides; i++) {
						$('#slideIndex').append('<span id="slide-' + i + '" class="numbers">' + i + '</span>');
					}
					$('.numbers').click(function() { goto(($(this).attr('id')).replace('slide-', '') - 1, false); return false; });
				}
	
				// Start
				init();
	
				//Init function
				function init() {
					manageControls(currentPosition);
					if (o.autoplay == true) setNextTimeOut(o.duration);
				}
	
				// Next
				function next() {
					currentPosition++;
					if (currentPosition >= numberOfSlides) currentPosition = 0;
					slideTo(currentPosition, true);
				}
	
				// Previous
				function prev() {
					currentPosition--;
					if (currentPosition < 0) currentPosition = numberOfSlides - 1;
					slideTo(currentPosition, false);
				}
	
				// Go to a slide 
				function goto(position) {
					currentPosition = position;
					slideTo(currentPosition, false);
				}
	
				// Set time out for next slide
				function setNextTimeOut() {
					t = setTimeout(function() { next(); }, o.duration);
				}
	
				function clearNextTimeOut()
				{ 
					clearTimeout(t);
				}
				// Slide
				function slideTo(position, continuously) {
					$('#slideInner').stop();
					clearNextTimeOut();
					// usual cases
					if (continuously == false || o.autoplay == false || position != 0) {
						$('#slideInner').animate({ 'marginLeft': o.slideWidth * (-position) }, '', '',
							function() {
								manageControls(position);
								if (o.autoplay == true) setNextTimeOut();
							}
						)
					}
					// autoplay: slide from last to first one continuously
					else {
						// slide to the 'fake' first slide (actually at the last)
						$('#slideInner').animate({ 'marginLeft': o.slideWidth * (-numberOfSlides) }, '', '',
							function() {
								//immediately change to the 'true' first slide
								$('#slideInner').css('marginLeft', 0);
								manageControls(position)
								if (o.autoplay == true) setNextTimeOut();
							}
						)
					}
				}
	
				// manageControls: Hides and Shows controls depending on currentPosition
				function manageControls(position) {
					if (o.showNavigator) {
						// Hide left arrow if position is first slide
						if (position == 0) { $('#leftControl').hide() } else { $('#leftControl').show() };
						// Hide right arrow if position is last slide
						if (position == (numberOfSlides - 1)) { $('#rightControl').hide() } else { $('#rightControl').show() };
					}
	
					// Hilight the current page
					if (o.showSlideIndex == true) {
						// remove active class from all pages
						$('.numbers').removeClass("active");
						// add only to the current page
						$('#slide-' + (position + 1)).addClass("active");
					}
				}
			});
		};
	})(jQuery);

});



