/**
 * @class RTW
 * @author Malcolm Clark
 *
 * RoundTheWorldExperts master object
 *
 * __Author:__ Malcolm Clark<br />
 * __Modified By:__ $LastChangedBy: ravalc $<br />
 * __Copyright:__ Copyright Flight Centre Ltd. All Rights Reserved.<br />
 * __Version:__ $Revision: 7707 $<br />
 * __Last Modified:__ $Date: 2011-05-10 15:38:02 +1000 (Tue, 10 May 2011) $
 *
 * ###Requires
 *
 * * FCL
 * * FCL.UTIL
 * * FCL.FORMS
 */
RTW =
{
    /* Name of class */
    name: 'RTW',

    /* Name of cookie for when user has come from an AdWords link */
    analyticsCookieName: 'RTW.ANALYTICS_COOKIE',
    
    /**
     * Code that needs to be executed on every page load.  Also creates a cookie if a "gclid" variable has been passed through in the url from Google AdWords.
     *
     * ###Functions called:
     * * RTW.UTIL.tickerInit();
     */
    init: function()
    {
		$(document).ready(function() 
        {
				RTW.detectUrl();	// yuin - 15/11/11 - Function to show active page 
				RTW.setMegaMenu();
				RTW.startHomeBanner();
				RTW.setTabContent();
				RTW.setupTopBanner();
				RTW.setupSearchResultsCss();
				RTW.handleConsInfo();  // jan - 30/11/11 Function to open/close consultant info
				RTW.handleContactUs();
				RTW.removeContentBottom(); // Remove #contentBottom box from page if empty
				RTW.onloadOperators(); // set-up scripts removed from html pages e.g ticker; news scroller)

        });
        $(window).bind('load', function(e)
        {
			$("#contact_us_details_button").click(function () {
				cl = $("#contact_us_details").attr("class");
				if (cl == "contact_us_details_hidden") {
					$("#contact_us_details").attr("class", "contact_us_details_show");
					$("#contact_us_details_button").attr("class", "contact_us_details_off");
				}
				if (cl == "contact_us_details_show") {
					$("#contact_us_details").attr("class", "contact_us_details_hidden");
					$("#contact_us_details_button").attr("class", "contact_us_details_on");
				}
			});
			
			// Yuin - 28/11/11 - To ensure this function only get called on home page
			// var getPathLength = window.location.pathname;
			// if (getPathLength.length <= 1){ // Jan (28/11/11) The slash in the path caused it to slip over the condition if '< 1'
			// 	$('#js-news').ticker();				
			// }
			
			// Home page tab switching
			$('#content .tab1').click(function() {
				$('#content').children().hide(); 
				$('#content .contentTab1, #content .tabbedContentBottom').show();
				// $('#content .tab1').attr('href',function(){return this.href + '#tab1';});	// Yuin - 17/11/11 - update url
				// jQuery.param.querystring(window.location.href, '#tab1');	// Yuin - 17/11/11 - update url
			});
			$('#content .tab2').click(function() {
				$('#content').children().hide(); 
				$('#content .contentTab2, #content .tabbedContentBottom').show();
			});
			$('#content .tab3').click(function() {
				$('#content').children().hide(); 
				$('#content .contentTab3, #content .tabbedContentBottom').show();
			});
			$('#content .tab4').click(function() {
				$('#content').children().hide(); 
				$('#content .contentTab4, #content .tabbedContentBottom').show();
			});

			
			// Product detail page bottom content tab switching:
			$('#content #productPageBottomContent .tabButton1').click(function() {
				$('#content #productPageBottomContent').children().hide(); 
				$('#content #productPageBottomContent .bottomContentTab1').show();
			});
			$('#content #productPageBottomContent .tabButton2').click(function() {
				$('#content #productPageBottomContent').children().hide(); 
				$('#content #productPageBottomContent .bottomContentTab2').show();
			});
			// Product Detail Adventure
			$('#content #productPageBottomContent .tabBtn1').click(function() {
				$('#content #productPageBottomContent').children().hide(); 
				$('#content #productPageBottomContent .tab13').show();
			});
			$('#content #productPageBottomContent .tabBtn2').click(function() {
				$('#content #productPageBottomContent').children().hide(); 
				$('#content #productPageBottomContent .tab23').show();
			});
			$('#content #productPageBottomContent .tabBtn3').click(function() {
				$('#content #productPageBottomContent').children().hide(); 
				$('#content #productPageBottomContent .tab33').show();
			});
			

			// Activating handlers for various links on home page
			$('.leftColumnBox.customersSay').next().click(function(){location.href="/about-us/comments"});
			$('.leftColumnBox.travelStories').next().click(function(){location.href="http://roundtheworld.visitorreview.org/"});
			$('.leftColumnBox.travelInspiration').next().click(function(){location.href="/travel"});

			$('.rightColumnBox.travelButler').next().click(function(){location.href="/travel-butler"});
			$('.rightColumnBox.howToPlan').next().click(function(){location.href="/plan-trip"});
			$('.rightColumnBox.faresExplained').next().click(function(){location.href="/advice/flight"});
			$('.rightColumnBox.toursATW').next().click(function(){location.href="/adventure/list"+RTW.PRODUCTCROSSSALE.toursAtwLink});
			$('.rightColumnBox.customersSay').next().click(function(){location.href="/about-us/comments"});
			$('.rightColumnBox.travelStories').next().click(function(){location.href="http://roundtheworld.visitorreview.org/"});  //INCORRECT LOCATION REFERENCE
			$('.rightColumnBox.travelInspiration').next().click(function(){location.href="/travel"});
			$('.rightColumnBox.toursAdventures').next().click(function(){location.href="/adventure"});
			$('.rightColumnBox.openDated').next().click(function(){location.href="/"});  //ENTER CORRECT LOCATION REFERENCE
			$('.rightColumnBox.lateGetaways').next().click(function(){location.href="/"}); //ENTER CORRECT LOCATION REFERENCE
			
			$('.clickEmailUs').click(function(){location.href="/contact-us?email"});
			$('.clickCallMeBack').click(function(){location.href="/contact-us?call"});
			$('.clickMakeAppointment').click(function(){location.href="/contact-us?appointment"});
			
			$('.clickTours').click(function(){location.href="#"});
			$('.butler').click(function(){location.href="/travel-butler"});
			$('.signUpNewsletter').click(function(){location.href="/newsletter"});
			$('.lowPricePromiseLink').click(function(){location.href="/about-us/low-price-promise"});
			
			// search button
			if ($('div.InputButton>span').text()==="search" && $('div.InputButton>span').next().attr("tagName").match(/img/i) && $('div.InputButton>span').next().attr("alt").match(/submit/i)) {
				$('div.InputButton>span').click(function(){
					$(this).next().click();
				});
			}
			
			$('<a href="#tab13" id="closeLink" class="contactUsLink productEnquiryFormLink close">close</a>').insertAfter($('.productEnquiryFormLink.open:visible'));
			$('#closeLink').hide();
			$('.productEnquiryFormLink.open:visible').click(function(){
				$this = $(this);
				$('#enquiryForm').slideDown(); 
				$this.css('display','none');
				$this.next().css('display','inline-block');
			});
			$('#closeLink').click(function(){
				$this = $(this);
				$('#enquiryForm').slideUp(); 
				$this.css('display','none');
				$this.prev().css('display','inline-block');
				$('.message').hide();
			});
			
			// Product enquiry form gets fired from all three tabs, but switches to tab1
			$('.productEnquiryFormLink.tab2').click(function(event) {
				$('.simpleContentTabsInside').show(); // adventure tabs
				$('#content #productPageBottomContent').children().hide(); 
				$('.bottomContentTab1').show(); // flights tabs
				$('#content #productPageBottomContent .tab13').show();
				$('#enquiryForm').slideDown();
				$('.productEnquiryFormLink.open:visible').hide();
				$('#closeLink').show();
			});
			$('.productEnquiryFormLink.tab3').click(function(event) {
				$('.simpleContentTabsInside').show();
				$('#content #productPageBottomContent').children().hide(); 
				$('#content #productPageBottomContent .tab13').show();
				$('#enquiryForm').slideDown();
				$('.productEnquiryFormLink.open:visible').hide();
				$('#closeLink').show();
			});
        })
    },
	setMegaMenu: function() {
		// find page width, the X-position, and calculate rightmost X-position
		var pageWidth = $('#page-content').width();
		var pageLeftXpos = $('#page-content').position().left;
		var pageRightXpos = $('#page-content').position().left + pageWidth;
		// fix the megamenu widht for the 6th button (flexible created problems in FF)
		$('ul#nav li.regular:eq(5) .topMenuExpand').width(600);
		
		
		$('ul#nav li.regular').mouseenter(function(e) {
			var hoverSelf = this;
			
			$(hoverSelf).find('a span.green').removeClass('green').addClass('grey');
			
			// Find button X-position and its width
			var linkXPos = $(hoverSelf).position().left;
			var linkWidth = $(hoverSelf).width();
			// Find the active megamenu x-position and width
			var activeMegamenuWidth = $(hoverSelf).find('.topMenuExpand').width();
			// declare megamenu x-position variable (left absolute position)
			var mmXPos;
			
			// left position of megamenu cannot be less then 'pageLeftXpos' and not more than 'pageRightXpos - activeMegamenuWidth'
			// 30 px added for extra space
			mmXPos = linkXPos + (linkWidth/2) - (activeMegamenuWidth/2);
			mmXPos = mmXPos < pageLeftXpos + 30 ? pageLeftXpos + 30 : mmXPos;
			mmXPos = mmXPos + activeMegamenuWidth > pageRightXpos - 30 ? pageRightXpos - activeMegamenuWidth - 30 : mmXPos;
			
			// set value of X-position and show box
			$(hoverSelf).find('.topMenuExpand').css('left', mmXPos).show();
			
			// apply a style through added class to the menu link upon mouse entering the megamenu box
			// remove class from a link on mouseleave
			$(hoverSelf).find('.topMenuExpand').mouseenter( function(e) {
				var _this = this;
				$(_this).prev('a:first').addClass('megamenuHighlightButton');
			});
			$(hoverSelf).find('.topMenuExpand').mouseleave( function(e) {
				var _this = this;
				$(_this).prev('a:first').removeClass('megamenuHighlightButton');
			});
		});
		$('ul#nav li.regular').mouseleave(function(e) {
			var unHoverSelf = this;
			
			$(unHoverSelf).find('a span.grey').removeClass('grey').addClass('green');
			$(unHoverSelf).find('.topMenuExpand').hide();
		});
	},

	// yuin - 15/11/11 - Navigation menu buttons to corresponds with active page
	detectUrl: function(){
		var activeUrl = window.location.pathname.split('/')[1];
		//console.log(activeUrl);

		switch(activeUrl){
			case 'flights':
				$('#flights').find('a:first').css('background-position','0 -74px');
				$('#flights').find('a span.green').css('color','grey');
				break;
			case 'adventure':
				$('#adventure').find('a:first').css('background-position','0 -74px');
				$('#adventure').find('a span.green').css('color','grey');
				break;
			case 'places-to-stay':
				$('#places-to-stay').find('a:first').css('background-position','0 -74px');
				$('#places-to-stay').find('a span.green').css('color','grey');
				break;
			case 'getting-around':
				$('#getting-around').find('a:first').css('background-position','0 -74px');
				$('#getting-around').find('a span.green').css('color','grey');
				break;
			case 'city-intros':
				$('#city-intros').find('a:first').css('background-position','0 -74px');
				$('#city-intros').find('a span.green').css('color','grey');
				break;
			case 'activities':
				$('#activities').find('a:first').css('background-position','0 -74px');
				$('#activities').find('a span.green').css('color','grey');
				break;
			case 'gap-year':
				$('#gap-year').find('a:first').css('background-position','0 -74px');
				$('#gap-year').find('a span.green').css('color','grey');
				break;
			case 'plan-trip':
				$('#plan-trip').find('a:first').css('background-position','0 -74px');
				$('#plan-trip').find('a span.green').css('color','grey');
				break;
			default:
				$('activeUrl').find('a:first').css('background-position','0 0');
		}
	},
	
	startHomeBanner: function() {
		if ($('#slideShow').children('a').length <= 1){
            $('.bottomNavigation').remove();
            return;
        } 
        
        $('#slideShow').cycle({
            fx:     'fade',
            speed:  'fast',
            timeout: 4000,
            pager:  '.bottomNavigation',
            pagerEvent: 'mouseover',
            slideExpr: 'img'
        });
	},
	
	showPopupBox: function () {
		var topLeftPos = {
			'x-pos': xpos,
			'y-pos': ypos
		}
		
		
		
	},
	
	setTabContent: function() {
		var j = 0, emptyElements = [];
		var totalTabs = $('#content .tab').size();
		
		$('.tab .userContent').each( function(i) {
			if($(this).is(':empty') || ($(this).children().size()===0 && $.trim($(this).text()).length===0) ) {
				emptyElements[j] = i+1;
				j+=1;
			}
		})
		var numberOfTabs = totalTabs - emptyElements.length; // Get the number of visible tabs
		
		for(var k=0; k<emptyElements.length; k++) {
			$('#content .tab:nth-child('+emptyElements[k]+')').remove();
			$('.tab>.tabLinks>.tabButton:nth-child('+emptyElements[k]+')').remove(); // Remove tab headings for empty tab containers
			
			// adjust the reference numbers of elements after removing an empty element
			for ( j = k + 1; j < emptyElements.length; j++ ) {
				emptyElements[j] -= 1;
			}
		}
		//re-asign class names to re-ordered elements by their order
		$('#content>.tab').each( function(i) {
			i+=1;
			$(this).attr('class', 'tab contentTab'+i+'');
			$(this).find('.tabLinks>.tabButton').each( function (i) {
				var _this = this;
				i+=1;
				$(_this).attr('class', 'tabButton tab'+i+'');
			})
			//append the content with and empty container to apply clear-all style
			$(this).find('.userContent').append('<div class="clear-all"> </div>');
		});
		
		if(numberOfTabs == 1) {
			$('#content').attr('class', 'noTabs');
			$('.tab .tabLinks').remove();
			$('#sidebar-right').css('padding-top', '8px');
		}
		if(numberOfTabs > 1) {
			$('#content').attr('class', 'tabbedContent-'+ numberOfTabs);
		}
	},
	setupTopBanner: function () {
		if(!($('#content-top-banner.top-banner').children('img').size()===1)) {
			$('#content-top-banner.top-banner').remove();
		}
	},
	setupSearchResultsCss: function() {
		$('.boxInnerSimpleContent').height($('#searchResults').height() + 270);
	},
	
	handleConsInfo: function() {
		
		$('#consultantInfo .top .rightBox label').click( function(e) {
			if( $('#consultantInfo .consultantInfoContent').css('display')=='none') {
				$('#consultantInfo .consultantInfoContent').show();
				$(this).text('Hide');
			} else {
				$('#consultantInfo .consultantInfoContent').hide();
				$(this).text('Show');
			}
		});
	},

	// 12/12/2011 Jan - detect from which link the contact-us form has been accessed, open and scroll to
	handleContactUs: function() {
		var currentUrl = window.location.pathname.split('/')[1];
		var queryStr ="";
		var hasQueryStr = document.URL.indexOf('?');
		//console.log(currentUrl);

		if(currentUrl=="contact-us" && hasQueryStr!=-1)
		{
			queryStr =  document.URL.substring(hasQueryStr+1, document.URL.length);
			
		//console.log(queryStr);

			switch (queryStr)
			{
				case 'call':				
					if ($('#getCallback').find(".text").html().match(/get us to call you back/)) {
						$('#getCallback').find(".text").html("remove<br/>callback");
						$(".section.callback").removeClass("hide").addClass("show");
	          			// add in keyword for callback if added in
	          			$("#enquiryForm").prepend('<input type="hidden" name="en_callback_keyword" id="en_callback_keyword" value="rtwuk_callBack"/>');
	          			var callbackYPos = $(".section.callback").position().top;
	          			window.scroll(0,callbackYPos);
					}
					break;
				case 'appointment':
					if ($('#makeAppointment').find(".text").text() === "make an appointment") {
						$('#makeAppointment').find(".text").text("remove appointment");
						$(".section.appointment").removeClass("hide").addClass("show");
						$('#appStore').addClass("required");
						var appointmentYPos = $(".section.appointment").position().top;
						window.scroll(0, appointmentYPos);
					}
					break;
				case 'email':
					
					break;
			}
		}	
	},

	removeContentBottom: function() {
		if($('#contentBottom').is(':empty') || ($('#contentBottom').children().size()===0 && $.trim($('#contentBottom').text()).length===0) ) {
			$('#contentBottom').css('display', 'none');
		}
	},

	onloadOperators: function() {
		//homepage ticker
		//console.log($('#js-news'));
		 $('#js-news').ticker();
		
		//news scroller used in right hand bar for customer feedback
		$('.newsScroller').vTicker({speed: 500, pause: 5000, showItems: 1, animation: "fade"});
	}
};
RTW.init();
