// JavaScript Document

// dependencies
//	- utilities.js (part of UOS JS files) contains cookie related functions referenced here

		var storedCountry = readCookie("rbttCountry"); // get cookie value of stored country
		var currentDomain = location.host; // get current domain (so this works across test domains as well)
		var domainHomepage = "233100";
		
		var urlPath = document.location.pathname.toLowerCase(); // grab the URL
		var urlPathArray = urlPath.split('/'); // split URL into an array
		var urlCountryCode = urlPathArray[1];
		var newCookieValue;
		var countryMatch = false;
		var countryList=new Array();
			countryList[0]="ar"; 	// Aruba
			countryList[1]="bb";	// Barbados
			countryList[2]="an";	// Curacoa and Bonaire
			countryList[3]="jm";	// Jamaica
			countryList[4]="sxm";	// St. Martaan and Saba
			countryList[5]="sr";	// Suriname
			countryList[6]="tt";	// Trinidad and Tobago
			countryList[7]="ec";	// Eastern Caribbean
		
		for (var i in countryList) {
			if (urlCountryCode == countryList[i]) {
				countryMatch = true;
				break;
			}
		}

// ==============================================================================================
//
//  Document Ready
//
// ==============================================================================================

	$(document).ready(function() {
 
		cookieDetectSetRedirect();
		
		// Changing RBC in the Caribbean pages to the dual RBC shield and RBTT Logo
		if (document.location.toString().indexOf('about') != -1) { 
			$('#globalheader-logo > a > img').attr('src','/file-575391.jpg'); 
		}

	});

// ==============================================================================================
//
//  jQuery function to retrieve query string value
//
// ==============================================================================================

	$.urlParam = function(name){
		var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
		if (!results) { return 0; }
		return results[1] || 0;
	}	

// ==============================================================================================
//
//  Clears rbttCountry Cookie base on query string match
//		- for testing
//
// ==============================================================================================

	// if cookie=clear query string is present, clear the rbttCountry cookie
	if ($.urlParam('cookie') == 'clear') {
		//devConsole('got cleared: ' + $.urlParam('cookie'));
		createCookie("rbttCountry", "", 0);
		storedCountry = "";
	}
	
// ==============================================================================================
//
//  Browser Console / Log Function - So error is not thrown if not console not present
//
// ==============================================================================================

	function devConsole(msg) {
		if (typeof(console) !== 'undefined' && console != null) {
			console.log(msg);
		}	
	}

// ==============================================================================================
//
//  Create / Redefine Cookie on Page Visit
// 		- Country specific pages set the rbttCountry cookie based on the current country.
//			-> cookie does not exist - set cookie based on country code in URL
//			-> cookie exists - re-set the cookie (extend the exp date)		
// 		- Country independant pages (About RBTT / Privacy & Security / etc..) with no Cookie set
//			-> cookie does not exits:
//				-> hide header links and search field if no cookie present
//				-> hide sub-footer and footer search section if no cookie present
//				-> modify sub-header links (prod and serv, cust serv) to root (country selector)
//				-> right nav items?
//			-> cookie exists:
//				-> modify header links and search field to include country info
//				-> modify sub-header links to include country info
//				-> modify sub-footer links and search field to include country info
//				-> right nav items?
//
// ==============================================================================================

	function cookieDetectSetRedirect() {
	
		// if cookie is null or empty or undefined
		if ((storedCountry == null) || (storedCountry == "") || (storedCountry == 'undefined')) {
			//devConsole("no cookie has been set: " + storedCountry);
			
			//devConsole("Country Match: " + countryMatch);
		
			if (countryMatch) {
				// we are on a country specific page - set cookie to url's country code
				//devConsole("we are on a country specific page with no cookie set - set cookie to url's country code: " + urlCountryCode);

				newCookieValue = urlCountryCode;

				enableCountrySelector(newCookieValue);	// set flag and country on country selector in header
				
				countryDependantModify(newCookieValue); // is this needed here? Only used on About RBTT pages and other non-country specific pages
				
				//devConsole("All we had to do was alter country selector and write new cookie?");
				
			} else {
				// non country specific page with no cookie set
				//devConsole("non country specific page with no cookie set - hide contry dependant items");
				
				newCookieValue = "";
				
				countryDependantHide();
			}
	
		} else {
			
			//devConsole("yes cookie set: " + storedCountry);
			
			var countryVal = storedCountry.split("_");	// cookie is either ('cc') or ('cc_##') format
			
			if ( countryMatch ) {
				// Country specific page
				//devConsole("We are on a country specific page with existing cookie");
				
				if (countryVal[0] == urlCountryCode) {
					newCookieValue = storedCountry;		// as long as countries match, retains _## if already exists in cookie
				} else {
					newCookieValue = urlCountryCode;	// in case cookie differs from current country, value of country code alias in url is used
				}
				
				enableCountrySelector(newCookieValue);	// set flag and country on country selector in header
				
				countryDependantModify(newCookieValue);	// modify country dependant links, etc...
				
			} else {
				// Country independant page
				//devConsole("We are on a country independant page with existing cookie");
				
				if ((typeof(CMS_PageId) != 'undefined') && (CMS_PageId == domainHomepage)) {
					// RBTT.com Landing Page with Country Selector - Redirect user to their previously selected country
					window.location = "http://" + currentDomain + "/" + countryVal[0] + "/personal/";

				} else {
					// All other country independant pages
					
					newCookieValue = storedCountry;
					
					enableCountrySelector(newCookieValue); 	// set flag and country on country selector in header	
					
					countryDependantModify(newCookieValue);	// modify country dependant links, etc...
				}
			}
		}

		//devConsole("Create / Re-Write Cookie: " + newCookieValue);

		createCookie("rbttCountry", newCookieValue, 365);			
	}

// ==============================================================================================
//
//  Set Country Cookie and Redirect
//
// ==============================================================================================

	function setCountry(id) {
	
		var cookieVal;
	
		// ensure id has a value - on rbtt landing page default selection
		// has no value so we do not want users to proceed
		if (id != "") {
			
			//devConsole("Create cookie with this id: " + id);
			
			// set cookie to new country value
			createCookie("rbttCountry", id, 365);
		
			// split cookie value into an array
			cookieVal = id.split("_");
			
			// bring user to selected country's homepage
			window.location = "http://" + currentDomain + "/" + cookieVal[0] + "/personal/";
			
		}
	}

// ==============================================================================================
//
//  About RBTT and Country Independant Pages - Hide Country Dependant Sections and Modify Links
//
// ==============================================================================================

	function countryDependantHide() {
	
		//devConsole("Hide Country Dependant Items");

		if ($('#globalheader-links').length) {
			$('#globalheader-links').remove();	// hide header items 
			$('#globalheader-search').remove();	// hide header items 
		}
		
		if ($('#globalfooter-relatedlinks').length) {
			$('#globalfooter-relatedlinks').remove();	// hide footer - Related Links  
		}
		if ($('#globalfooter-searchbar').length) {
			$('#globalfooter-searchbar').remove();
		}

		if ($('#mainnav').length) {
			// set sub header links to point to root (rbtt.com)
			$('#prodserv').attr('href', '/');
			$('#custserv').attr('href', '/');
		}
		
		if ($('#custServRightNav').length) {
			$('#custServNumberItem').remove();
			$('#findABranchLink').attr('href','/');
			$('#findABranchLink span').html('Please select a country');
		}
	}

// ==============================================================================================
//
//  About RBTT and Country Independant Pages - Modify Country Dependant Links
//
// ==============================================================================================

	function countryDependantModify(country) {
	
		//devConsole("Modify Country Dependant items: " + country);
		
		var countryVal = country.split("_");	// country is based on cookie which is either ('cc') or ('cc_##') format
	
		if ($('#mainnav').length) { // if subheader nav exists
			// these ids below are only on the About RBTT Header
			$('#prodserv').attr('href', 'http://' + currentDomain + '/' + countryVal[0] + '/personal/');
			$('#custserv').attr('href', 'http://' + currentDomain + '/' + countryVal[0] + '/customerservice/');
		}
		//	#signInLink
		//	#divider3
		//	#siteMapLinkHead
		//	#siteMapLinkFooter
		//	#searchCollectionHeader
		//	#searchCollectionFooter
		//	#findABranchLink
		// 	#custServRightNav
		// 	#custServNumber
		// 	#custServNumberItem
		
		switch (countryVal[0]) {
			case "ec":		// All EC
				$('#signInLink').hide();	// no online banking link for EC countries
				$('#divider3').hide();		// also hide divider so it is not trailing
				$('#siteMapLinkHead').attr('href','http://' + currentDomain + '/ec/sitemap/');
				$('#siteMapLinkFooter').attr('href','http://' + currentDomain + '/ec/sitemap/');
				$('#custServNumberItem').remove();
				$('#searchCollectionHeader').attr('value','ec_collection');
				$('#searchCollectionFooter').attr('value','ec_collection');
				$('#findABranchLink').attr('href','http://' + currentDomain + '/ec/customerservice/cid-232458.html');
				break;
			case "ar":		// Aruba
				$('#signInLink').attr('href','https://aw.rbttnetbank.com');	
				$('#siteMapLinkHead').attr('href','http://' + currentDomain + '/ar/sitemap/');
				$('#siteMapLinkFooter').attr('href','http://' + currentDomain + '/ar/sitemap/');
				$('#custServNumber').html('Call 297-588-0101');
				$('#searchCollectionHeader').attr('value','ar_collection');
				$('#searchCollectionFooter').attr('value','ar_collection');
				$('#findABranchLink').attr('href','http://' + currentDomain + '/ar/customerservice/cid-231879.html');
				break;
			case "bb":		// Barbados
				$('#signInLink').hide();	// no online banking link for Barbados
				$('#divider3').hide();		// also hide divider so it is not trailing
				$('#siteMapLinkHead').attr('href','http://' + currentDomain + '/bb/sitemap/');
				$('#siteMapLinkFooter').attr('href','http://' + currentDomain + '/bb/sitemap/');
				$('#custServNumber').html('Call 246-431-2500');
				$('#searchCollectionHeader').attr('value','bb_collection');
				$('#searchCollectionFooter').attr('value','bb_collection');
				$('#findABranchLink').attr('href','http://' + currentDomain + '/bb/customerservice/cid-233442.html');
				break;
			case "an":		// Curacao and Bonaire
				$('#signInLink').attr('href','https://an.rbttnetbank.com');	
				$('#siteMapLinkHead').attr('href','http://' + currentDomain + '/an/sitemap/');
				$('#siteMapLinkFooter').attr('href','http://' + currentDomain + '/an/sitemap/');
				$('#custServNumber').html('Call 011-5999-763-8000');
				$('#searchCollectionHeader').attr('value','an_collection');
				$('#searchCollectionFooter').attr('value','an_collection');
				$('#findABranchLink').attr('href','http://' + currentDomain + '/an/customerservice/cid-236259.html');
				break;
			case "jm":		// Jamaica
				$('#signInLink').attr('href','https://jm.rbttnetbank.com');
				$('#siteMapLinkHead').attr('href','http://' + currentDomain + '/jm/sitemap/')
				$('#siteMapLinkFooter').attr('href','http://' + currentDomain + '/jm/sitemap/');;
				$('#custServNumber').html('Call 876-960-2340');
				$('#searchCollectionHeader').attr('value','jm_collection');
				$('#searchCollectionFooter').attr('value','jm_collection');
				$('#findABranchLink').attr('href','http://' + currentDomain + '/jm/customerservice/cid-234024.html');
				replaceContent();
				break;						
			case "sxm":		// St Maarten and Saba
				$('#signInLink').attr('href','https://an.rbttnetbank.com');		
				$('#siteMapLinkHead').attr('href','http://' + currentDomain + '/sxm/sitemap/');
				$('#siteMapLinkFooter').attr('href','http://' + currentDomain + '/sxm/sitemap/');
				$('#custServNumber').html('Call 011-599-542-5908');
				$('#searchCollectionHeader').attr('value','sxm_collection');
				$('#searchCollectionFooter').attr('value','sxm_collection');
				$('#findABranchLink').attr('href','http://' + currentDomain + '/sxm/customerservice/cid-234184.html');
				break;
			case "sr":		// Suriname
				$('#signInLink').attr('href','https://sr.rbttnetbank.com');		// same as Jamaica's ?
				$('#siteMapLinkHead').attr('href','http://' + currentDomain + '/sr/sitemap/');
				$('#siteMapLinkFooter').attr('href','http://' + currentDomain + '/sr/sitemap/');
				$('#custServNumber').html('Call 011-597-471555');
				$('#searchCollectionHeader').attr('value','sr_collection');
				$('#searchCollectionFooter').attr('value','sr_collection');
				$('#findABranchLink').attr('href','http://' + currentDomain + '/sr/customerservice/cid-232379.html');
				replaceContent();
				break;
			case "tt":		// Trinidad and Tabago
				$('#signInLink').attr('href','https://tt.rbttnetbank.com');		
				$('#siteMapLinkHead').attr('href','http://' + currentDomain + '/tt/sitemap/');
				$('#siteMapLinkFooter').attr('href','http://' + currentDomain + '/tt/sitemap/');
				$('#custServNumber').html('Call 868-625-7288');
				$('#searchCollectionHeader').attr('value','tt_collection');
				$('#searchCollectionFooter').attr('value','tt_collection');
				$('#findABranchLink').attr('href','http://' + currentDomain + '/tt/customerservice/cid-230657.html');
				// Replace the logo and content for rebranded specific pages
				replaceContent();
				break;
			default :		// No Match - Remove dependant items
				countryDependantHide()	;	
				break;
		}		
	}

// ==============================================================================================
//
//  Header - Country Selector - Set Event Listeners / Set Country
//
// ==============================================================================================

	function enableCountrySelector(country) {
	
		// Header - Country Selector Specific - check if the country selector exists
		if ($('#header_country_selector').length) { 
		
			//devConsole("Enable Country Selector in Header: " + country);
	
			// change the flag icon to match the current country
			modifyCountrySelector(country);
			
			// set an event listener for a click to expand the country list
			$(".magicoverlay-trigger-expand").click(function(){
				$(this).parent().addClass("active");
			});
			
			// set an event listener for a click to collapse the country list
			$(".magicoverlay-trigger-collapse").click(function(){
				$(this).parent().removeClass("active");
			});
			
			// set an event listener for a click on one the countries listed,
			// on click set the cookie and redirect user to selected country
			$('#country_list li').click( function(){
				setCountry($(this).attr('id'));
			});					
		} 
	}

// ==============================================================================================
//
//  Header - Country Selector - Modify List, Flag Icon, Currently Selected
//
// ==============================================================================================

	function modifyCountrySelector(country) {
		
		//devConsole("set flag, alt, and text of current country in country selector");
		
		// remove the current country from the list of countries
		$('#' + country).remove();
		//devConsole("How can we remove item from list if _## is not there?");
		
		// set alt and src attributes of the flag img tag, and value of the span tags
		switch (country) {
			case "ec_1":	// Antigua
				$('#country_flag').attr("src", "/file-499440.jpg");
				$('#country_flag').attr("alt", "Eastern Caribbean");
				$(".magicoverlay-trigger-expand span").text("Antigua");
				$(".magicoverlay-trigger-collapse span").text("Antigua");					
				break;
			case "ar":		// Aruba
			case "ar_2":
				$('#country_flag').attr("src", "/file-499436.jpg");
				$('#country_flag').attr("alt", "Aruba Flag");
				$(".magicoverlay-trigger-expand span").text("Aruba");
				$(".magicoverlay-trigger-collapse span").text("Aruba");					
				break;
			case "bb":		// Barbados
			case "bb_3":
				$('#country_flag').attr("src", "/file-499437.jpg");
				$('#country_flag').attr("alt", "Barbados Flag");
				$(".magicoverlay-trigger-expand span").text("Barbados");
				$(".magicoverlay-trigger-collapse span").text("Barbados");					
				break;
			case "an":		// Curacao and Bonaire
			case "an_4":
				$('#country_flag').attr("src", "/file-499439.jpg");
				$('#country_flag').attr("alt", "Curacao Flag");
				$(".magicoverlay-trigger-expand span").text("Curacao & Bonaire");
				$(".magicoverlay-trigger-collapse span").text("Curacao & Bonaire");					
				break;
			case "ec_5":	// Grenada
				$('#country_flag').attr("src", "/file-499440.jpg");
				$('#country_flag').attr("alt", "Eastern Caribbean");
				$(".magicoverlay-trigger-expand span").text("Grenada");
				$(".magicoverlay-trigger-collapse span").text("Grenada");						
				break;
			case "jm":		// Jamaica
			case "jm_6":			
				$('#country_flag').attr("src", "/file-499442.jpg");
				$('#country_flag').attr("alt", "Jamaica Flag");
				$(".magicoverlay-trigger-expand span").text("Jamaica");
				$(".magicoverlay-trigger-collapse span").text("Jamaica");
				break;						
			case "ec_7":	// St Kitts and Nevis
				$('#country_flag').attr("src", "/file-499440.jpg");
				$('#country_flag').attr("alt", "Eastern Caribbean");
				$(".magicoverlay-trigger-expand span").text("St Kitts & Nevis");
				$(".magicoverlay-trigger-collapse span").text("St Kitts & Nevis");						
				break;
			case "ec_8":	// St Lucia
				$('#country_flag').attr("src", "/file-499440.jpg");
				$('#country_flag').attr("alt", "Eastern Caribbean");
				$(".magicoverlay-trigger-expand span").text("St Lucia");
				$(".magicoverlay-trigger-collapse span").text("St Lucia");						
				break;						
			case "sxm":		// St Maarten and Saba
			case "sxm_9":			
				$('#country_flag').attr("src", "/file-499446.jpg");
				$('#country_flag').attr("alt", "St Maarten Flag");
				$(".magicoverlay-trigger-expand span").text("St Maarten & Saba");
				$(".magicoverlay-trigger-collapse span").text("St Maarten & Saba");						
				break;
			case "ec_10":	// St Vincent
				$('#country_flag').attr("src", "/file-499440.jpg");
				$('#country_flag').attr("alt", "Eastern Caribbean");
				$(".magicoverlay-trigger-expand span").text("St Vincent");
				$(".magicoverlay-trigger-collapse span").text("St Vincent");						
				break;
			case "sr":		// Suriname
			case "sr_11":			
				$('#country_flag').attr("src", "/file-499448.jpg");
				$('#country_flag').attr("alt", "Suriname Flag");
				$(".magicoverlay-trigger-expand span").text("Suriname");
				$(".magicoverlay-trigger-collapse span").text("Suriname");						
				break;
			case "tt":		// Trinidad and Tabago
			case "tt_12":			
				$('#country_flag').attr("src", "/file-499450.jpg");
				$('#country_flag').attr("alt", "Trinidad and Tabago Flag");
				$(".magicoverlay-trigger-expand span").text("Trinidad & Tobago");
				$(".magicoverlay-trigger-collapse span").text("Trinidad & Tobago");					
				break;
			default :		// Blank - Transparent
				$('#country_flag').attr("src", "/file-499449.gif");
				$('#country_flag').attr("alt", "blank");
				$(".magicoverlay-trigger-expand span").text("Select Country");
				$(".magicoverlay-trigger-collapse span").text("Select Country");						
				break;
		}
	}
	
// ==============================================================================================
//
//  Replace the logo and content for rebranded specific pages
//
// ==============================================================================================
	
	// Temporary function for client to review the changes in preview mode
	function replaceContentTemp() {
		if (document.location.toString().indexOf('preview') != -1) { replaceContent(); }
	}
	
	
	function replaceContent() {
		// Replace the existing logo to RBC shield and Royal Bank description in the RBTT Home pages
		$('#globalheader-logo > a > img').attr('src','/file-578928.gif'); 
		$('#globalheader-logo > a > img').attr('alt','RBC Royal Bank'); 
		
		// Replace the information box for General Inquiries and Suggestions, Compliments & Complaints Forms
		if (document.location.toString().indexOf('customerservice') != -1) { 
		
			$('.callout-content > p ').html("<p>It is an individual decision to use the Internet for communication purposes and that includes personal information disclosed to us through the Internet. Any unprotected communication over the Internet is, as with communication via any other medium (e.g. cellular phones, post office mail), not confidential, subject to possible interception or loss and is also subject to possible alteration. The policy of RBC Caribbean is to adhere to strict policies of confidentiality, but RBC Caribbean cannot guarantee confidentiality of information transmitted on the Website, and is not and shall not be held responsible or liable for any unauthorised access to information on the Website.</p><p>RBC Caribbean shall not be liable in any way whatsoever, directly or indirectly, for any damages or loss whatsoever, resulting from or in connection with any communication sent by you to RBC Caribbean or any communication sent by RBC Caribbean to you at your request through the Internet, or for interference with or corruption of information transmitted on the Website; including but not limited to the publication or use for whatever purpose of all or part of the Information.</p>");
		}
		
		// Replace Breadcrumb text from RBTT to RBC Caribbean
		// Change only pages with RBTT text breadcrumb
		if ($('#CMS_Breadcrumb_Container').length) {
			var label = $('#CMS_Breadcrumb_Container > a:first').text();
			if (label.toLowerCase() == "rbtt") {
				$('#CMS_Breadcrumb_Container > a:first').text('RBC Caribbean');
				$('#CMS_Breadcrumb_Container > a:first').attr('href','http://www.rbc.com/caribbean');
			}
		}			
		
	}
