/*
 * Copyright 1997-2010 Day Management AG
 * Barfuesserplatz 6, 4001 Basel, Switzerland
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * Day Management AG, ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Day.
 */
/**
 * Utility functions for forms components.
 */
function cq5forms_isArray(obj) {
	if (typeof obj.length == 'number' && typeof obj.item == 'function') {
		return true;
	} else {
		return false;
	}
}

function cq5forms_showMsg(fid, field, msg, index) {
    var f = document.forms[fid].elements[field];
    alert(msg);
    if ( cq5forms_isArray(f) ) {
    	if ( !index) index = 0;
    	f[index].focus();
    } else {
    	f.focus()
    }
}
function cq5forms_isEmpty(obj) {
    var empty = true;
    if ( cq5forms_isArray(obj)) {
        for(i=0;i<obj.length;i++) {
            if (obj[i].type == "radio" || obj[i].type == "checkbox" ) {
                if (obj[i].checked) {empty = false;}
            } else {
                if (obj[i].value.length>0) { empty = false;}
            }
        }
    } else {
        if (obj.type == "radio" || obj.type == "checkbox" ) {
            if (obj.checked) {empty = false;}
        } else {
            if (obj.value.length>0) { empty = false;}
        }
    }
    return empty;
}
function cq5forms_regcheck(obj, pattern) {
    var result=false;
    var t = pattern.exec(obj);
    if (t) {
        var len = obj.length;
        var pattlen = t[0].length;
        result = (pattlen == len);
    }
    return result;
}
/*
 * Copyright 1997-2010 Day Management AG
 * Barfuesserplatz 6, 4001 Basel, Switzerland
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * Day Management AG, ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Day.
 */
(function($) {
    $(function () {
        // Used to output caught errors
        function errorLog(error, message) {
            try {
                if ($.cq.isAuthor() || window.location.hash == '#debug') {
                    if (typeof console != 'undefined' && typeof console.log  != 'undefined') {
                        console.log(error);
                        console.log(message);
                    }
                    alert(error.name+':\n'+error.message+'.\n'+message+'.');
                }
            } catch (e) { }
        }

        try {
            // Opacity fading conflicts in IE8 with the PNG fix and text anti-aliasing
            var fadingSpeed = $.browser.msie ? 0 : 250;

            // Removes the URL hash if it corresponds to the id of an element in the given context
            function removeHash(context) {
                try {
                    if (window.location.hash.length > 0 && $(window.location.hash, context).length > 0) {
                        window.location = (window.location+'').replace(window.location.hash, '');
                    }
                } catch (e) {
                    errorLog(e, 'Could not remove hash');
                }
            }

            // carousel code
            try {
                $('.cq-carousel').each(function () {
                    var carousel = $(this);
                    var playDelay = +$("var[title='play-delay']", this).text();
                    if (!playDelay) {
                        playDelay = 6000;
                    }
                    var slidingSpeed = +$("var[title='transition-time']", this).text();
                    if (!slidingSpeed) {
                        slidingSpeed = 1000;
                    }
                    var banners = $('.cq-carousel-banners', this);
                    //do not why, but
                    // var links = $('.cq-carousel-banner-switch a', this);
                    //returns more links than expected after component reload. Changed to "find" = works......
                    var switcher = $('.cq-carousel-banner-switch', this);
                    var links = switcher.find('a');
                    var items = $('.cq-carousel-banner-item', this);
                    var width = items.outerWidth();
                    var itemActive = items.filter(':first');
                    var itemPrevious = null;
                    var interval = null;
                    var i = 0;

                    var ctlPrev = $('a.cq-carousel-control-prev', this);
                    ctlPrev.click(function() {
                        if (ctlPrev.is('.cq-carousel-active')) {
                            $(links[(i+links.length-1)%links.length]).click();
                        }
                        return false;
                    });
                    var ctlNext = $('a.cq-carousel-control-next', this);
                    ctlNext.click(function() {
                        if (ctlNext.is('.cq-carousel-active')) {
                            $(links[(i+1)%links.length]).click();
                        }
                        return false;
                    });
                    if (links.length > 1) {
                        ctlNext.addClass('cq-carousel-active');
                    }
                    function play() {
                        stop();
                        if( playDelay > 0) {
                            interval = setInterval(function () {
                                $(links[(i+1)%links.length]).click();
                            }, playDelay);
                        }
                    }
                    function stop() {
                        if (interval !== null) {
                            clearInterval(interval);
                            interval = null;
                        }
                    }

                    // Show first item (needed for browsers that don't support CSS3 selector :first-of-type)
                    if (fadingSpeed || $.browser.version > 6) {
                        itemActive.css('left', 0);
                    } else {
                        itemActive.show();
                    }

                    links
                        .click(function () {
                            var link = $(this);
                            var itemNew = items.filter(link.attr('href'));
                            var j = itemNew.prevAll().length;
                            var direction = (j > i || interval !== null) ? 1 : -1;

                            if (!link.is('.cq-carousel-active')) {
                                links.removeClass('cq-carousel-active');
                                link.addClass('cq-carousel-active');

                                if (itemActive.is(':animated')) {
                                    itemActive.stop(true, true);
                                    itemPrevious.stop(true, true);
                                }

                                if (fadingSpeed) {
                                    itemNew.css({'left': direction*width}).animate({'left': 0, 'opacity': 1}, slidingSpeed);
                                    itemActive.animate({'left': -direction*width, 'opacity': 0}, slidingSpeed);
                                } else if ($.browser.version > 6) {
                                    itemNew.css({'left': direction*width}).animate({'left': 0}, slidingSpeed);
                                    itemActive.animate({'left': -direction*width}, slidingSpeed);
                                } else {
                                    itemNew.fadeIn();
                                    itemActive.fadeOut();
                                }

                                itemPrevious = itemActive;
                                itemActive = itemNew;
                                i = j;
                                if (i > 0) {
                                    ctlPrev.addClass('cq-carousel-active');
                                } else {
                                    ctlPrev.removeClass('cq-carousel-active');
                                }
                                if (i < links.length-1) {
                                    ctlNext.addClass('cq-carousel-active');
                                } else {
                                    ctlNext.removeClass('cq-carousel-active');
                                }
                            }

                            return false;
                        })
                        .each(function () {
                            var link = $(this);

                            link.attr('title', link.text());
                        })
                        .filter(':first').addClass('cq-carousel-active');

                    play();
                    carousel.hover(
                            function() {
                                stop();
                                ctlPrev.fadeIn();
                                ctlNext.fadeIn();
                            },
                            function() {
                                play();
                                ctlPrev.fadeOut();
                                ctlNext.fadeOut();
                            }
                    );

                    // Accessing the page with the anchor of a banner in the URL can break the layout
                    removeHash(this);
                });
            } catch (e) {
                errorLog(e, 'Could not initialize the banners');
            }
        } catch (e) {
            errorLog(e, 'Init failed');
        }
    });
})($CQ || $);
var mobile_ajax_Path = "/content/publictransport/mobile";
var resource_file_path = "www.publictransport.sg";
//var resource_file_path = "ptppublish.portalcity.sg";

function getTrainRouteInfo(){


	
	if (jQuery("#trainId").val() != "default"  && jQuery("#trainId").val() != "mrt_sys_map"){

		jQuery.ajax({
		    url: mobile_ajax_Path+"/mobile_ajaxlib.html?trainId="+jQuery("#trainId").val()+"&action=getTrainStationInfo" ,
		    success: function(data){
			
	
	
		    	//jQuery("#train_result").html(data.replace(/www.lta.sg/g, "www.publictransport.sg"));
		    	jQuery("#train_result").html(data.replace(/www.lta.sg/g, resource_file_path));
		    	jQuery("#train_option").css("display","none");
		 },
	      error: function(data){
			
	    	alert("Sorry, our system is encountering high demand at the moment. Please try again later");
	      }
		});	
	}
	
	if (jQuery("#trainId").val() == "mrt_sys_map"){
		jQuery("#train_option").css("display","none");
		
		//	jQuery("#train_result").html("MRT/LRT Station: <a href='http://www.publictransport.sg/pdf/mrt_sys_map.jpg'>MAP</a>. (download)");
		jQuery("#train_result").html("MRT/LRT Station: <a href='http://"+resource_file_path+"/pdf/mrt_sys_map.jpg'>MAP</a>. (download)");
		
	}
	
}


function MRT_LRT_Home(){
	if ( jQuery("#train_result").html() != "" ){
	jQuery("#train_option").css("display","block");
	jQuery("#trainId").val("default");
	jQuery("#train_result").html("");
	}else{
		window.location = mobile_ajax_Path+"/mobilehome.html";
	}
}






//=======================================================


function getBusServiceInfo(){

	if (jQuery("#busSerNo").val() != "default"){
		jQuery.ajax({
		    url: mobile_ajax_Path+"/mobile_ajaxlib.html?busServiceNo="+jQuery("#busSerNo").val()+"&action=getBusServiceInfo" ,
		    success: function(data){
			

			jQuery("#busRoute_result").html(data.replace(/www.lta.sg/g, resource_file_path));
			
			jQuery("#busRoute_option").css("display","none");
		 },
	      error: function(data){
		
	    	alert("Sorry, our system is encountering high demand at the moment. Please try again later");
	      }
		});	
	}
	
	
}


function busRoute_Home(){
	if ( jQuery("#busRoute_result").html() != "" ){
	jQuery("#busRoute_option").css("display","block");
	jQuery("#busSerNo").val("default");
	jQuery("#busRoute_result").html("");
	}else{
		window.location = mobile_ajax_Path+"/mobilehome.html";
	}
}









//=======================================================


function getBusArrivalInfo_mobile(){

//	bus_service

	
	if (jQuery("#bus_stop").val() == ""   ){
		alert("Please enter the bus stop code.");
		return false;
	}
	
	var	busStopCode = jQuery("#bus_stop").val()+"";
	var	busSerNo = jQuery("#bus_service").val()+"";

	
;	
	if (jQuery("#bus_stop").val() != ""  ){
		jQuery.ajax({
			url: "http://"+location.host+"/busarrival/"+busStopCode+".json" ,
			dataType: 'json',
		   	success: function(data){
			
		jQuery("#busArrival_option").css("display","none");	
		
		 // no time arr data in the json file 
	       if(data =="" || data =="null" || data ==null || data.info ==""){
	    	   jQuery("#busArrival_result_empty").html("<p>The current bus arrival information is not available.</p>");
	       }

		var busService;
		var arrNow;
		var arrLater;
		var arrNowDisFriendly;
		var arrLaterDisFriendly;
		var currentSeconds;
		var nextRefresh;
		var count = 1;
    	var time = String(data.time);
    	var dataTime_DATE = time.substring(0,8);
    	
    	var dataTime_HR = time.substring(9,11).replace(/^[0]+/g,""); // remove leading 0
    	var dataTime_MIN = time.substring(11,13).replace(/^[0]+/g,"");// remove leading 0
    	
    	if( time.substring(9,11) == "00" || time.substring(9,11) == ""){  dataTime_HR=0; }      
    	if( time.substring(11,13) == "00"||  time.substring(11,13) == ""){ dataTime_MIN =0; }  
    	
    	var dataTime_HR_MIN =   parseInt(dataTime_HR *60 ) +  parseInt(dataTime_MIN);
   
       
//-------formating the date/time for display  
        var d=new Date();
        var month=new Array(12);
        month["01"]="January";
        month["02"]="February";
        month["03"]="March";
        month["04"]="April";
        month["05"]="May";
        month["06"]="June";
        month["07"]="July";
        month["08"]="August";
        month["09"]="September";
        month["10"]="October";
        month["11"]="November";
        month["12"]="December";
        
        var displayDateTime;
        var dayUnit = "AM";
        if (  parseInt(time.substring(9,11)) > 12 ){dayUnit=" PM"; }
        time = time.substring(0,2)+" "+  month[time.substring(2,4)] +" "+time.substring(4,8) +" "+time.substring(9,11) +":"+time.substring(11,13);
        
        
//-------formating the date/time for display    
        
        var now = new Date();
        var nowHour=  now.getHours();
        var nowMin=  now.getMinutes();
        
        if (nowHour < 10 ){ nowHour = "0"+nowHour; }
        if (nowMin < 10 ){ nowMin = "0"+nowMin; }    
        var curTime_HR_MIN =   parseInt(nowHour*60)+  parseInt(nowMin);
        
        var nowDay=  now.getDate();
        var nowMonth=  now.getMonth()+1;
        var nowYear=  now.getFullYear();
        
        if (nowDay < 10 ){ nowDay = "0"+nowDay; }
        if (nowMonth < 10 ){ nowMonth = "0"+nowMonth; }
           
        timeDiff = parseInt(curTime_HR_MIN) - parseInt(dataTime_HR_MIN)  ;
    	
       if (  ( dataTime_DATE != (nowDay+""+nowMonth+""+nowYear) )  || timeDiff > 10  ){  //more than 10 mins 
       	count =0;	
       }
   
       
      
       
       
       
		var gotArrData = false;
		jQuery.each(data.info,function(i,infoValue){
			
			busService = infoValue.bsvc;
			arrNow = infoValue.arr1;		
		if ( busService == busSerNo && busSerNo != "" ){ gotArrData = true;}
		if ( arrNow != "" && busSerNo == "" ){ gotArrData = true;}	
		});
		

		if (count != 0 && gotArrData){ 
			
			capIcon = "";
			
			 jQuery.get(mobile_ajax_Path+"/mobile_ajaxlib.html?busServiceId="+busStopCode+"&action=getBusStopByIdDiscapbilityFriendlyCheck"  , function(data) {
	            	if (trim(data) == "false"){ 
	                    capIcon = "<div class='not_discapability_friendly_icon' style='float:left;margin-left:10px;'> </div>"; 
	                }
	            }); 
			
			
			jQuery("div#busArrival_result").html("");// clear content
				
			jQuery("div#busArrival_result").append("<div id='arrival_time_result'>");
			
			jQuery("div#busArrival_result").append("<div id='busStopDetail'></div>");
			
			
			
			
			jQuery.ajax({
					url: mobile_ajax_Path+"/mobile_ajaxlib.html?busStopCode="+busStopCode+"&action=getBusStopDescription",
					 success: function(data){
					jQuery("div#busStopDetail").append("<div style='float:left'>Bus Stop Code : "+busStopCode+"</div> "+capIcon+"<br>"); 
					jQuery("div#busStopDetail").append("Bus Stop Descriptions : "+data+"<br>");
					jQuery("div#busStopDetail").append("Last Updated : "+time+"<br><br>");		
					}
					});



				
			jQuery("div#busArrival_result").append("<div class='arrival_time_bus_col '>Bus No.</div><div class='arrival_time_arriving_col '>Arriving</div><div class='arrival_time_next_bus_col '>Next Bus</div>");

			jQuery("div#busArrival_result").append("<div class='br_line'></div>");	
			jQuery.each(data.info,function(i,infoValue){
				
				busService = infoValue.bsvc;
				arrNow = infoValue.arr1;
				arrLater = infoValue.arr2;
				arrNowDisFriendly = infoValue.wc1;
				arrLaterDisFriendly = infoValue.wc2;
				arrNowCapIcon = "";
				arrLaterCapIcon = "";
				
				
				if (busSerNo != "" &&  busService == busSerNo ){
			
				if (arrNowDisFriendly == 1 && arrNow != ""){ arrNowCapIcon= "<div class='discapability_friendly_icon'></div>";  }
				if (arrLaterDisFriendly == 1 && arrNow != ""){ arrLaterCapIcon= "<div class='discapability_friendly_icon'></div>";  }

				jQuery("div#busArrival_result").append("<div class='mobile_arrival_time_divider'></div>");
				jQuery("div#busArrival_result").append("<div class='arrival_time_bus_col'>"+busService+"</div>");
				 
				   arrNowTxt = arrNow+" Mins";
				   arrLaterTxt = arrLater+" Mins";
				   
				   if ( arrNow == 0 || arrNow.toLowerCase() == "arr" ) 
				   {  arrNowTxt ="Arr"; }

				   if ( arrNow != 0 && arrNow.toLowerCase() != "arr" &&  arrNow != "") 
				   {  arrNowTxt =arrNow+" Mins";  }
				   
				   if ( arrNow == ""){	  
					   arrNowTxt ="NA.";  
				   }
				  
				   if ( arrLater != 0 && arrLater.toLowerCase() != "arr" &&  arrLater != "") 
				   {  arrLaterTxt =arrLater+" Mins";  }
				      
				   
				   if ( arrLater == "" || arrLater == 0){	  
					   arrLaterTxt ="NA.";  
				   }
			
				jQuery("div#busArrival_result").append("<div class='arrival_time_arriving_col'><div class='ar_txt'>"+arrNowTxt+"  </div>"+arrNowCapIcon+"</div> ");
				jQuery("div#busArrival_result").append("<div class='arrival_time_next_bus_col'><div class='ar_txt'>"+arrLaterTxt+"  </div>"+arrLaterCapIcon+" </div> ");
				jQuery("div#busArrival_result").append("<div class='mobile_arrival_time_divider'></div>");
				jQuery("div#busArrival_result").append("<div class='br_line'></div>");
				
				}
				
				if (busSerNo == "" ){
					
					if (arrNowDisFriendly == 1 && arrNow != ""){ arrNowCapIcon= "<div class='discapability_friendly_icon'></div>";  }
					if (arrLaterDisFriendly == 1 && arrNow != ""){ arrLaterCapIcon= "<div class='discapability_friendly_icon'></div>";  }

					jQuery("div#busArrival_result").append("<div class='mobile_arrival_time_divider'></div>");
					jQuery("div#busArrival_result").append("<div class='arrival_time_bus_col'>"+busService+"</div>");
					 
					   arrNowTxt = arrNow+" Mins";
					   arrLaterTxt = arrLater+" Mins";
					   
					   if ( arrNow == 0 || arrNow.toLowerCase() == "arr" ) 
					   {  arrNowTxt ="Arr"; }

					   if ( arrNow != 0 && arrNow.toLowerCase() != "arr" &&  arrNow != "") 
					   {  arrNowTxt =arrNow+" Mins";  }
					   
					   if ( arrNow == ""){	  
						   arrNowTxt ="NA.";  
					   }
					  
					   if ( arrLater != 0 && arrLater.toLowerCase() != "arr" &&  arrLater != "") 
					   {  arrLaterTxt =arrLater+" Mins";  }
					      
					   
					   if ( arrLater == "" || arrLater == 0){	  
						   arrLaterTxt ="NA.";  
					   }
				
					jQuery("div#busArrival_result").append("<div class='arrival_time_arriving_col'><div class='ar_txt'>"+arrNowTxt+"  </div>"+arrNowCapIcon+"</div> ");
					jQuery("div#busArrival_result").append("<div class='arrival_time_next_bus_col'><div class='ar_txt'>"+arrLaterTxt+"  </div>"+arrLaterCapIcon+" </div> ");
					jQuery("div#busArrival_result").append("<div class='mobile_arrival_time_divider'></div>");
					
					
					
				}
				

			});
			jQuery("div#busArrival_result").append("<div class='br_line'></div>");
			jQuery("div#mobile_refresh_link").append("<a href='busarrivaltime.html?busStopCode="+busStopCode+"&busSerNo="+busSerNo+" '>Refresh</a>");
			
			
			
			} else {	
				tempBusSerNo = "";
				
				if (busSerNo != ""  ){
					jQuery("#busArrival_result_empty").html("<p>"+busSerNo+"  - Bus service is not available.</p>");
				}else{
				jQuery("#busArrival_result_empty").html("<p>The current bus arrival information is not available.</p>");
				}
			}
			
			
			jQuery("div#busArrival_result").append("</div>");
			
			
			
		
	},
    error: function(data){
		jQuery("div#busArrival_option").css("display","none");
		jQuery("div#busArrival_result").html("");
		jQuery("div#busArrival_result_empty").html("<p>"+busStopCode+" - Bus stop not found. Pls verify the bus stop code.</p>");
		 }
	
	});	
		
		
	
		
		
		
		
	}
	
}


function busArrival_Home(){
	
	if ( jQuery("#busArrival_result").html() != "" || jQuery("#busArrival_result_empty").html() != "" ){
	jQuery("#busArrival_option").css("display","block");

	jQuery("#busArrival_result").html("");
	jQuery("#mobile_refresh_link").html("");
	jQuery("#busArrival_result_empty").html("");
	}else{
		window.location = mobile_ajax_Path+"/mobilehome.html";
	}
}






var  keywordSynId = "";

var  latestsuggestion = 0;
var  latestsuggestionPBS = 0;

//var mapPath_page ="/content/publictransport/en/homepage/map";
var map_ajax_Path ="/content/publictransport/en/homepage/Ajax";

function doShowPremium(busSvrName , busSvrNum)  // call from Map app
{
	
    showPremiumBusRouteDetail( unescape(busSvrName) , busSvrNum);
    showPremiumMenu();
}

function doArrivalRefresh(busStopCode)  // call from Map app
{
    showBusStopWithArrivalPanel();
    showArrivalResult(busStopCode);
}

/*-------------Methods for Suggestion box---------------------------------------*/


function detectInput(  ) // for all 3 textfields
{   
    
jQuery('#search_input').keyup(function(e) { 
    if(e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 13) { // not up,down,enter key
        retrieveData();
        suggestion_hightligh_counter=-1; 
        }
});

jQuery('#originPBS').keyup(function(e) { 
	
    if(e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 13) { // not up,down,enter key
        retrieveDataPBS(   jQuery('#originPBS').val() ,'pbs_suggestion_box_origin'   );
        suggestion_hightligh_counter=-1; 
        
        }
});

jQuery('#destinationPBS').keyup(function(e) { 
    if(e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 13) { // not up,down,enter key
        retrieveDataPBS(   jQuery('#destinationPBS').val() ,'pbs_suggestion_box_destination'   );
        suggestion_hightligh_counter=-1; 
        }
});




}

var suggestion_hightligh_counter = -1;
function suggestionSelection( inputBox, suggestionBox    ){

    jQuery("#"+inputBox).keydown(function(e) {
 
        if(e.keyCode == 13  ) {
        
            if ( jQuery("#suggestion_"+suggestion_hightligh_counter).html() != null ){
            jQuery("#"+inputBox).val(   unescape( jQuery("#suggestion_"+suggestion_hightligh_counter).text()) );
            suggestion_hightligh_counter=-1; 
            }

            if(inputBox == "search_input" ){
                hideSuggestionBox();
                submitKeyword();
            }else{
                hideSuggestionBoxPBS();
            }
        
            if (inputBox == "originPBS"){
                var originPBS = trim(jQuery('#originPBS').val());
               
            	 if (  originPBS != "" &&  originPBS != "Enter your origin"   ) {
            	submitPBSsearch();
            	 }
            }
            
            if (inputBox == "destinationPBS"){
            	 var destinationPBS = trim(jQuery('#destinationPBS').val());
           	 if (  destinationPBS != "" &&  destinationPBS != "Enter your destination"   ) {
             	submitPBSsearch();
             	 }
            }
             
            
            e.preventDefault();
        }   
        
        if(e.keyCode == 38) {
            
            
             if (suggestion_hightligh_counter  > 0 ){
        
            if (suggestion_hightligh_counter % 2 == 0 ){  bgColorCode = "#D4D4D4"; }else{    bgColorCode = "#E0E0E0"; }
                
            jQuery("#suggestion_"+suggestion_hightligh_counter).css("backgroundColor",bgColorCode);
            jQuery("#suggestion_"+suggestion_hightligh_counter).css("color","#000000");
            
           
            suggestion_hightligh_counter = suggestion_hightligh_counter - 1;
            jQuery("#suggestion_"+suggestion_hightligh_counter).css("backgroundColor","#0000FF");
            jQuery("#suggestion_"+suggestion_hightligh_counter).css("color","#ffffff");
            
            }
            
             
                 e.preventDefault();
                 
        }
        
        if(e.keyCode == 40) {
     
            //count how many result is returned
            maxSuggestionCount = jQuery('#'+suggestionBox+' > div').size()-2; // max is 5 , one additional div for synId

        
            if (suggestion_hightligh_counter  < maxSuggestionCount){
                 
            if (suggestion_hightligh_counter % 2 == 0 ){  bgColorCode = "#D4D4D4"; }else{    bgColorCode = "#E0E0E0"; }

            jQuery("#suggestion_"+suggestion_hightligh_counter).css("backgroundColor",bgColorCode);
            jQuery("#suggestion_"+suggestion_hightligh_counter).css("color","#000000");

            suggestion_hightligh_counter = suggestion_hightligh_counter + 1;
            jQuery("#suggestion_"+suggestion_hightligh_counter).css("backgroundColor","#0000FF");
            jQuery("#suggestion_"+suggestion_hightligh_counter).css("color","#ffffff");
            
              }
                 e.preventDefault();
        }

    });
    
    
    
    
    
}



function retrieveData( )
{   
    input = trim( jQuery("#search_input").val() );
    if ( (trim(input).length) >= 3   ){
        populateData();
    }
    if ( input.length < 3 ){  
        hideSuggestionBox();
    }
}  


function populateData() { 

    input = trim( jQuery("#search_input").val() );
    latestsuggestion = Math.floor(Math.random()*10);
    jQuery.ajax({
        url:    map_ajax_Path+"/map_ajaxlib.html?keyword="+input+"&searchType=normal&keywordSynId="+latestsuggestion+"&action=getAddressByKeywords",
        success: function(result) {
        jQuery('#suggestion_box').html(result);  
        if ( jQuery('#synId').html() == latestsuggestion ){
            jQuery('#suggestion_box').slideDown(300);
        }
    },
    async: true 
}); 

} 



function highLightOn(thisElement)
{ 
    thisElement.style.backgroundColor = "#0000FF";
    thisElement.style.color= "#ffffff";
}


function highLightOff(thisElement , color)
{ 
    thisElement.style.backgroundColor = color;
    thisElement.style.color= "#000000";
}


function selectSuggestion(thisElement)  
{ 
    jQuery("#search_input").val( jQuery(thisElement).text() );
    selectedAddressId = jQuery(thisElement).html();
    if ( selectedAddressId !=""){
    
        submitKeyword();
    }
}

function hideSuggestionBox()
{ 
    jQuery('#suggestion_box').slideUp(1000 ,function(){jQuery('#suggestion_box').html("");}  );
} 

function clearEgText(){
    if ( jQuery('#search_input').val() == "eg: Bishan Road / Republic Plaza / 219428" ){
    jQuery('#search_input').val("");
    }
    } 

function hideSuggestionBoxMapMenu()
    {
    if ( jQuery('#search_input').val() == "" ){
    jQuery('#search_input').val("eg: Bishan Road / Republic Plaza / 219428");
    }
        jQuery('#suggestion_box').slideUp(1000 ,function(){jQuery('#suggestion_box').html("");}  );
    } 


/*-------------Methods for Searching by Keywords---------------------------------------*/    

function submitKeyword() { 

    if ( jQuery('#search_input').val() == "" || jQuery('#search_input').val() =="eg: Bishan Road / Republic Plaza / 219428"){
        alert("Please enter the Keyword(s) to search");
    }else{
    

        resetBusServiceOption();
        resetBusInterChangeOption();
        resetStationOption();
        resetMenuOption();
    
        
        latestsuggestion = "";
        jQuery("#submit_loading_icon").css("display","block");
        jQuery('#suggestion_box').html("");
        input = trim( jQuery('#search_input').val());  

        // check for postal code, if there is, submit only postal code  (xxxxxx)
        var re = new RegExp(/\(\d\d\d\d\d\d\)+$/g);
        
        if (input.match(re)){
            
            input  = ""+/\(\d\d\d\d\d\d\)+$/g.exec(input); // use this for all browser, IE cant read RegExp
            input = input.replace(/\((\d{6})\)$/g, "$1");
        }
        
        
        // check for bus stop code, if there is, submit only bus stop code [xxxxx]
        var re = new RegExp(/\[\d\d\d\d\d\]+$/g);

        if (input.match(re)){
            input  = ""+/\[\d\d\d\d\d\]+$/g.exec(input); // use this for all browser, IE cant read RegExp
            input = input.replace ("[", "");
            input = input.replace ("]", "");
        }   
        


    jQuery.ajax({
            url: map_ajax_Path+"/map_ajaxlib.html?keyword="+input+"&action=getAddressFullDetailByKeywords",
            success: function(data){
            jQuery('#bus_route_result_content').css("display", "none"); // hide the bus route result content
            jQuery('#address_result_content').css("display", "block");
            jQuery('#address_result_content').html( data);  
            jQuery("#submit_loading_icon").css("display","none");
            jQuery('#result_based_on').html("<div style='float:left;width:120px;'>Search by keywords : </div><div style='float:left;width:350px;'><b>\" "+jQuery('#search_input').val()+" \"</b></div>"); 

            //count how many result is returned
            count = jQuery('#address_result_content > div').size();
            if( count > 1 ){ // if more than 1 , then hide map
                jQuery('#address_result_content').css("min-height","350px");   
                jQuery('.map_content_section').slideUp(400);
            }else{      
                showOnMap(jQuery('#longitude').html() , jQuery('#latitude').html()); 
                jQuery('#address_result_content').css("min-height","0px");   
                if(  jQuery('.address_detail').html()  == "No result found"){
                    alert("No result found");
                }
            }       
            resetBusServiceOption();
            resetBusInterChangeOption();
            resetStationOption();
        },
          error: function(data){
        	
            alert("No result found.");
            jQuery('#submit_loading_icon').css("display" , "none");
              
          }
    }); 
    }
    hideSuggestionBox(); 
}  




/*===============Methods for result panel===============*/      

/*---------result for selected bus route---------------*/
function showBusRoute(zoom , type ,busServiceNo_Dir){

    if (jQuery("#busservice_option").val() != "default"){
    
        resetMap();
        
        var dataSerNoDir = busServiceNo_Dir.split("_");
        
        busServiceNo = dataSerNoDir[0];
        busServiceDir = dataSerNoDir[1];
        
        if (busServiceDir == null || busServiceDir == ""){
            
            busServiceDir = 1;
        }
    
    jQuery('#menu_option').val("other"); 
    jQuery("#map_menu_loading").css("display", "block");//show loading
    jQuery('#address_result_content').css("display", "none"); // hide the address result content
    jQuery('#bus_stop_arrival_time_result_content').css("display", "none");
    
    objBusRoutes.showBusRoutes(zoom, "", busServiceNo , busServiceDir);  //show route
    
    showAnnouncement("normal_announcement");
    
    jQuery.ajax({
        url: map_ajax_Path+"/map_ajaxlib.getBusRouteByServiceId."+busServiceNo+".html" ,
        success: function(data){
        jQuery('#result_based_on').html("Bus Service No : <b>\" "+busServiceNo+" \"</b>"); 
        jQuery('#bus_route_result_content').css("display", "block");
        jQuery('#bus_route_result_content').html(data);    
        jQuery('.map_content_section').slideDown(400); 
        jQuery("#map_menu_loading").css("display", "none");
      },
      error: function(data){
    	  window.location.reload();
        //  alert("Sorry, our system is encountering high demand at the moment. Please try again later.");
          jQuery('#map_menu_loading').css("display" , "none");
      }
}); 
    resetBusInterChangeOption();
    resetStationOption();
    }
}    



/*---------result for selected bus interchange---------------*/
function showBusInter(busInterID){
    
    if (jQuery("#businter_option").val() != "default"){
        
        
        resetMap();

    
    showAnnouncement("normal_announcement");
    jQuery('#menu_option').val("other"); 
    jQuery("#map_menu_loading").css("display","block");
    jQuery('#bus_route_result_content').css("display", "none"); // hide the bus result content
    jQuery('#address_result_content').css("display", "block"); // combine with address_result_content, same format
    jQuery('#address_result_content').css("min-height","0px");  
    jQuery('#bus_stop_arrival_time_result_content').css("display", "none");
    jQuery('#result_based_on').html(""); 

    jQuery.ajax({
        url: map_ajax_Path+"/map_ajaxlib.getBusInterChangeById."+busInterID+".html" ,
        success: function(data){
        jQuery('#address_result_content').html(data);  

        //zoom into map
        showOnMap( jQuery('#selected_busInter_longitude').html() ,jQuery('#selected_busInter_latitube').html() , 5);
        jQuery('.map_content_section').slideDown(400);  
        jQuery('#map_menu_loading').css("display" , "none");
      },
      error: function(data){
          jQuery('#map_menu_loading').css("display" , "none");
          
    	  window.location.reload(); 
       // alert("Sorry, our system is encountering high demand at the moment. Please try again later.");
        
          
      }
    }); 
    resetBusServiceOption();
    resetStationOption();
    }
}     



/*---------result for selected MRT/LRT station---------------*/
function showTrainStation(stationID){
    
    if (jQuery("#mrtlrt_option").val() != "default"){

        resetMap();

    showAnnouncement("normal_announcement");
    jQuery('#menu_option').val("other"); 
    jQuery("#map_menu_loading").css("display","block");
    jQuery('#bus_route_result_content').css("display", "none"); // hide the bus result content
    jQuery('#address_result_content').css("display", "block"); // combine with address_result_content, same format
    jQuery('#address_result_content').css("min-height","0px");  
    jQuery('#bus_stop_arrival_time_result_content').css("display", "none");
    jQuery('#result_based_on').html(""); 

    jQuery.ajax({
        url: map_ajax_Path+"/map_ajaxlib.getTrainLocationByTrainId."+stationID+".html" ,
        success: function(data){    
        jQuery('#address_result_content').html(data+"<br>Click <a href='http://www.smrt.com.sg/trains/train_timings.asp' target='_blank'>here</a> for first and last train times at the stations of East West Line, North South Line, Circle Line and Bukit Panjang LRT.<br>Click <a href='http://www.sbstransit.com.sg/transport/trpt_nel_1st.aspx'  target='_blank'>here</a>  for first and last train times at the stations of North East Line, Punggol LRT and Sengkang LRT.");  
        
        //zoom into map
        showOnMap( jQuery('#selected_station_longitude').html() ,jQuery('#selected_station_latitube').html() ,6 );
        jQuery('.map_content_section').slideDown(400);  
        jQuery('#map_menu_loading').css("display" , "none");

      },
      error: function(data){
    	  
    	  window.location.reload();
      //  alert("Sorry, our system is encountering high demand at the moment. Please try again later.");
        jQuery('#map_menu_loading').css("display" , "none");
          
      }
    });   
    resetBusServiceOption();
    resetBusInterChangeOption();
    }
}     


/*---------result list for Pack & Ride ---------------*/
function getParkAndRideCarpark(){

    addCustomOverlay("PnR", "http://"+location.host+"/kml/PnR.kml", true);

    
    showAnnouncement("parkAndRide_announcement");
    jQuery("#map_menu_loading").css("display","block");
    jQuery("#menu_option").val("PnR");
    jQuery('#bus_route_result_content').css("display", "none");
    jQuery('#address_result_content').css("display", "block"); // combine with address_result_content, same format
    jQuery('#address_result_content').css("min-height","0px");  
    jQuery('#result_based_on').html("Park & Ride Car Park Locations"); 
    
    jQuery.ajax({
        url: map_ajax_Path+"/map_ajaxlib.getParkAndRideCarpark.html" ,
        success: function(data){    
        jQuery('#address_result_content').html(data);  
        jQuery('.map_content_section').slideDown(400);  
        jQuery("#map_menu_loading").css("display","none"); 
        
     },
     error: function(data){
        alert("Sorry, our system is encountering high demand at the moment. Please try again later.");
        jQuery('#map_menu_loading').css("display" , "none");
    
     }
    });    


}


/*---------result list for Bus Stop with Arrival Panel ---------------*/
function showBusStopWithArrivalPanel(){

    jQuery("div#bus_stop_arrival_time_result_content").html("");

    addCustomOverlay("arrivaltime", "http://"+location.host+"/kml/arrivaltime.kml", true);

    showAnnouncement("busStopWithTimePanel_announcement");
    jQuery("#map_menu_loading").css("display","block");
    jQuery("#menu_option").val("arrivaltime_panel");
    jQuery('#bus_route_result_content').css("display", "none");
    jQuery('#address_result_content').css("display", "none"); 
    jQuery('#address_result_content').css("min-height","0px");  
    jQuery('#result_based_on').html("Bus Stops with Arrival Time Panel"); 
    jQuery("div#bus_stop_arrival_time_result_content").html("");
    
    jQuery.ajax({
        url: map_ajax_Path+"/map_ajaxlib.getBusStopWithPanel.html"  ,
        success: function(data){
        
        jQuery('#address_result_content').html(data);  
        jQuery('.map_content_section').slideDown(400);  
        jQuery("#map_menu_loading").css("display","none"); 
        jQuery('#academic_belt_view_all').html("");
        jQuery('#academic_belt_txt').html("");
        jQuery('#address_result_content').css("display", "block"); // combine with address_result_content, same format
        jQuery('#bus_stop_arrival_time_result_content').fadeIn(300); 
    
     },
     error: function(data){
        alert("Sorry, our system is encountering high demand at the moment. Please try again later.");
        jQuery('#map_menu_loading').css("display" , "none");
     }
    });  


}

function showArrivalResult(busStopCode){

    var arrivalFileUrl;
    
   arrivalFileUrl = "http://"+location.host+"/busarrival/"+busStopCode+".json";
    // arrivalFileUrl = "/apps/publictransport/components/page/map/46069.json";
    
    var backBtnActionvar =""; 
    if(jQuery("#menu_option").val() == "arrivaltime_belt"){ backBtnAction = "showBusStopAlongAcademicBelt()";  }
    if(jQuery("#menu_option").val() == "arrivaltime_panel"){ backBtnAction = "showBusStopWithArrivalPanel()";  }
    if(jQuery("#menu_option").val() == "other_bus_stops"){ backBtnAction = "showSpecialBusStoplist()";  }
    
    
    
    if(jQuery("#menu_option").val() != "arrivaltime_panel" && jQuery("#menu_option").val() != "arrivaltime_belt"  && jQuery("#menu_option").val() != "other_bus_stops"){ backBtnAction = "showBusStopWithArrivalPanel()";  }

    
	//hide other result if any
	jQuery("#premium_bus_detail_content").css("display" ,"none");
	jQuery("#shuttle_bus_detail_content").css("display" ,"none");
	jQuery("#bus_route_result_content").css("display" ,"none");
	jQuery("#address_result_content").css("display" ,"none");
	jQuery("#premium_bus_route_title").html("");
	jQuery("#shuttle_bus_route_title").html("");
	

    jQuery.ajax({
        url: arrivalFileUrl,
        dataType: 'json',
        success: function(data){
    	
    	
    	//if empty json
       if(data == "" || data == "null" || data == null   ){
    	   jQuery("div#address_result_content").css( "display","none");
           jQuery("div#bus_stop_arrival_time_result_content").css( "display","block");
       
           jQuery("div#bus_stop_arrival_time_result_content").html("<p align='center'><b>The current bus arrival information is not available.</b> <div class='centered_btn'><a class='back_btn' onclick='"+backBtnAction+"'>Back</a> </p>");
       }

        var busService;
        var arrNow;
        var arrLater;
        var arrNowDisFriendly;
        var arrLaterDisFriendly;
        var currentSeconds;
        var nextRefresh;
        var count = 1;
        var time = String(data.time);
        var dataTime_DATE = time.substring(0,8);
        
        var dataTime_HR = time.substring(9,11).replace(/^[0]+/g,""); // remove leading 0
        var dataTime_MIN = time.substring(11,13).replace(/^[0]+/g,"");// remove leading 0
        
    	if( time.substring(9,11) == "00" || time.substring(9,11) == ""){  dataTime_HR=0; }      
    	if( time.substring(11,13) == "00"||  time.substring(11,13) == ""){ dataTime_MIN =0; }  
       

        var dataTime_HR_MIN =   parseInt(dataTime_HR *60 ) +  parseInt(dataTime_MIN);
   
       
//-------formating the date/time for display  
        var d=new Date();
        var month=new Array(12);
        month["01"]="January";
        month["02"]="February";
        month["03"]="March";
        month["04"]="April";
        month["05"]="May";
        month["06"]="June";
        month["07"]="July";
        month["08"]="August";
        month["09"]="September";
        month["10"]="October";
        month["11"]="November";
        month["12"]="December";
        
        var displayDateTime;
        var dayUnit = "AM";
        if (  parseInt(time.substring(9,11)) > 12 ){dayUnit=" PM"; }
        time = time.substring(0,2)+" "+  month[time.substring(2,4)] +" "+time.substring(4,8) +" "+time.substring(9,11) +":"+time.substring(11,13);
        
        
//-------formating the date/time for display    
        
        var now = new Date();
        var nowHour=  now.getHours();
        var nowMin=  now.getMinutes();
        
        if (nowHour < 10 ){ nowHour = "0"+nowHour; }
        if (nowMin < 10 ){ nowMin = "0"+nowMin; }    
        var curTime_HR_MIN =   parseInt(nowHour*60)+  parseInt(nowMin);
        
        var nowDay=  now.getDate();
        var nowMonth=  now.getMonth()+1;
        var nowYear=  now.getFullYear();
        
        if (nowDay < 10 ){ nowDay = "0"+nowDay; }
        if (nowMonth < 10 ){ nowMonth = "0"+nowMonth; }
           
        timeDiff = parseInt(curTime_HR_MIN) - parseInt(dataTime_HR_MIN)  ;
      
        if (  ( dataTime_DATE != (nowDay+""+nowMonth+""+nowYear) )  || timeDiff > 10   ){  //more than 10 mins 
        count =0;   
       }
       
        jQuery('#address_result_content').fadeOut(300, function() {
    
            capIcon = "";
            
        	
            jQuery.get(map_ajax_Path+"/map_ajaxlib.html?busServiceId="+busStopCode+"&action=getBusStopByIdDiscapbilityFriendlyCheck"  , function(data) {
             
            	if (trim(data) == "false"){ 
                	
                    capIcon = "<div class='not_discapability_friendly_icon'></div>"; 
                }
                jQuery("#result_based_on").html("<div class='arrival_time_bus_stop_code'>Bus Stop Code : "+busStopCode+"</div> "+capIcon);
            }); 
            
            
        
            jQuery("div#address_result_content").html("");// clear content
                
            jQuery("#academic_belt_view_all").html("<a  onclick='"+backBtnAction+"'>View All</a>");
            jQuery("div#address_result_content").append("<div id='arrival_time_result'>");
            jQuery("div#address_result_content").append("<div id='arrival_time_result_time_display'> <a class='back_btn' onclick='"+backBtnAction+"'>Back</a> <div class='spacer'></div>  <div id='refresh_btn'><a class='back_btn'  onclick='showArrivalResult(\""+busStopCode+"\")'>Refresh</a></div>      <div id='timer'>Last Updated on "+time+"</div> </div>");
            jQuery("div#address_result_content").append("<div class='arrival_time_bus_col header'>Bus No.</div><div class='arrival_time_arriving_col header'>Arriving</div><div class='arrival_time_next_bus_col header'>Next Bus</div>");
            
            
            // no time arr data in the json file 
            if(data.info ==""){
         	   jQuery("div#address_result_content").css( "display","none");
                jQuery("div#bus_stop_arrival_time_result_content").css( "display","block");
                jQuery("div#bus_stop_arrival_time_result_content").html("<p align='center'><b>The current bus arrival information is not available.</b> <div class='centered_btn'><a class='back_btn' onclick='"+backBtnAction+"'>Back</a> </p>");
            }
            
            
            if (count != 0 ){ 
                
            jQuery.each(data.info,function(i,infoValue){
                busService = infoValue.bsvc;
                arrNow = infoValue.arr1;
                arrLater = infoValue.arr2;
                arrNowDisFriendly = infoValue.wc1;
                arrLaterDisFriendly = infoValue.wc2;
                arrNowCapIcon = "";
                arrLaterCapIcon = "";
              
               
                
                
                
                
                
            
                if (arrNowDisFriendly == 1 && arrNow != "" && arrNow != "N.A."){ arrNowCapIcon= "<div class='discapability_friendly_icon'></div>";  }
                if (arrLaterDisFriendly == 1 && arrNow != "" && arrNow != "N.A."){ arrLaterCapIcon= "<div class='discapability_friendly_icon'></div>";  }

                jQuery("div#address_result_content").append("<div class='arrival_time_divider'></div>");
                jQuery("div#address_result_content").append("<div class='arrival_time_bus_col'>"+busService+"</div>");
                 
                   arrNowTxt = arrNow+" Mins";
                   arrLaterTxt = arrLater+" Mins";
                   
                   if ( arrNow == 0 || arrNow.toLowerCase() == "arr" ) 
                   {  arrNowTxt ="Arr"; }

                   if ( arrNow != 0 && arrNow.toLowerCase() != "arr" &&  arrNow != "") 
                   {  arrNowTxt =arrNow+" Mins";  }
                   
                   if ( arrNow == "" || arrNow == "N.A." ){    
                       arrNowTxt ="N.A.";  
                   }
                  
                   if ( arrLater != 0 && arrLater.toLowerCase() != "arr" &&  arrLater != "") 
                   {  arrLaterTxt =arrLater+" Mins";  }
                      
                   
                   if ( arrLater == "" || arrLater == 0 || arrLater == "N.A." ){      
                       arrLaterTxt ="N.A.";  
                   }
            
                jQuery("div#address_result_content").append("<div class='arrival_time_arriving_col'><div class='ar_txt'>"+arrNowTxt+"  </div>"+arrNowCapIcon+"</div> ");
                jQuery("div#address_result_content").append("<div class='arrival_time_next_bus_col'><div class='ar_txt'>"+arrLaterTxt+"  </div>"+arrLaterCapIcon+" </div> ");
                jQuery("div#address_result_content").append("<div class='arrival_time_divider'></div>");
                jQuery("div#address_result_content").append("<div class='br_line'></div>");
            
                jQuery('#address_result_content').fadeIn(300);

            });
            
            } else {    
                
                jQuery("div#bus_stop_arrival_time_result_content").css( "display","block");
                
                jQuery("div#bus_stop_arrival_time_result_content").html("<p align='center'><b>The current bus arrival information is not available.</b> <div class='centered_btn'><a class='back_btn'  onclick='"+backBtnAction+"'>Back</a> </p>");
                }
            
            
            jQuery("div#address_result_content").append("</div>");
        });

    },
    error: function(data){
        jQuery("div#address_result_content").css( "display","none");
        jQuery("div#bus_stop_arrival_time_result_content").css( "display","block");
    
        jQuery("div#bus_stop_arrival_time_result_content").html("<p align='center'><b>The current bus arrival information is not available.</b> <div class='centered_btn'><a class='back_btn' onclick='"+backBtnAction+"'>Back</a> </p>");
         }
    
    });  



}





/*---------result list for Bus Stop along Academic Belt---------------*/
function showBusStopAlongAcademicBelt(){

    addCustomOverlay("arrivaltime", "http://"+location.host+"/kml/arrivaltime.kml", true);

    jQuery("div#bus_stop_arrival_time_result_content").html("");
    showAnnouncement("busStopAlongAcadamicBelt_announcement");
    jQuery("#menu_option").val("arrivaltime_belt");
    jQuery("#map_menu_loading").css("display","block");
    jQuery('#bus_route_result_content').css("display", "none");
    jQuery('#address_result_content').css("display", "block"); // combine with address_result_content, same format
    jQuery('#address_result_content').css("min-height","50px");  
    jQuery('#academic_belt_txt').css("display", "block");
    //jQuery('#academic_belt_txt').html("Academic Belt");
    jQuery('#result_based_on').html("Bus Stops along Academic Belt"); 

    jQuery.ajax({
        url: map_ajax_Path+"/map_ajaxlib.getBusStopAlongAcademicBelt.html"  ,
        success: function(data){    
        jQuery('#address_result_content').html(data);  
        jQuery('.map_content_section').slideDown(400);  
        jQuery("#map_menu_loading").css("display","none"); 
     },
     error: function(data){
      alert("Sorry, our system is encountering high demand at the moment. Please try again later.");
      jQuery('#map_menu_loading').css("display" , "none");  
     }
    });   
}

/*---------Change menu option (public transport/ premium bus)---------------*/
function changeMenu(thisElement){

    jQuery('#academic_belt_view_all').html("");
    jQuery("div#bus_stop_arrival_time_result_content").html("");
    
    if( thisElement.value == "other_bus_stops" ){ 
    	showSpecialBusStoplist();
    }
    
    if( thisElement.value == "premium" ){ 
        showPremiumMenu();
    }

    if( thisElement.value == "shuttle" ){ 
        showShuttleMenu();
    }
    
    if( thisElement.value == "other" ){ 
        jQuery('#address_result_content').html("");
        jQuery('#result_based_on').html(""); 
        hidePremiumMenu();
        hideShuttleMenu();
        resetBusServiceOption();
        resetBusInterChangeOption();
        resetStationOption();
        
        showAnnouncement("normal_announcement");
        
        resetMap();
    }

    if( thisElement.value == "PnR" ){ 
        hidePremiumMenu();
        hideShuttleMenu();
        
        
        resetMap();
        getParkAndRideCarpark();

        resetBusServiceOption();
        resetBusInterChangeOption();
        resetStationOption();

    }

    if( thisElement.value == "arrivaltime_panel" ){ 
        hidePremiumMenu();
        hideShuttleMenu();
        
        
        resetMap();
        showBusStopWithArrivalPanel();

        resetBusServiceOption();
        resetBusInterChangeOption();
        resetStationOption();

    } 

    if( thisElement.value == "arrivaltime_belt" ){ 
        hidePremiumMenu();
        hideShuttleMenu();
        
        
        resetMap();
        showBusStopAlongAcademicBelt();

        resetBusServiceOption();
        resetBusInterChangeOption();
        resetStationOption();
    } 
}      








/*------------Shuttle Bus function-----------------------*/

function showShuttleMenu(){
    resetMap();
    showAnnouncement("shuttleBusService_announcement");
    jQuery('#academic_belt_txt').css("display", "none");
    jQuery('#shuttle_option').animate({"left": "0px"} , 500);  
    jQuery('.map_content_section').slideUp(400);
    
    jQuery('#premium_bus_route_list_content').css("display","none");
    jQuery('#premium_bus_route_list_content').css("min-height","0px");
    

    jQuery('#address_result_content').html("");
    jQuery('#bus_route_result_content').html("");
    jQuery('#bus_stop_arrival_time_result_content').html("");
    jQuery('#result_based_on').html(""); 
    
    jQuery('#shuttle_bus_title').fadeIn(500);
    jQuery('.map_search').fadeOut(500);

    resetBusServiceOption();
    resetBusInterChangeOption();
    resetStationOption();

    jQuery('#shuttle_bus_detail_content').css("display","block");
    jQuery('#shuttle_bus_detail_content').css("min-height","450px");
    
    jQuery('#shuttle_bus_route_list_content_filtered').css("display", "none");
    jQuery('#shuttle_bus_route_list_content_filtered').css("min-height","0px"); 
    
    jQuery('#shuttle_bus_route_list_content').css("display","block");
    jQuery('#shuttle_bus_route_list_content').css("min-height","450px");
    
    jQuery('#shuttle_bus_route_detail_content').css("display","none");
    jQuery('#shuttle_bus_route_detail_content').css("min-height","0px");
    
    jQuery('#shuttle_bus_route_matched_content').css("display","none");
    jQuery('#shuttle_bus_route_matched_content').css("min-height","0px");

    jQuery('#hidemap_btn_shuttle').css("display", "none");
    jQuery('#showmap_btn_shuttle').css("display", "block");
    
    jQuery('#shuttle_bus_route_title').html("Shuttle Bus Category : All");
    jQuery('#shuttle_bus_route_title').css("display","block");
    
}


function instantShowShuttleMenu(){
    resetMap();
    showAnnouncement("shuttleBusService_announcement");
    jQuery('#academic_belt_txt').css("display", "none");
    jQuery('#shuttle_option').animate({"left": "0px"} , 1);  
    jQuery('.map_content_section').slideUp(1);
    
    jQuery('#premium_bus_route_list_content').css("display","none");
    jQuery('#premium_bus_route_list_content').css("min-height","0px");
    
    jQuery('#shuttle_bus_route_title').html("Shuttle Bus Category : All");
    jQuery('#shuttle_bus_route_title').css("display","block");

    jQuery('#address_result_content').html("");
    jQuery('#bus_route_result_content').html("");
    jQuery('#bus_stop_arrival_time_result_content').html("");
    jQuery('#result_based_on').html(""); 
    
    jQuery('#shuttle_bus_title').css("display","block");
    jQuery('.map_search').css("display","none");

    resetBusServiceOption();
    resetBusInterChangeOption();
    resetStationOption();

    jQuery('#shuttle_bus_detail_content').css("display","block");
    jQuery('#shuttle_bus_detail_content').css("min-height","450px");
    
    jQuery('#shuttle_bus_route_list_content').css("display","block");
    jQuery('#shuttle_bus_route_list_content').css("min-height","450px");
    
    jQuery('#shuttle_bus_route_detail_content').css("display","none");
    jQuery('#shuttle_bus_route_detail_content').css("min-height","0px");
    
    jQuery('#shuttle_bus_route_matched_content').css("display","none");
    jQuery('#shuttle_bus_route_matched_content').css("min-height","0px");

    jQuery('#hidemap_btn_shuttle').css("display", "none");
    jQuery('#showmap_btn_shuttle').css("display", "block");
    
}


function hideShuttleMenu(){

    jQuery('#shuttle_bus_title').fadeOut(400);
    jQuery('.map_content_section').slideDown(400);

    jQuery('#shuttle_bus_detail_content').css("display","none");
    jQuery('#shuttle_bus_detail_content').css("min-height","0px"); 
    jQuery('#shuttle_bus_route_list_content_filtered').css("display", "none");
    jQuery('#shuttle_bus_route_list_content_filtered').css("min-height","0px"); 
    
    jQuery('#shuttle_option').animate({"left": "900px"} , 500); 

    jQuery('#shuttle_bus_route_title').css("display", "none");
    jQuery('#academic_belt_view_all').html("");
    jQuery('#hidemap_btn_shuttle').css("display", "none");
    jQuery('#showmap_btn_shuttle').css("display", "none");

    jQuery('.map_search').fadeIn(500);
    resetMap();
} 



function showShuttleBusRouteDetail( shuttlebusServiceId ){


    ecasped_shuttlebusServiceId = escape(shuttlebusServiceId);
    jQuery("body").css("cursor", "wait");


    jQuery.ajax({
        url: map_ajax_Path+"/map_ajaxlib.getShuttleBusRouteById."+trim(ecasped_shuttlebusServiceId)+".html"  , 
        success: function(data){

        jQuery('#shuttle_bus_route_list_content').fadeOut(400, function() {
            jQuery('#shuttle_bus_route_matched_content').fadeOut(200, function() {
            
            jQuery('#result_based_on').html("");
            jQuery('#bus_route_result_content').html("");
            jQuery('#shuttle_bus_route_list_content').css("display", "none");
            jQuery('#shuttle_bus_route_list_content_filtered').css("display", "none");
            
            
            jQuery('#address_result_content').html("");
            jQuery('#shuttle_bus_route_title').css("display", "block");

            jQuery('#academic_belt_view_all').html("<a href='#' onclick='resetShuttleBusRouteList()' > View All</a>");
        
            jQuery('#hidemap_btn_shuttle').css("display", "none");
            jQuery('#shuttle_bus_route_detail_content').html(data);
            jQuery('#shuttle_bus_route_detail_content').css("min-height","200px");
            jQuery('#shuttle_bus_route_detail_content').fadeIn(300);
            
            jQuery('#shuttle_bus_route_title').html("Shuttle Bus Service : "+jQuery('#shuttle_bus_name').html()  );
            
            window.scrollTo(0,0);
            jQuery("body").css("cursor", "auto");
            jQuery('.map_content_section').slideUp(400);
            
            
            jQuery('#hidemap_btn_shuttle').css("display", "none");
            jQuery('#showmap_btn_shuttle').css("display", "block");
            });
        });
     },
     error: function(data){
      alert("Sorry, our system is encountering high demand at the moment. Please try again later.");
    jQuery("body").css("cursor", "auto");
     }
        
    } ); 


}

function resetShuttleBusRouteList(){
    jQuery('.map_content_section').slideUp(400);
    jQuery('#showmap_btn_shuttle').css("display", "block");
    
    
    jQuery('#shuttle_bus_route_detail_content').fadeOut(400, function() {
        jQuery('#shuttle_bus_route_matched_content').fadeOut(200, function() {
        jQuery('#shuttle_bus_route_matched_content').html("");
        jQuery('#shuttle_bus_route_list_content').fadeIn(200);
        jQuery('#shuttle_bus_route_list_content_filtered').fadeIn(200);
        
        jQuery('#result_based_on').html(""); 
        jQuery('#hidemap_btn_shuttle').css("display", "none");
        jQuery('#shuttle_bus_route_title').html("");
        jQuery('#academic_belt_view_all').html("");
        jQuery('#shuttleBusKeywords').val("Enter your keyword(s)");
        jQuery('#shuttleBusCategory').val("All");
        });
    });

}



function submitShuttleBusSearch(){


    var shuttleBusKeywords = trim(jQuery('#shuttleBusKeywords').val());
    var shuttleBusCategory = trim(jQuery('#shuttleBusCategory').val());

if (shuttleBusKeywords == "Enter your keyword(s)" || shuttleBusKeywords == ""  ) {
    alert("Please enter your Keyword(s) to search");
}else{
    jQuery("#map_menu_loading").css("display","block");

    jQuery.ajax({
        url: map_ajax_Path+"/map_ajaxlib.html?shuttleBusKeywords="+shuttleBusKeywords+"&shuttleBusCategory="+shuttleBusCategory+"&action=getShuttleBusesByKeywordsAndCategory"  , 
        success: function(data){ 
        
        jQuery('.map_content_section').slideUp(400);
        jQuery('#academic_belt_view_all').html("<a href='#' onclick='resetShuttleBusRouteList()' > View All</a>");
        
        jQuery('#hidemap_btn').css("display", "none");
        jQuery('#showmap_btn').css("display", "block"); 
        jQuery('#shuttle_bus_route_title').html("");
                
        jQuery('#shuttle_bus_route_list_content').fadeOut(400, function() {
        jQuery('#shuttle_bus_route_detail_content').fadeOut(200, function() {
            
            jQuery('#shuttle_bus_route_list_content_filtered').css("display", "none");
            
        jQuery('#shuttle_bus_detail_content').css("min-height", "250px");
        jQuery('#shuttle_bus_route_matched_content').html(data);
        jQuery('#shuttle_bus_route_matched_content').fadeIn(400);
        
        jQuery('#hidemap_btn_shuttle').css("display", "none");
        jQuery('#showmap_btn_shuttle').css("display", "block");
        jQuery("#map_menu_loading").css("display","none");
        }); 
        }); 
     },
     error: function(data){
      alert("No result found.");
    jQuery("#map_menu_loading").css("display","none");
     }  
    } ); 
}
}




function getShuttleBusByCategory(){
	
var shuttleBusKeywords = trim(jQuery('#shuttleBusKeywords').val());
var category = jQuery("#shuttleBusCategory").val();
var categoryTxt ="";

if ( shuttleBusKeywords == "" || shuttleBusKeywords == "Enter your keyword(s)" ) {

if(category != "All" ){
    jQuery("#map_menu_loading").css("display", "block");//show loading
    
    
jQuery.ajax({
    url: map_ajax_Path+"/map_ajaxlib.getShuttleBusesByCategory."+category+".html"  ,
    success: function(data){ 
    
    jQuery("#map_menu_loading").css("display", "none");//hide loading
	
    jQuery('#shuttle_bus_route_list_content').css("display", "none");
    
 
  if(category =="HOSPITAL_SHUTTLE" ){ categoryTxt= "Shuttle Bus Category : Hospitals";  }
  if(category =="POI_SHUTTLE" ){ categoryTxt= "Shuttle Bus Category : Tourist Attractions";  }

    jQuery('#shuttle_bus_route_title').css("display","block");
    jQuery('#shuttle_bus_route_title').html(categoryTxt );
    
    jQuery('#academic_belt_view_all').css("display","block");
    jQuery('#academic_belt_view_all').html("<a href='#' onclick='getAllShuttleBus()'>View All</a>");

    jQuery('#shuttle_bus_route_list_content_filtered').css("display", "block");
    jQuery('#shuttle_bus_route_list_content_filtered').html(data);
    
    

    jQuery('#shuttle_bus_route_list_content').css("display","none");
    jQuery('#shuttle_bus_route_list_content').css("min-height","0px");
    
    jQuery('#shuttle_bus_route_detail_content').css("display","none");
    jQuery('#shuttle_bus_route_detail_content').css("min-height","0px");
    
    jQuery('#shuttle_bus_route_matched_content').css("display","none");
    jQuery('#shuttle_bus_route_matched_content').css("min-height","0px");
    
    
    

},
error: function(data){
      alert("No result found.");
      jQuery("#map_menu_loading").css("display", "none");//show loading
    jQuery("#map_menu_loading").css("display","none");
}   
} ); 

}else {
		getAllShuttleBus();
		
	}

}else{
	
	 submitShuttleBusSearch();

}



}



function getAllShuttleBus(){
    
	var category = jQuery("#shuttleBusCategory").val();
	if ( category == "All" ){
    jQuery("#shuttleBusCategory").val("All");
    jQuery('#shuttle_bus_route_title').html("Shuttle Bus Category : All");
    jQuery('#shuttle_bus_route_title').css("display","block");
	}
     
    jQuery('#academic_belt_view_all').html("");
    jQuery('#academic_belt_view_all').css("display","none");


    
    jQuery('#shuttle_bus_route_list_content_filtered').css("display","none");
    jQuery('#shuttle_bus_route_list_content').css("display","block");
}





/*------------Premium Bus function-----------------------*/


function showPremiumMenu(){
    resetMap();
  
    
    jQuery('#academic_belt_view_all').html("<a href='/content/dam/publictransport/pdf/PBS Summary Table.pdf' target='parent'>Click here for Operator's details </a>");
    
    showAnnouncement("premiumBusService_announcement");
    jQuery('#academic_belt_txt').css("display", "none");
    jQuery('#premium_option').animate({"left": "0px"} , 500);  
    jQuery('.map_content_section').slideUp(400);
    jQuery('#bus_route_result_content').html("");
    jQuery('#premium_bus_title').fadeIn(500);
    jQuery('.map_search').fadeOut(500);

    resetBusServiceOption();
    resetBusInterChangeOption();
    resetStationOption();


    
    jQuery('#bus_route_result_content').html("");
    jQuery('#bus_route_result_content').css("min-height","0px");
    jQuery('#address_result_content').html("");
    jQuery('#address_result_content').css("min-height","0px");
    jQuery('#result_based_on').html(""); 
    jQuery('#premium_bus_route_list_content').css("display","block");
    jQuery('#premium_bus_route_list_content').css("min-height","450px");
    jQuery('#premium_bus_detail_content').css("display","block");
    
    jQuery('#hidemap_btn').css("display", "none");
    jQuery('#showmap_btn').css("display", "block");
} 

function instantShowPremiumMenu(){
	
	jQuery('#academic_belt_view_all').html("<a href='/content/dam/publictransport/pdf/PBS Summary Table.pdf' target='parent'>Click here for Operator's details </a>");
	   
	
    showAnnouncement("premiumBusService_announcement");
    jQuery('#academic_belt_txt').css("display", "none");

    jQuery('#premium_option').css("left", "0px");
    jQuery('.map_content_section').slideUp(1);
    jQuery('#premium_bus_title').css("display","block");
    jQuery('.map_search').css("display","none");

    jQuery('#bus_route_result_content').html("");
    jQuery('#bus_route_result_content').css("min-height","0px");
    jQuery('#address_result_content').html("");
    jQuery('#address_result_content').css("min-height","0px");
    jQuery('#result_based_on').html(""); 
    jQuery('#premium_bus_route_list_content').css("display","block");
    jQuery('#premium_bus_route_list_content').css("min-height","450px");
    jQuery('#hidemap_btn').css("display", "none");
    jQuery('#showmap_btn').css("display", "block");
}


function hidePremiumMenu(){

    jQuery('#premium_bus_title').fadeOut(400);
    jQuery('.map_content_section').slideDown(400);
    jQuery('#address_result_content').css("min-height","0px"); 

    jQuery('#premium_bus_route_list_content').css("display","none");
    jQuery('#premium_bus_route_detail_content').css("display","none");
    jQuery('#premium_bus_route_matched_content').css("display","none");
    jQuery('#premium_option').animate({"left": "900px"} , 500); 

    jQuery('#premium_bus_route_title').css("display", "none");
    jQuery('#academic_belt_view_all').html("");
    jQuery('#hidemap_btn').css("display", "none");
    jQuery('#showmap_btn').css("display", "none");

    jQuery('.map_search').fadeIn(500);
    jQuery('#premium_bus_detail_content').css("min-height","0px");
    jQuery('#originPBS').val("Enter your origin");
    jQuery('#destinationPBS').val("Enter your Destination");
    resetMap();
} 

function showHideMapBtn(){

    jQuery('#hidemap_btn').css("display", "block");
    jQuery('#showmap_btn').css("display", "none");
    
    jQuery('#hidemap_btn_shuttle').css("display", "block");
    jQuery('#showmap_btn_shuttle').css("display", "none");
    jQuery('.map_content_section').slideDown(400);

}






function showPremiumBusRouteDetail( busServiceId , busServiceNumber){

	// if no proper SvrNo
	if (busServiceNumber.substring(0,1) =="-"  ){ busServiceNumber ="-";  }
	
	
    ecasped_busServiceId = escape(busServiceId);
    jQuery("body").css("cursor", "wait");

    jQuery.ajax({
        url: map_ajax_Path+"/map_ajaxlib.html?busServiceId="+trim(ecasped_busServiceId)+"&action=getPremiumBusRoute"  ,
        success: function(data){ 

        jQuery('#premium_bus_route_detail_content').css("min-height","380px");
        
        jQuery('#premium_bus_route_list_content').fadeOut(400, function() {
            jQuery('#premium_bus_route_matched_content').fadeOut(200, function() {
                
            jQuery('#result_based_on').html("");
            jQuery('#bus_route_result_content').html("");
            jQuery('#address_result_content').html("");
            jQuery('#premium_bus_route_title').css("display", "block");
            jQuery('#premium_bus_route_title').html(busServiceNumber +" : "+busServiceId );
            jQuery('#academic_belt_view_all').html("<a href='#' onclick='resetPremiumBusRouteList()' style='float: right;' > View All</a><br><a href='/content/dam/publictransport/pdf/PBS Summary Table.pdf' target='parent'>Click here for Operator's details </a>");
            jQuery('#premium_bus_route_matched_content').html("");
            jQuery('#hidemap_btn').css("display", "none");
            jQuery('#premium_bus_route_detail_content').html(data);
            jQuery('#premium_bus_route_detail_content').fadeIn(300);

            window.scrollTo(0,0);
            jQuery("body").css("cursor", "auto");
            jQuery('.map_content_section').slideUp(400);
            });
        });
        
     },
     error: function(data){
      alert("Sorry, our system is encountering high demand at the moment. Please try again later.");
    jQuery("body").css("cursor", "auto");
     }  
    } ); 


}

function resetPremiumBusRouteList(){
    jQuery('.map_content_section').slideUp(400);
    jQuery('#showmap_btn').css("display", "block");

    jQuery('#premium_bus_route_detail_content').fadeOut(400, function() {
    	
        jQuery('#premium_bus_route_matched_content').html("");
        jQuery('#premium_bus_route_list_content').fadeIn(200);
        jQuery('#result_based_on').html(""); 
        jQuery('#hidemap_btn').css("display", "none");
        jQuery('#premium_bus_route_title').html("");
        jQuery('#academic_belt_view_all').html("<a href='/content/dam/publictransport/pdf/PBS Summary Table.pdf' target='parent'>Click here for Operator's details </a>");
        
    });

}




/*------------Premium Bus Search function-----------------------*/
function retrieveDataPBS( inputText , outputBox) // inputText is keyword, outputBox is the ID of the suggestion box
{  
	/*
    input = trim( inputText );
    if ( trim(input).length >= 3   ){
    	
        jQuery('#map_submenu').css("height","300px");
        populateDataPBS( input, outputBox );
    }
    if ( input.length < 3 ){  
        hideSuggestionBox();
    }
    */
}  


function populateDataPBS( input , outputBox ) { 
/*
    input = trim(input );

    if (outputBox == "pbs_suggestion_box_origin"){   
        searchType = "PremiumBus_origin";
    }
    if (outputBox == "pbs_suggestion_box_destination"){   
        searchType = "PremiumBus_destination";
    }

    latestsuggestionPBS = Math.floor(Math.random()*10);
    jQuery.ajax({
        url:    map_ajax_Path+"/map_ajaxlib.html?keyword="+input+"&searchType="+searchType+"&keywordSynId="+latestsuggestionPBS+"&action=getAddressByKeywords",
        success: function(result) {
        jQuery('#pbs_suggestion_box_origin').html("");
        jQuery('#pbs_suggestion_box_destination').html("");
        jQuery('#'+outputBox).html( result);  
        
        if ( jQuery('#synId').html() == latestsuggestionPBS ){
            jQuery('#'+outputBox).slideDown(300);
        }
    },
    async: true
    });          
*/
} 

function selectSuggestionPBS(thisElement , searchType)  
{ 
    if (searchType == "PremiumBus_origin"){   
        jQuery("#originPBS").val( jQuery(thisElement).html() );
    }
    if (searchType == "PremiumBus_destination"){   
        jQuery("#destinationPBS").val( jQuery(thisElement).html() );
    }



}

function hideSuggestionBoxPBS()
{ 

    setTimeout( 
            function(){
                jQuery('#pbs_suggestion_box_origin').slideUp(500 ,
                    function(){
                    jQuery('#pbs_suggestion_box_origin').html(""); 
                    jQuery('#map_submenu').css("height","50px");
                });
                 
                } 
            ,300 );
    
    setTimeout( 
            function(){
                jQuery('#pbs_suggestion_box_destination').slideUp(500 ,
                    function(){
                    jQuery('#pbs_suggestion_box_destination').html("");  
                    jQuery('#map_submenu').css("height","50px");
                });
                 
                } 
            ,300 );
    
    suggestion_hightligh_counter = -1; 

} 



function submitPBSsearch(){
    latestsuggestionPBS = "";
    hideSuggestionBoxPBS();

    var originPBS = trim(jQuery('#originPBS').val());
    var destinationPBS = trim(jQuery('#destinationPBS').val());
    jQuery('#premium_bus_route_matched_content').css("display","block");
    jQuery('#showmap_btn').css("display", "block");

    // check for postal code, if there is, submit only postal code
    var re = new RegExp(/\(\d\d\d\d\d\d\)+$/g);
    if (originPBS.match(re)){
        originPBS  = ""+re.exec(originPBS);
        originPBS = originPBS.replace(/\((\d{6})\)$/g, "$1");
    }
    if (destinationPBS.match(re)){
        destinationPBS  = ""+re.exec(destinationPBS);
        destinationPBS = destinationPBS.replace(/\((\d{6})\)$/g, "$1");

    }   
    
    if (originPBS == "Enter your origin"  ){ originPBS = ""; }
    if (destinationPBS == "Enter your Destination"  ){ destinationPBS = ""; }
    
    
 //   if (  originPBS != "" &&  originPBS != "Enter your origin" && destinationPBS != ""  &&  destinationPBS != "Enter your Destination") {
    if ( ( originPBS != "" &&  originPBS != "Enter your origin"  )  || (destinationPBS != ""  &&  destinationPBS != "Enter your Destination")  ) {

        jQuery('#map_menu_loading').css("display" ,"block");
         jQuery.ajax({
            url: map_ajax_Path+"/map_ajaxlib.html?origin="+originPBS+"&destination="+destinationPBS+"&action=searchPremiumBusService" ,
            success: function(data){

            jQuery('.map_content_section').slideUp(400);
            
            jQuery('#hidemap_btn').css("display", "none");
            jQuery('#academic_belt_view_all').html("<a href='#' onclick='resetPremiumBusRouteList()' style='float: right;' > View All</a><br><a href='/content/dam/publictransport/pdf/PBS Summary Table.pdf' target='parent'>Click here for Operator's details </a>");
            jQuery('#premium_bus_route_title').html("Premium Bus Service between "+jQuery('#originPBS').val()+" and "+ jQuery('#destinationPBS').val() +".");

            jQuery('#premium_bus_detail_content').css("min-height","400px");
            
            jQuery('#premium_bus_route_detail_content').fadeOut(400, function() {
                jQuery('#premium_bus_route_list_content').fadeOut(200, function() {
                            
                    jQuery('#map_menu_loading').css("display" ,"none");
                    jQuery('#premium_bus_route_matched_content').html(data);
                    jQuery('#premium_bus_route_matched_content').fadeIn(400);
                }); 
            }); 
            
        },
        error: function(data){
          alert("No result found.");

          jQuery('#map_menu_loading').css("display" , "none");
      }
    });  
    
   }else{
         
       alert("Please enter Origin/Destination to begin the search.");

    }


}





/*---------------------------special bus stop list------------------------*/

function showSpecialBusStoplist(){
    resetMap();
    

    addCustomOverlay("arrivaltime", "http://"+location.host+"/kml/arrivaltime.kml", true);

    jQuery("div#bus_stop_arrival_time_result_content").html("");
    
    showAnnouncement("none");
    jQuery("#menu_option").val("other_bus_stops");
    jQuery("#map_menu_loading").css("display","block");
    jQuery('#bus_route_result_content').css("display", "none");
    jQuery('#address_result_content').css("display", "block"); // combine with address_result_content, same format
    jQuery('#address_result_content').css("min-height","50px");  
    jQuery('#academic_belt_txt').css("display", "block");

    jQuery('#result_based_on').html("Other Bus Stops"); 

    jQuery.ajax({
        url: map_ajax_Path+"/map_ajaxlib.getSpecialBusStop.html"  ,
        success: function(data){    
        jQuery('#address_result_content').html(data);  
        jQuery('.map_content_section').slideDown(400);  
        jQuery("#map_menu_loading").css("display","none"); 
     },
     error: function(data){
      alert("Sorry, our system is encountering high demand at the moment. Please try again later.");
      jQuery('#map_menu_loading').css("display" , "none");  
     }
    });  


}















/*------------reset function-----------------------*/

function resetBusServiceOption(){
    
    jQuery("#busservice_option").val("default");
}

function resetBusInterChangeOption(){
    jQuery("#businter_option").val("default");
}

function resetStationOption(){
    jQuery("#mrtlrt_option").val("default");
}

function resetMenuOption(){
    showAnnouncement("normal_announcement");
    jQuery('#menu_option').val("other");
}

function hidemap(){

    jQuery('.map_content_section').slideUp(400)
    jQuery('#hidemap_btn').css("display", "none");
    jQuery('#showmap_btn').css("display", "block");
    jQuery('#hidemap_btn_shuttle').css("display", "none");
    jQuery('#showmap_btn_shuttle').css("display", "block");
}

function showmap(){
    jQuery('.map_content_section').slideDown(400);
    jQuery('#hidemap_btn').css("display", "block");
    jQuery('#showmap_btn').css("display", "none");
    jQuery('#hidemap_btn_shuttle').css("display", "block");
    jQuery('#showmap_btn_shuttle').css("display", "none");  
}




/*------------Announcement function-----------------------*/
function showAnnouncement( announcementId ){

    jQuery('#normal_announcement').removeClass('show_announcement');
    jQuery('#normal_announcement').addClass('hide_announcement');

    jQuery('#premiumBusService_announcement').removeClass('show_announcement');
    jQuery('#premiumBusService_announcement').addClass('hide_announcement');

    jQuery('#parkAndRide_announcement').removeClass('show_announcement');
    jQuery('#parkAndRide_announcement').addClass('hide_announcement');

    jQuery('#busStopAlongAcadamicBelt_announcement').removeClass('show_announcement');
    jQuery('#busStopAlongAcadamicBelt_announcement').addClass('hide_announcement');

    jQuery('#busStopWithTimePanel_announcement').removeClass('show_announcement');
    jQuery('#busStopWithTimePanel_announcement').addClass('hide_announcement');

    jQuery('#shuttleBusService_announcement').removeClass('show_announcement');
    jQuery('#shuttleBusService_announcement').addClass('hide_announcement');
    
    jQuery('#'+announcementId).removeClass('hide_announcement');
    jQuery('#'+announcementId).addClass('show_announcement');

}


/*------------General function-----------------------*/


function showOnMapWithBusRoute( longitude , latitude ) {
    
    doMapMoveLonLat(103.85, 1.35 , 0 , true);
    removeCustomOverlay("PnR");
    removeCustomOverlay("arrivaltime");
    
    jQuery('.map_content_section').slideDown(400);
    doMapGoToLonLat(longitude, latitude, 6);
    hideSuggestionBox(); 
    scroll(0,0);

}

function showOnMap( longitude , latitude ) {
    resetMap();
    jQuery('.map_content_section').slideDown(400);
    doMapGoToLonLat(longitude, latitude, 6);
    hideSuggestionBox(); 
    scroll(0,0);
    
//  jQuery('html,body').animate({
    //  scrollTop: 0
    //  }, 1000);
}

function showOnMap(longitude , latitude,  zoom ) {
    resetMap();
    jQuery('.map_content_section').slideDown(400);
    doMapGoToLonLat(longitude, latitude, 6);
    hideSuggestionBox(); 
    scroll(0,0);
    //jQuery('html,body').animate({  // not work in ie 7
    //  scrollTop: 0
    //  }, 1000);
}    

function onClickClearTextBox(input , originTxt){
    if (input.value == originTxt ) {
        input.value = "";   
    }   
}

function onBlurClearTextBox(input , originTxt){
    if (input.value == "" ) {
        input.value = originTxt;    
    }   
}

function trim(stringToTrim) {
    stringToTrim = stringToTrim.replace(/^\s+|\s+$/g ,"");
    return stringToTrim;
}

function showCurrentDate() { //  dd/mm/yyyy
    var currentDate=new Date();
    date = currentDate.getDay() +"/"+ (currentDate.getMonth()+1) +"/"+ currentDate.getFullYear();
    return date;
}

function showCurrentTime() {
    var currentDate = new Date();
    var hours = currentDate.getHours();
    var minutes = currentDate.getMinutes();
    var seconds = currentDate.getSeconds();

    if (minutes < 10){
        minutes = "0" + minutes;
    }
    if (seconds < 10){
        seconds = "0" + seconds;
    }

    time = hours + ":" + minutes +":"+seconds+" ";

    if(hours > 11){
        time += "PM";
    } else {
        time += "AM";
    }
    return time;
}



function launchResoureFile( filepath){

    window.open("http://"+window.location.host+filepath,'Download');
}



function resetMap(){
	 // jQuery("#map").html("");
   // map_init();
   doMapMoveLonLat(103.85, 1.35 , 0 , true);
    removeCustomOverlay("PnR");
   removeCustomOverlay("arrivaltime");
    objBusRoutes.clear();

}













/*

function showPBSroute( button, content  ){
    
if ( button== "pbs_route_1"){
    jQuery("#pbs_route_1").css("backgroundColor" , "#cccccc");  
    jQuery("#pbs_route_2").css("backgroundColor" , "#ffffff");
    jQuery("#pbs_route_3").css("backgroundColor" , "#ffffff");
}
if ( content== "pbs_route_1_content"){
    jQuery("#pbs_route_1_content").css("display" , "block");    
    jQuery("#pbs_route_2_content").css("display" , "none");
    jQuery("#pbs_route_3_content").css("display" , "none");
}


if ( button== "pbs_route_2"){
    jQuery("#pbs_route_2").css("backgroundColor" , "#cccccc");  
    jQuery("#pbs_route_1").css("backgroundColor" , "#ffffff");
    jQuery("#pbs_route_3").css("backgroundColor" , "#ffffff");
}
if ( content== "pbs_route_2_content"){
    jQuery("#pbs_route_2_content").css("display" , "block");    
    jQuery("#pbs_route_1_content").css("display" , "none");
    jQuery("#pbs_route_3_content").css("display" , "none");
}

if ( button== "pbs_route_3"){
    jQuery("#pbs_route_3").css("backgroundColor" , "#cccccc");  
    jQuery("#pbs_route_2").css("backgroundColor" , "#ffffff");
    jQuery("#pbs_route_1").css("backgroundColor" , "#ffffff");
}
if ( content== "pbs_route_3_content"){
    jQuery("#pbs_route_3_content").css("display" , "block");    
    jQuery("#pbs_route_2_content").css("display" , "none");
    jQuery("#pbs_route_1_content").css("display" , "none");
}





}


*/



















var mrtTripAdded = false;

var DFC_page_path ="/content/publictransport/en/homepage/eServices" ;

var DFC_ajax_path ="/content/publictransport/en/homepage/Ajax";
		
function changeFareType(){
	
	if ( jQuery("#mode_type_select").val() != "" ){
		jQuery("#fare_type_select option:first").attr("disabled" ,"disabled");
	}
	if ( jQuery("#trip1").html() != ""){
		if (confirm("Changing the Fare Type would start a new journey.Do you want to proceed?")){
		//resetAlloption();
			window.location = DFC_page_path+"/farecalculator.html";
		}
	} 
}

function newJourney(){
		if (confirm("This will start a new journey. Do you want to proceed?")){
		//resetAlloption();
		//jQuery('#tripContextParameter').html("") ;
		window.location = DFC_page_path+"/farecalculator.html";
		}
}

function duplicatedBusService(){
	if (confirm("Adding the same bus service twice means the start of a new journey. Do you want to proceed?")){
	resetAlloption();
	}
}



function showAdditionalAction(selectedValue){

	
	if ( jQuery('#fare_type_select').val() == "default"  || jQuery('#fare_type_select').val() == ""  ){
		alert("Please select a fare type.");
		jQuery("#mode_type_select").val("default");
	}else{
	
		if (selectedValue == ""){
			jQuery('#mrt_option_step').slideUp(250);
			jQuery('#bus_option_first_step').slideUp(250);
			jQuery('#bus_option_second_step').slideUp(250);
			resetAllBusoption();
			resetAllMrtoption();
		}
		
		if (selectedValue == "bus"){
		
			jQuery('#mrt_option_step').slideUp(250);
			jQuery('#bus_option_first_step').slideDown(250);
			resetAllMrtoption();
	
		}
		if (selectedValue == "mrt"){
			jQuery('#bus_option_first_step').slideUp(250);
			jQuery('#bus_option_second_step').slideUp(250);
			jQuery('#mrt_option_step').slideDown(250);
			resetAllBusoption();
		}
	
	}
}

function showBusMoreAction(){// selected a bus service no.

	jQuery("#bus_service_no option:first").attr("disabled" ,"disabled");

	if (jQuery('#bus_service_no').val() != ""){
	resetSecondBusoption();
	if (jQuery('#bus_option_second_step').css('display') == "none"){
		jQuery('#loading_icon_first').css("display" , "block"); 
	}else{
		jQuery('#loading_icon_second').css("display" , "block");	
	}

		//populate the bus route direction option
		jQuery.ajax({
	     // url: DFC_ajax_path+"/fare_calculator_ajaxlib.html?busServiceId="+jQuery('#bus_service_no').val()+"&inputId=bus_service_direction&action=getBusRouteDirectionListByServiceId" ,
			 url: DFC_ajax_path+"/fare_calculator_ajaxlib.getBusRouteDirectionListByServiceId."+jQuery('#bus_service_no').val()+".bus_service_direction.html" ,
	      success: function(data){
				jQuery('#bus_route_direction_content').html(data);
				
				//populate the start bus stop option
				jQuery.ajax({
				      url: DFC_ajax_path+"/fare_calculator_ajaxlib.getBoardingBusStopListByServiceId."+jQuery('#bus_service_no').val()+".bus_stop_start."+jQuery('#bus_service_direction').val()+".html"  ,
				      success: function(data){
				      jQuery('#bus_stop_start_content').html(data);
						jQuery('#bus_stop_end_content').html("<select><option value=''>Select Bus Stop</option></select>");
					
						jQuery('#loading_icon_first').css("display" , "none");
						jQuery('#loading_icon_second').css("display" , "none");		

						jQuery('#bus_option_second_step').slideDown(250); // only slideDown after data is populated
					},
					error: function(data){
						alert("Sorry, our system is encountering high demand at the moment. Please try again later");
						jQuery('#loading_icon_first').css("display" , "none");
						jQuery('#loading_icon_second').css("display" , "none");	
			      }
				});	 
				

	      },
	      error: function(data){
	    	  
	    	  alert("Sorry, our system is encountering high demand at the moment. Please try again later");
	    	  jQuery('#loading_icon_first').css("display" , "none");
			  jQuery('#loading_icon_second').css("display" , "none");	
	      }
	});	
	}
}

function changeDirection(){
	resetSecondBusoption();
	jQuery('#loading_icon_second').css("display" , "block");

	jQuery.ajax({
		url: DFC_ajax_path+"/fare_calculator_ajaxlib.getBoardingBusStopListByServiceId."+jQuery('#bus_service_no').val()+".bus_stop_start."+jQuery('#bus_service_direction').val()+".html",

	     success: function(data){
		
			jQuery('#bus_stop_start_content').html(data);
			jQuery('#bus_stop_end_content').html("<select><option value=''>Select Bus Stop</option></select>");
			jQuery('#loading_icon_second').css("display" , "none");
		 },
	     error: function(data){
			 alert("Sorry, our system is encountering high demand at the moment. Please try again later");
			 jQuery('#loading_icon_second').css("display" , "none");	
			 jQuery('#bus_option_second_step').slideUp(200);
	     }
	});	
	
	
}


function showAlightingBusStopList(){
	if ( jQuery('#bus_stop_start').val() != "" ){
		jQuery('#loading_icon_second').css("display" , "block");
		
		jQuery.ajax({
		    url: DFC_ajax_path+"/fare_calculator_ajaxlib.html?busServiceId="+jQuery('#bus_service_no').val()+"&direction="+jQuery('#bus_service_direction').val()+"&entryMarkerId="+jQuery('#bus_stop_start').val()+"&inputId=bus_stop_end&action=getAlightingBusStopListByServiceId" ,
		    success: function(data){	
			jQuery('#bus_stop_end_content').html(data);	
			jQuery('#loading_icon_second').css("display" , "none");
		 },
	     error: function(data){
			alert("Sorry, our system is encountering high demand at the moment. Please try again later");
			jQuery('#loading_icon_second').css("display" , "none");	
			jQuery('#bus_option_second_step').slideUp(200);
	     }
	});	
	}else{
		jQuery('#bus_stop_end_content').html("<select><option value=''>Select Bus Stop</option></select>");
	}
}

 

function addTrip(){


resetCompute = true;	
tripNum = 1;
for (i=1;i<=6;i++)
{
	if( jQuery('#trip'+i).html() != "" ){ tripNum += 1; }
}
	
if (  parseInt(tripNum) < 7){

	ticketType= jQuery('#fare_type_select').val();
	if (ticketType == 30){ ticketTypetxt = "Adult"; }	
	if (ticketType == 36){ ticketTypetxt = "Children/Student";}	
	if (ticketType == 39){ ticketTypetxt = "Senior Citizen";}	
	jQuery('#fare_type').html("Fare Type : "+ticketTypetxt);
	
//---------------------------Bus -------------------------//
	if ( jQuery('#mode_type_select').val() == "bus"){
	busServiceId = jQuery('#bus_service_no').val();
	entryMarkerId = jQuery('#bus_stop_start').val();
	exitMarkerId = jQuery('#bus_stop_end').val();	

	var tripContextParameter = jQuery('#tripContextParameter').html();
	
	startNewJourney = false;
	for (i=1;i<=6;i++)
	{
		if ( ("Bus Svc "+busServiceId) == jQuery('#trip'+i+' .bus_col').html()){
			duplicatedBusService();
			startNewJourney = true;
		}	
	}
	
	if (startNewJourney == false){
		if(entryMarkerId == "default" || exitMarkerId == "default"){  
			alert("Please select the boarding and alighting bus stop for your trip");
		}else{
				jQuery('#loading_icon_full_block').css("display" , "block");
				jQuery('#loading_icon_full_block').css("height" , "420px");
				jQuery.ajax({
				      url: DFC_ajax_path+"/fare_calculator_ajaxlib.html?busServiceId="+busServiceId+"&entryMarkerId="+entryMarkerId+"&exitMarkerId="+exitMarkerId+"&ticketType="+ticketType+"&tripContextParameter="+tripContextParameter+"&action=getBusFareComputation" ,
				      success: function(data){
					
					
					jQuery("#fare_info").html(trim(data));
					if ( jQuery("#fare_result_addtrip").html() != "" && jQuery("#fare_result_addtrip").html() != "null" && jQuery("#fare_result_addtrip").html() != null ){ 
						alert(jQuery("#fare_result_addtrip").html() );
						jQuery('#loading_icon_full_block').css("display" , "none");
						jQuery("#fare_info").html("");
					}else{
						jQuery("#fare_info").html("");
							
							jQuery('#trip'+tripNum).html("<div class='num_col'>Trip "+tripNum+"</div>"+data);
							jQuery("#fare_info").css("display","none");
							jQuery("#fare_result").css("display","block");	
							jQuery('#bus_option_second_step').slideUp(250);
							
							resetSecondBusoption();
							resetAllBusoption();

							jQuery('#loading_icon_full_block').css("display" , "none");
							tripNum +=1;
							
							
							
							if (jQuery("div.tripContext_data").html()!="" && jQuery("div.tripContext_data").html() != null){
						jQuery("#tripContextParameter").html( jQuery("div.tripContext_data").html());
						jQuery('div.tripContext_data').remove();	
						
							}
					}
							
				      },
				      error: function(data){
				    	  console.log(data);
				    	  alert("Sorry, our system is encountering high demand at the moment. Please try again later");
				    	  jQuery('#loading_icon_full_block').css("display" , "none");
				      }
				});	
		
	}
	} // close for "newJourney"
	}			

	
//---------------------------Mrt -------------------------//
	
if ( jQuery('#mode_type_select').val() == "mrt"){

	if ( jQuery('#mrt_stop_start').val() == jQuery('#mrt_stop_end').val() &&  jQuery('#mrt_stop_start').val() != "default" ){
		alert("Please select different boarding and alighting MRT/LRT stations");
		return false;
	}
	
	entryMarkerId = jQuery('#mrt_stop_start').val();
	exitMarkerId = jQuery('#mrt_stop_end').val();	
	ticketType= jQuery('#fare_type_select').val();
	
	var tripContextParameter = jQuery('#tripContextParameter').html();
	
			if (mrtTripAdded == false ){ 
				
				if(entryMarkerId == "default" || exitMarkerId == "default"){  
					alert("Please select the boarding and alighting MRT station for your trip");
				}else{	
					jQuery('#loading_icon_full_block').css("display" , "block");
					jQuery('#loading_icon_full_block').css("height" , "330px");
					
					entryMarkerId = jQuery('#mrt_stop_start').val();
					exitMarkerId = jQuery('#mrt_stop_end').val();
					ticketType= jQuery('#fare_type_select').val();
					
					jQuery.ajax({
					      url: DFC_ajax_path+"/fare_calculator_ajaxlib.html?entryMarkerId="+entryMarkerId+"&exitMarkerId="+exitMarkerId+"&ticketType="+ticketType+"&tripContextParameter="+tripContextParameter+"&action=getRailFareComputation" ,
					      success: function(data){
						
						jQuery("#fare_info").html(trim(data));
						if ( jQuery("#fare_result_addtrip").html() != "" && jQuery("#fare_result_addtrip").html() != "null" && jQuery("#fare_result_addtrip").html() != null ){ 
							alert(jQuery("#fare_result_addtrip").html() );
							jQuery('#loading_icon_full_block').css("display" , "none");
							jQuery("#fare_info").html("");
						}else{
							jQuery("#fare_info").html("");
							
						    mrtTripAdded = true;
							jQuery('#trip'+tripNum).html("<div class='num_col'>Trip "+tripNum+"</div>"+data);	
							jQuery("#fare_info").css("display","none");
							jQuery("#fare_result").css("display","block");	
							jQuery('#loading_icon_full_block').css("display" , "none");
							
							tripNum+=1;
							resetAllMrtoption();
							jQuery('#mrt_option_step').slideUp(250);
							jQuery('#mode_type_select').val("bus");
							jQuery('#bus_option_first_step').slideDown(250);
							
							if (jQuery("div.tripContext_data").html()!="" && jQuery("div.tripContext_data").html() != null){
								jQuery("#tripContextParameter").html( jQuery("div.tripContext_data").html());
								jQuery('div.tripContext_data').remove();	
								
							}
						}
							
							
					      },
					      error: function(data){
					    	  console.log(data);
					    	  alert("Sorry, our system is encountering high demand at the moment. Please try again later");
					    	  jQuery('#loading_icon_full_block').css("display" , "none");
					      }
					});	
				}
			}else{
				alert("Distance Fares allows only one entry into the MRT / LRT system in a single journey. ");
				resetCompute = false;
			}
	}

jQuery('#trip'+tripNum).css("display","block");
jQuery('#compute_btn').css("display","block");

		if (resetCompute){
		jQuery('#totalDistance').html("" ) ;
		jQuery('#totalFare').html("" ) ;
		jQuery('.compute_result').css("display","none");
		}	
}else{
 alert("Distance Fares allows a maximum of 5 transfers in a journey");
}

}

// ----------------compute -------------------------//

function compute(){
	
	var totalFare= 0;
	var totalDistance= 0;
	

	if (jQuery('#trip1').html() != ""){	
	totalFare += parseInt(jQuery('#trip1 .fare_raw').html()); 
	totalDistance += parseInt(jQuery('#trip1 .distance_raw').html());
	}

	jQuery('#totalDistance').html( " km"  ) ;
	jQuery('#totalFare').html("$" );
	jQuery('.compute_result').fadeIn(300);
	
	if (jQuery('#trip2').html() != ""){
	totalFare += parseInt(jQuery('#trip2 .fare_raw').html()); 
	totalDistance += parseInt(jQuery('#trip2 .distance_raw').html());
	}

	if (jQuery('#trip3').html() != ""){
	totalFare += parseInt(jQuery('#trip3 .fare_raw').html()); 
	totalDistance += parseInt(jQuery('#trip3 .distance_raw').html());
	}
	
	if (jQuery('#trip4').html() != ""){
	totalFare += parseInt(jQuery('#trip4 .fare_raw').html()); 
	totalDistance += parseInt(jQuery('#trip4 .distance_raw').html());
	}
	
	if (jQuery('#trip5').html() != ""){
	totalFare += parseInt(jQuery('#trip5 .fare_raw').html()); 
	totalDistance += parseInt(jQuery('#trip5 .distance_raw').html());
	}
	
	if (jQuery('#trip6').html() != ""){
	totalFare += parseInt(jQuery('#trip6 .fare_raw').html()); 
	totalDistance += parseInt(jQuery('#trip6 .distance_raw').html());
	}

	if(totalFare != 0){
	jQuery('#totalDistance').html( (totalDistance/ 100).toFixed(1)+" km" ) ;
	jQuery('#totalFare').html("$"+ (totalFare/ 100).toFixed(2)  );
	jQuery('.compute_result').fadeIn(300);
	}
	
	
	
	if (jQuery('#trip1').html() == ""){	
		alert("Please add at least one trip before computing the fare.");
		}

}






/*----------Reset Function--------------*/

function resetAllBusoption(){
	jQuery('#bus_service_no').val("default");
	jQuery('#bus_stop_start').val("default");
	jQuery('#bus_stop_end').val("default");
}

function resetSecondBusoption(){
	jQuery('#bus_stop_start').val("default");
	jQuery('#bus_stop_end').val("default");
}

function resetAllMrtoption(){
	jQuery('#mrt_stop_start').val("default");
	jQuery('#mrt_stop_end').val("default");
}


function resetAlloption(){
	jQuery('#fare_type_select').val("default");
	jQuery('#mode_type_select').val("default");	
	jQuery('#bus_service_no').val("default");	
	jQuery('#bus_stop_start').val("default");
	jQuery('#bus_stop_end').val("default");	
	jQuery('#mrt_stop_start').val("default");
	jQuery('#mrt_stop_end').val("default");	
	
	jQuery('#fare_type').html("");		
	for (i=1;i<=6;i++)
	{
		jQuery('#trip'+i).html("");	
	}
	mrtTripAdded = false ;
	
	jQuery('#bus_option_first_step').slideUp(250);
	jQuery('#bus_option_second_step').slideUp(250);
	jQuery('#mrt_option_step').slideUp(250);
	
	jQuery("#fare_result").css("display","none");
	jQuery("#fare_info").css("display","block");
	
	jQuery('#totalDistance').html("" ) ;
	jQuery('#totalFare').html("" ) ;
	jQuery('.compute_result').css("display","none");
	jQuery('#tripContextParameter').html("" ) ;
	jQuery('#compute_btn').css("display","none");
}




/*--------- fare calculator page method call-----------------------*/

function showRules(){
	alert("Transfer Rules"+'\n' + '\n' +
"1) Maximum of 5 transfers within a single journey, with a 45 minute allowance between each transfer."+'\n' +
"2) All journeys must be completed within 2 hours."+'\n' +
"3) Single entry and exit for rail travel."+'\n' +
"4) Same bus service number must not be taken more than once in a journey.");
	
}




/*--------- init add trip from menu block-----------------------*/

function addTrip_init( type, ticketType_par, busServiceId_par , entryMarkerId_par , exitMarkerId_par){


resetCompute = true;	
tripNum = 1;
for (i=1;i<=6;i++)
{
	if( jQuery('#trip'+i).html() != "" ){ tripNum += 1; }
}

if (  parseInt(tripNum) < 7 && ticketType_par != "" && entryMarkerId_par != ""){
	
	jQuery('#fare_type_select').val(ticketType_par); // set the ticket type
	ticketType= ticketType_par;
	if (ticketType == 30){ ticketTypetxt = "Adult"; }	
	if (ticketType == 36){ ticketTypetxt = "Children/Student";}	
	if (ticketType == 39){ ticketTypetxt = "Senior Citizen";}	
	jQuery('#fare_type').html("Fare Type : "+ticketTypetxt);

//---------------------------Bus -------------------------//
	if ( type == "bus"){
	busServiceId = busServiceId_par;
	entryMarkerId = entryMarkerId_par;
	exitMarkerId = exitMarkerId_par;	
	
	var tripContextParameter = jQuery('#tripContextParameter').html();
	
	
	startNewJourney = false;
	for (i=1;i<=6;i++)
	{
		if ( ("Bus Svc "+busServiceId) == jQuery('#trip'+i+' .bus_col').html()){
			duplicatedBusService();
			startNewJourney = true;
		}	
	}

	if (startNewJourney == false){
		if(entryMarkerId == "default" || exitMarkerId == "default"){  
			alert("Please select the boarding and alighting bus stop for your trip");
		}else{
				jQuery('#loading_icon_first').css("display" , "block");
				
				
				
				jQuery.ajax({
				      url: DFC_ajax_path+"/fare_calculator_ajaxlib.html?busServiceId="+busServiceId+"&entryMarkerId="+entryMarkerId+"&exitMarkerId="+exitMarkerId+"&ticketType="+ticketType+"&tripContextParameter="+tripContextParameter+"&action=getBusFareComputation" ,
				      success: function(data){
					
					jQuery("#fare_info").html(trim(data));
					if ( jQuery("#fare_result_addtrip").html() != "" && jQuery("#fare_result_addtrip").html() != "null" && jQuery("#fare_result_addtrip").html() != null ){ 
						alert(jQuery("#fare_result_addtrip").html());
						jQuery('#loading_icon_first').css("display" , "none")
						jQuery("#fare_info").html("");
					}else{
							jQuery("#fare_info").html("");
							
							jQuery('#trip'+tripNum).html("<div class='num_col'>Trip "+tripNum+"</div>"+data);
							jQuery("#fare_info").css("display","none");
							jQuery("#fare_result").css("display","block");	
							jQuery('#bus_option_second_step').slideUp(250);
							
							resetSecondBusoption();
							resetAllBusoption();

							jQuery('#loading_icon_first').css("display" , "none");
							tripNum +=1;
							
							if (jQuery("div.tripContext_data").html()!="" && jQuery("div.tripContext_data").html() != null){
						jQuery("#tripContextParameter").html( jQuery("div.tripContext_data").html());
						jQuery('div.tripContext_data').remove();	
						
							}
					}	
							
							
				      },
				      error: function(data){
				    	  console.log(data);
				    	  alert("Sorry, our system is encountering high demand at the moment. Please try again later");
				    	  jQuery('#loading_icon_full_block').css("display" , "none");
				      }
				});	
				
				
		
	}
	} // close for "newJourney"
	}			

	
//---------------------------Mrt -------------------------//
	
if ( type == "mrt"){

	entryMarkerId = entryMarkerId_par;
	exitMarkerId = exitMarkerId_par;	
	ticketType= ticketType_par;

	var tripContextParameter = jQuery('#tripContextParameter').html();
	
			if (mrtTripAdded == false ){ 
				
				if(entryMarkerId == "default" || exitMarkerId == "default"){  
					alert("Please select the boarding and alighting MRT station for your trip");
				}else{	
					jQuery('#loading_icon_first').css("display" , "block");
			
					
					entryMarkerId = entryMarkerId_par;
					exitMarkerId =exitMarkerId_par;	
					ticketType= ticketType_par;
					
					jQuery.ajax({
					      url: DFC_ajax_path+"/fare_calculator_ajaxlib.html?entryMarkerId="+entryMarkerId+"&exitMarkerId="+exitMarkerId+"&ticketType="+ticketType+"&tripContextParameter="+tripContextParameter+"&action=getRailFareComputation" ,
					      success: function(data){
		

						jQuery("#fare_info").html(trim(data));
						if ( jQuery("#fare_result_addtrip").html() != "" && jQuery("#fare_result_addtrip").html() != "null" && jQuery("#fare_result_addtrip").html() != null ){ 
							alert(jQuery("#fare_result_addtrip").html() );
							jQuery('#loading_icon_full_block').css("display" , "none");
							jQuery('#loading_icon_first').css("display" , "none");
							jQuery("#fare_info").html("");
						}else{
							jQuery("#fare_info").html("");
						
						    mrtTripAdded = true;
							jQuery('#trip'+tripNum).html("<div class='num_col'>Trip "+tripNum+"</div>"+data);	
							jQuery("#fare_info").css("display","none");
							jQuery("#fare_result").css("display","block");	
							jQuery('#loading_icon_first').css("display" , "none");
							
							tripNum+=1;
							resetAllMrtoption();
							jQuery('#mrt_option_step').slideUp(250);
							jQuery('#mode_type_select').val("bus");
							jQuery('#bus_option_first_step').slideDown(250);
							
							if (jQuery("div.tripContext_data").html()!="" && jQuery("div.tripContext_data").html() != null){
								jQuery("#tripContextParameter").html( jQuery("div.tripContext_data").html());
								jQuery('div.tripContext_data').remove();	
								
							}
							
						}
							
							
							
							
					      },
					      error: function(data){
					    	  console.log(data);
					    	  alert("Sorry, our system is encountering high demand at the moment. Please try again later");
					    	  jQuery('#loading_icon_full_block').css("display" , "none");
					      }
					      
					      
					});	
				}
			}
	}

jQuery('#trip'+tripNum).css("display","block");
jQuery('#compute_btn').css("display","block");

		if (resetCompute){
		jQuery('#totalDistance').html("" ) ;
		jQuery('#totalFare').html("" ) ;
		jQuery('.compute_result').css("display","none");
		}	
}


}










function setMapDimension( map_h,map_w){
    jQuery("#map").css("width" ,map_w+"px");
    jQuery("#map").css("height" ,map_h+"px");
    
    jQuery(".embedding_map").css("width" ,map_w+"px");
    jQuery(".embedding_map").css("height" ,map_h+"px");
}
var brow_type = navigator.appName;
if(window.location.hash && brow_type == "Microsoft Internet Explorer"){
	(function($){ 
		$(window).load(
				function(){
					var hash_loc = window.location.hash;
					hash_loc = hash_loc.substring(1);
					if(!$(".col_menu.section div.collapse-panel a[name='"+hash_loc+"']").length > 0){
						$(".col_menu.section div a[name='"+hash_loc+"']+h2").trigger("click");
						var posTop = $(".col_menu.section div a[name='"+hash_loc+"']").position();
						$("body").scrollTop(posTop.top);
					}
					else{
						var posTop = $(".col_menu.section div a[name='"+hash_loc+"']").position();
						$("body").scrollTop(posTop.top);
					}
				});
	})($CQ || $);
}
                
var PANEL_NORMAL_CLASS    = "collapse-panel";
var PANEL_COLLAPSED_CLASS = "collapse-panelcollapsed";
var PANEL_HEADING_TAG     = "h2";
var PANEL_CONTENT_CLASS   = "collapse-panelcontent";
var PANEL_COOKIE_NAME     = "collapse-panels";
var PANEL_ANIMATION_DELAY = 20; /*ms*/
var PANEL_ANIMATION_STEPS = 10; 

function setUpPanels()
{
    loadSettings();
    
    // get all headings
    var headingTags = document.getElementsByTagName(PANEL_HEADING_TAG);
    
    // go through all tags
    for (var i=0; i<headingTags.length; i++)
    {
        var el = headingTags[i];
        
        // make sure it's the heading inside a panel
        if (el.parentNode.className != PANEL_NORMAL_CLASS && el.parentNode.className != PANEL_COLLAPSED_CLASS)
            continue;
        
        // get the text value of the tag
        var name = el.firstChild.nodeValue;
    
        // look for the name in loaded settings, apply the normal/collapsed class
        if (panelsStatus[name] == "false")
            el.parentNode.className = PANEL_COLLAPSED_CLASS;
        else
        if (panelsStatus[name] == "true")
            el.parentNode.className = PANEL_NORMAL_CLASS;
        else
        {
            // if no saved setting, see the initial setting
            panelsStatus[name] = (el.parentNode.className == PANEL_NORMAL_CLASS) ? "true" : "false";
        }
        
        // add the click behavor to headings
        el.onclick = function() 
        {
            var target    = this.parentNode;
            var name      = this.firstChild.nodeValue;
            var collapsed = (target.className == PANEL_COLLAPSED_CLASS);
            saveSettings(name, collapsed?"true":"false");
            animateTogglePanel(target, collapsed);
        };
    }
}

/**
 * Start the expand/collapse animation of the panel
 * @param panel reference to the panel div
 */
function animateTogglePanel(panel, expanding)
{
    // find the .panelcontent div
    var elements = panel.getElementsByTagName("div");
    var panelContent = null;
    for (var i=0; i<elements.length; i++)
    {
        if (elements[i].className == PANEL_CONTENT_CLASS)
        {
            panelContent = elements[i];
            break;
        }
    }
    
    // make sure the content is visible before getting its height
    panelContent.style.display = "block";
    
    // get the height of the content
    var contentHeight = panelContent.offsetHeight;
    
    // if panel is collapsed and expanding, we must start with 0 height
    if (expanding)
        panelContent.style.height = "0px"; 
    
    var stepHeight = contentHeight / PANEL_ANIMATION_STEPS;
    var direction = (!expanding ? -1 : 1);
    
    setTimeout(function(){animateStep(panelContent,1,stepHeight,direction)}, PANEL_ANIMATION_DELAY);
}

/**
 * Change the height of the target
 * @param panelContent  reference to the panel content to change height
 * @param iteration     current iteration; animation will be stopped when iteration reaches PANEL_ANIMATION_STEPS
 * @param stepHeight    height increment to be added/subtracted in one step
 * @param direction     1 for expanding, -1 for collapsing
 */
function animateStep(panelContent, iteration, stepHeight, direction)
{
    if (iteration<PANEL_ANIMATION_STEPS)
    {
        panelContent.style.height = Math.round(((direction>0) ? iteration : 10 - iteration) * stepHeight) +"px";
        iteration++;
        setTimeout(function(){animateStep(panelContent,iteration,stepHeight,direction)}, PANEL_ANIMATION_DELAY);
    }
    else
    {
        // set class for the panel
        panelContent.parentNode.className = (direction<0) ? PANEL_COLLAPSED_CLASS : PANEL_NORMAL_CLASS;
        // clear inline styles
        panelContent.style.display = panelContent.style.height = "";
    }
}

// -----------------------------------------------------------------------------------------------
// Load-Save
// -----------------------------------------------------------------------------------------------
/**
 * Reads the "panels" cookie if exists, expects data formatted as key:value|key:value... puts in panelsStatus object
 */
function loadSettings()
{
    // prepare the object that will keep the panel statuses
    panelsStatus = {};
    
    // find the cookie name
    var start = document.cookie.indexOf(PANEL_COOKIE_NAME + "=");
    if (start == -1) return;
    
    // starting point of the value
    start += PANEL_COOKIE_NAME.length+1;
    
    // find end point of the value
    var end = document.cookie.indexOf(";", start);
    if (end == -1) end = document.cookie.length;
    
    // get the value, split into key:value pairs
    var cookieValue = unescape(document.cookie.substring(start, end));
    var panelsData = cookieValue.split("|");
    
    // split each key:value pair and put in object
    for (var i=0; i< panelsData.length; i++)
    {
        var pair = panelsData[i].split(":");
        panelsStatus[pair[0]] = pair[1];
    }
}

function expandAll()
{
    for (var key in panelsStatus)
        saveSettings(key, "true");
        
    setUpPanels();
}

function collapseAll()
{
    for (var key in panelsStatus)
        saveSettings(key, "false");
        
    setUpPanels();
}

/**
 * Takes data from the panelsStatus object, formats as key:value|key:value... and puts in cookie valid for 365 days
 * @param key   key name to save
 * @paeam value key value
 */
function saveSettings(key, value)
{
    // put the new value in the object
    panelsStatus[key] = value;
    
    // create an array that will keep the key:value pairs
    var panelsData = [];
    for (var key in panelsStatus)
        panelsData.push(key+":"+panelsStatus[key]);
        
    // set the cookie expiration date 1 year from now
    var today = new Date();
    var expirationDate = new Date(today.getTime() + 28 * 1000 * 60 * 60 * 24);
    // write the cookie
    document.cookie = PANEL_COOKIE_NAME + "=" + escape(panelsData.join("|")) + ";expires=" + expirationDate.toGMTString();
}

// -----------------------------------------------------------------------------------------------
// Register setUpPanels to be executed on load
if (window.addEventListener)
{
    // the "proper" way
    window.addEventListener("load", setUpPanels, false);
}
else 
if (window.attachEvent)
{
    // the IE way
    window.attachEvent("onload", setUpPanels);
}

(function($){
    $(window).load(
            function(){
            var free_type = navigator.appName;
                if(window.location.hash && free_type != "Microsoft Internet Explorer"){
                    var hash_locs = window.location.hash;
                    hash_locs = hash_locs.substring(1);
                    if(!$(".col_menu.section div.collapse-panel a[name='"+hash_locs+"']").length > 0){
                        $(".col_menu.section div a[name='"+hash_locs+"']+h2").trigger("click");
                        var posTops = $(".col_menu.section div a[name='"+hash_locs+"']").position();
                        $("body").scrollTop(posTops.top);
                    }
                    else{
                        var posTops = $(".col_menu.section div a[name='"+hash_locs+"']").position();
                        $("body").scrollTop(posTops.top);
                    }
                }
            });
})($CQ || $); 




var selected ; // define the current selected "expended" panel (Obj)  

function sliderLib( widthvalue,  path ,count , lastselected ){
    

// set first panel arrow to on, 2nd and the rest push to the right 
if ( lastselected == 2 ){

  selected =jQuery("#accord_btn_1"); 
  jQuery("div.slider_arrow img:first").attr("src",path +"/arrow_on.png"); // set only selected to on
  jQuery(selected).find("img.panel_hover_bar").animate({"opacity": "0"});
  jQuery(selected).find("div.is_selected").html("selected");

  
}else{

  selected =jQuery("#accord_btn_"+(parseInt(lastselected)-1));
  jQuery(selected).find("img:first").attr("src",path +"/arrow_on.png"); // set only selected to on
  jQuery(selected).find("img.panel_hover_bar").animate({"opacity": "0"});
  jQuery(selected).find("div.is_selected").html("selected");

}
  
tempFlag = 0;
count = parseInt(count );
  

// set max width
jQuery("div.accordion_par").css( "width", widthvalue );

  //retrieve from cookie then push all panels to the right except the one to expand
 for(var p = lastselected; p <= count  ;p++) {
 jQuery("#accordion_par"+p+".accordion_par").animate({"left": 940 - ( (count - (p-1))*45)}, 0);
}
    

 
 
 
 
 
 jQuery("div.panel_bar_bg").hover(
		
		    function() { 
		    	if ( jQuery(this).find("div.is_selected").html() != "selected"){
		    	jQuery(this).find("img.panel_hover_bar").animate({"opacity": "0"}, { queue:false, duration:150});
		    	}
		    	
		    },
		    
		    function() {
		    	if ( jQuery(this).find("div.is_selected").html() != "selected"){
		    	jQuery(this).find("img.panel_hover_bar").animate({"opacity": "1"},  { queue:false, duration:150});
		    	}
});

 
 
 
 jQuery("div.accordion_btn_click").click(function(){ 

 if (this.id != "accordion_btn_"+(parseInt(lastselected))){ 
  tempFlag = 1;
 }

  selected  = this;

  var SelectedID = jQuery(this).attr("id");
  
  SelectedID = SelectedID.substring(11, SelectedID.length); 
  
    jQuery("div.accordion_btn_click").find("img:first").attr("src",path +"/arrow_off.png"); // set all to off
    jQuery(this).find("img:first").attr("src",path +"/arrow_on.png"); // set only selected to on

    for(var r = parseInt(SelectedID) ; r > 1  ; r--) {
    jQuery("#accordion_par"+r).animate({"left": (r-1) * 45 }, 700);
    }
 
    for(var i=1; i <= (parseInt(count) - parseInt(SelectedID) ) ; i++) {
    jQuery("#accordion_par"+(parseInt(SelectedID)+i)).animate({"left": 895  - ( ( parseInt(count ) -i - parseInt(SelectedID) ) * 45 ) },700);
    }
    
    
    for(var i=1; i <= parseInt(count)  ; i++) { // un-highlight all buttons
    	if(  SelectedID != i){
    	jQuery("#accordion_par"+i).find("img.panel_hover_bar").animate({"opacity": "1"});
    	}
    }
    
    // highlight the selected buttons
	jQuery("#accordion_par"+SelectedID).find("img.panel_hover_bar").animate({"opacity": "0"});
  
    
    jQuery("div.is_selected").html("");
    jQuery(this).find("div.is_selected").html("selected");

    
    time = Math.round((new Date()).getTime());//get current timestamp as last visit
    
      jQuery.get("/content/publictransport/en/homepage/cookie.html?operation=addcookie&name=lastpanelselected&value="+SelectedID, function(data){
      // lastpanelselected cookie added successfully
      });
      
      jQuery.get("/content/publictransport/en/homepage/cookie.html?operation=addcookie&name=lastpanelselectedPublishTime&value="+time, function(data){
      // lastpanelselectedPublishTime cookie added successfully
      });
      
      //fire a ajax call to its own URL when clicked for keep track with Web track
      jQuery.get( jQuery("#accordion_par"+SelectedID).find("div.url").html(), function(data){
          // doing nothing
          });

      
      
});
  
  
//---------------button panel mouseover---------------//
  
jQuery("div.accordion_btn_click").mouseover(
function(){ 
 if (this.id == "accord_btn_" +(parseInt(lastselected)-1) &&  tempFlag == 0){
 }
 else {
       if (selected != this  ){
       jQuery(this).find("img:first").attr("src",path +"/arrow_on.png");    
       
       } 
}
}); 
      

jQuery("div.accordion_btn_click").mouseout(

function(){ 
  if (this.id == "accord_btn_" +(parseInt(lastselected)-1) &&  tempFlag == 0){
 }
 else {
  if (selected != this   ){
       jQuery(this).find("img:first").attr("src",path +"/arrow_off.png"); 
  }
}


}); 


//---------------arrow icon mouseover---------------//


jQuery("div.slider_arrow").mouseover(
function(){ 
	jQuery(this).parent().find("img.panel_hover_bar").animate({"opacity": "0"},100);	  
}); 
   
jQuery("div.slider_arrow").mouseout(

function(){ 
	  if ( jQuery(this).parent().find("div.is_selected").html() != "selected"  ){
	jQuery(this).parent().find("img.panel_hover_bar").animate({"opacity": "1"},100);
	  }
}); 





}

(function($){
$(function(){
    $(".linkcontainer .link + .linkcontainer .link a").addClass("non-title-links");
    var title = $(".text .linkcontainer .link a:not('.non-title-links')");
    for(var x = 0; x < title.length; x++){
        var reverse = $(".linkcontainer .link:contains("+title[x].text+") + .linkcontainer .link");
        if(reverse.length != 0){
            var reversed = new Array();
            for(var i=0; i < reverse.length; i++){
                reversed[(reverse.length-1)-i] = reverse[i];
            }
            $(".linkcontainer .link:contains("+title[x].text+") + .linkcontainer").empty();
            for(var k=0; k < reverse.length; k++){
               $(".linkcontainer .link:contains("+title[x].text+") + .linkcontainer").append(reversed[k]);
            }
        }
    }
});
})($CQ || $);
var latestsuggestion_MenuBlock;


var map_page_path ="/content/publictransport/en/homepage/map";
var map_ajax_path ="/content/publictransport/en/homepage/Ajax";



/*-------------Methods for Suggestion box---------------------------------------*/

function detectInputPBS_MenuBlock(  ) // for all 3 textfields
{   
	jQuery('#originPBS').keyup(function(e) { 
	    if(e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 13) { // not up,down,enter key
	    	retrieveDataPBS_MenuBlock(   jQuery('#originPBS').val() ,'pbs_suggestion_box_origin'   );

	    	suggestion_hightligh_counter=-1; 
	        }
	});

	jQuery('#destinationPBS').keyup(function(e) { 
	    if(e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 13) { // not up,down,enter key
	    	retrieveDataPBS_MenuBlock(   jQuery('#destinationPBS').val() ,'pbs_suggestion_box_destination'   );
	    	suggestion_hightligh_counter=-1; 
	        }
	});

	}




function retrieveDataPBS_MenuBlock( inputText , outputBox) // inputText is keyword, outputBox is the ID of the suggestion box
{  
	input = trim( inputText );
	if ( trim(input).length >= 3   ){ 
	
		populateDataPBS( input, outputBox );
	}

	if ( input.length < 3 ){  
		hideSuggestionBox();
	}
}  


function populateDataPBS( input , outputBox ) { 

	input = trim(input );

	if (outputBox == "pbs_suggestion_box_origin"){   
		searchType = "PremiumBus_origin";
	}
	if (outputBox == "pbs_suggestion_box_destination"){   
		searchType = "PremiumBus_destination";
	}
	
	latestsuggestionPBS = Math.floor(Math.random()*10);
	jQuery.ajax({
        url:    map_ajax_path+"/map_ajaxlib.html?keyword="+input+"&searchType="+searchType+"&keywordSynId="+latestsuggestionPBS+"&action=getAddressByKeywords",
        success: function(result) {
		
		jQuery('#pbs_suggestion_box_origin').html("");
		jQuery('#pbs_suggestion_box_destination').html("");

		jQuery('#'+outputBox).html( result);  

		
		if ( jQuery('#synId').html() == latestsuggestionPBS ){
			jQuery('#'+outputBox).slideDown(300);
		}


                 },
        async: true
   });          

}



function submitPremiumBusSearch(){
	
	originPBS = trim(jQuery("#originPBS").val());
	destinationPBS = trim(jQuery("#destinationPBS").val());
	
	if (originPBS ==""  || destinationPBS =="" || originPBS =="Enter your Origin"  || destinationPBS =="Enter your Destination"){
		
		alert("Please enter the Origin and Destination");
	}else{
		
		newwindow=window.open(map_page_path+'.html?MapType=PremiumBusService&from=menublockShowPremium&origin='+originPBS+'&destination='+destinationPBS+'', 'name','height=900,width=925,resizable=yes,location=no,toolbar=no,scrollbars=yes,menubar=no,status=no,directories=no');
		if (window.focus) {newwindow.focus()}
		return false; 
	}
	
}


function openNew(src)
{
    window.open(
            src,            
            'Window',
            'height=845,width=908,resizable=1,location=0,toolbar=0,scrollbars=1,menubar=0,status=0,directories=0'            
        );
}

(function($){
    $(function(){
        var loc = new Array();
        if(document.URL.indexOf("bus_arrival_timings") > 0 || document.URL.indexOf("eServices.html") > 0){
            $(".useful-plain-ul ul li a").removeAttr("target");
            $(".useful-plain-ul ul li a").click(function(){
                if($.inArray($(this).text(), loc) == -1){
                    loc[loc.length] = $(this).attr("href");
                    loc[loc.length] = $(this).text();
                }
                $("'.useful-plain-ul ul li a:contains("+$(this).text()+")'").removeAttr("href");
                openNew(loc[($.inArray($(this).text(), loc)-1)]);
                });
        }
    });
})($CQ || $);

var latestsuggestion_MenuBlock;

var map_page_path ="/content/publictransport/en/homepage/map";


/*-------------Methods for Suggestion box---------------------------------------*/


function selectSuggestionMenuBlock(thisElement){
	
	 jQuery("#search_input").val(jQuery(thisElement).html());
	 jQuery('#suggestion_box').slideUp(400)
}



function submitKeywordMenuBlock(){
	latestsuggestion_MenuBlock = "";
	input = trim( jQuery("#search_input").val() );
	
	if(input == "" || input == "eg: Bishan Road / Republic Plaza / 219428"){
		alert("Please enter the keyword(s) to search");
		return false; 
	}else{
		input=input.replace("&", "%26*");
	newwindow=window.open(map_page_path+'.html?keyword='+input+'&from=menublockSearchByKeywords ', 'name','height=900,width=925,resizable=yes,location=no,toolbar=no,scrollbars=yes,menubar=no,status=no,directories=no');
	if (window.focus) {newwindow.focus()}
	return false; 
	}
}


function detectInputMenuBlock(){


jQuery("#search_input").keydown(function(e) {
	
    if(e.keyCode == 13 && jQuery("#map_menu_menu_homepage_wapper").html() != null) {

    	  input = trim( jQuery("#search_input").val() );
    
    		if(input == "" || input == "eg: Bishan Road / Republic Plaza / 219428"){
    			alert("Please enter the keyword(s) to search");
    			return false; 
    		}else{
    			input=input.replace("&", "%26*");
    			newwindow=window.open(map_page_path+'.html?keyword='+input+'&from=menublockSearchByKeywords ', 'name','height=900,width=925,resizable=yes,location=no,toolbar=no,scrollbars=yes,menubar=no,status=no,directories=no');
    		if (window.focus) {newwindow.focus()}
    		return false; 
    		}
        e.preventDefault();
    } 
});


}


function  LaunchShowOnMap( longitude , latitude ) {
	latestsuggestion_MenuBlock = "";
	input = trim( jQuery("#search_input").val() );
	
	newwindow=window.open(map_page_path+'.html?keyword='+input+'&longtitude='+longitude+'&latitude='+latitude+'&from=menublockSearchByAddress ', 'name','height=900,width=925,resizable=yes,location=no,toolbar=no,scrollbars=yes,menubar=no,status=no,directories=no');
	if (window.focus) {newwindow.focus()}
	return false; 
}



function  LaunchShowBusRoute( zoom , type ,busServiceNo ) {

	if ( busServiceNo != "default"){

		newwindow=window.open(map_page_path+'.html?zoom='+zoom+'&busServiceNo='+busServiceNo+'&from=menublockShowBusRoute ', 'name','height=900,width=925,resizable=yes,location=no,toolbar=no,scrollbars=yes,menubar=no,status=no,directories=no');
			
		if (window.focus) {newwindow.focus()}
	}
	return false; 
}


function  LaunchShowBusInter(busInterID ) {

	if ( busInterID != "default"){
	newwindow=window.open(map_page_path+'.html?busInterID='+busInterID+'&from=menublockShowBusInterChange ', 'name','height=900,width=925,resizable=yes,location=no,toolbar=no,scrollbars=yes,menubar=no,status=no,directories=no');
	if (window.focus) {newwindow.focus()}
	}
	return false; 
	
}



function  LanuchShowTrainStation(trainID ) {
	if ( trainID != "default"){
	newwindow=window.open(map_page_path+'.html?trainID='+trainID+'&from=menublockShowTrainStation', 'name','height=900,width=925,resizable=yes,location=no,toolbar=no,scrollbars=yes,menubar=no,status=no,directories=no');
	if (window.focus) {newwindow.focus()}
	}
	
	return false; 
}
(function($){$(document).ready(function(){
    $("#tab0").addClass("active");
    $(".gen-tab-menu > li").click(function(e){
        switch(e.target.id){
            case "tab0":
                $("#tab0").addClass("active");
                $("#tab1").removeClass("active");
                $("#tab2").removeClass("active");
                $("#tab3").removeClass("active");
                $("div.tab0").fadeIn();
                $("div.tab1").css("display", "none");
                $("div.tab2").css("display", "none");
                $("div.tab3").css("display", "none");               
            break;
            case "tab1":
                $("#tab1").addClass("active");
                $("#tab0").removeClass("active");
                $("#tab2").removeClass("active");
                $("#tab3").removeClass("active");
                $("div.tab1").fadeIn();
                $("div.tab0").css("display", "none");
                $("div.tab2").css("display", "none");
                $("div.tab3").css("display", "none");  
            break;
            case "tab2":
                $("#tab2").addClass("active");
                $("#tab0").removeClass("active");
                $("#tab1").removeClass("active");
                $("#tab3").removeClass("active");
                $("div.tab2").fadeIn();
                $("div.tab0").css("display", "none");
                $("div.tab1").css("display", "none");
                $("div.tab3").css("display", "none");  
            break;
            case "tab3":
                $("#tab3").addClass("active");
                $("#tab0").removeClass("active");
                $("#tab1").removeClass("active");
                $("#tab2").removeClass("active");
                $("div.tab3").fadeIn();
                $("div.tab0").css("display", "none");
                $("div.tab1").css("display", "none");
                $("div.tab2").css("display", "none");               
            break;
        }
        return false;
    });
});})($CQ || $);
var mrtTripAdded = false;

var DFC_page_path ="/content/publictransport/en/homepage/eServices" ;


jQuery(document).ready(function()
		{
	
	if ( jQuery("#fare_calculator_menu_homepage_wapper").html() != ""  ){
		var mouse_is_inside;
	
				jQuery('#fare_calculator_menu_homepage_wapper').hover(function(){ 
				    mouse_is_inside=true; 
				}, function(){ 
				    mouse_is_inside=false; 
				});
		
				jQuery("body").click(function(event ){ 
					
					if (event.target.id == "fare_type_select"){  mouse_is_inside=true;}
					if (event.target.id == "mode_type_select"){  mouse_is_inside=true;}
					if (event.target.id == "bus_service_no"){  mouse_is_inside=true;}
					if (event.target.id == "bus_service_direction"){  mouse_is_inside=true;}
					
					if (event.target.id == "bus_stop_start"){  mouse_is_inside=true;}
					if (event.target.id == "bus_stop_end"){  mouse_is_inside=true;}
					
					if (event.target.id == "mrt_stop_start"){  mouse_is_inside=true;}
					if (event.target.id == "mrt_stop_end"){  mouse_is_inside=true;}
					
				   if(mouse_is_inside == false) { 
					   
					   
					   jQuery('#bus_option_second_step').slideUp(250);
					   jQuery('#mrt_option_step').slideUp(250);
					   
					   
						if (jQuery('#mode_type_select').val() == "mrt"   ){
							jQuery('#bus_option_first_step').slideUp(250);
							jQuery('#show_info_DFC').css("display" , "block");
							jQuery('#hide_info_DFC').css("display" , "none");
						}
						
						if ( jQuery('#mode_type_select').val() == "bus" && ( jQuery('#bus_service_no').val() != "" && jQuery('#bus_service_no').val() != null && jQuery('#bus_service_no').val() != "default"  )){
							jQuery('#show_info_DFC').css("display" , "block");
							jQuery('#hide_info_DFC').css("display" , "none");  
						}
						
						
					
						
						// resetAlloption();
						
						 
						};
						
				});
				
				
				
				
				jQuery('#bus_service_no').bind({
					  click: function() {
						jQuery('#show_info_DFC').css("display" , "none");
						jQuery('#hide_info_DFC').css("display" , "block");
					  }
				});
				
				
				jQuery('#mode_type_select').bind({
					  click: function() {
					
							if (jQuery('#mode_type_select').val() == "mrt"  ){
								jQuery('#show_info_DFC').css("display" , "none");
							}

					  }
				});		
				
				
	}
	
		});


function selected_type(){
	jQuery("#fare_type_select option:first").attr("disabled" ,"disabled");
}


function selected_mode(){
	jQuery("#mode_type_select option:first").attr("disabled" ,"disabled");
}




function addTrip_homepage(){
	
	
	
	if (    jQuery('#mode_type_select').val() == "bus"){
	if ( jQuery('#bus_stop_start').val() != "default"  &&   jQuery('#bus_stop_end').val()  != "default"  ){
	
	
	ticketType= jQuery('#fare_type_select').val();
	busServiceId = jQuery('#bus_service_no').val();
	entryMarkerId = jQuery('#bus_stop_start').val();
	exitMarkerId = jQuery('#bus_stop_end').val();	
	
window.location = DFC_page_path+"/farecalculator.html?type=bus&ticketType="+ticketType+"&busServiceId="+busServiceId+"&entryMarkerId="+entryMarkerId+"&exitMarkerId="+exitMarkerId;

}else{
		
		alert("Please select the boarding and alighting bus stop for your trip.");
	}
	}
	
	
	
	if (    jQuery('#mode_type_select').val() == "mrt"){
		
		if ( jQuery('#mrt_stop_start').val() == jQuery('#mrt_stop_end').val() &&  jQuery('#mrt_stop_start').val() != "default" ){
			alert("Please select different boarding and alighting MRT/LRT stations");
			return false;
		}
		
	if ( jQuery('#mrt_stop_start').val() != "default" &&    jQuery('#mrt_stop_end').val()  != "default" ){
	
		
		entryMarkerId = jQuery('#mrt_stop_start').val();
		exitMarkerId = jQuery('#mrt_stop_end').val();	
		ticketType= jQuery('#fare_type_select').val();
		
	window.location = DFC_page_path+"/farecalculator.html?type=mrt&ticketType="+ticketType+"&entryMarkerId="+entryMarkerId+"&exitMarkerId="+exitMarkerId;
		
}else{
		
		alert("Please select the boarding and alighting MRT station for your trip.");
	}
	}
	
}


function showInfo_DFC(){

	if (jQuery('#mode_type_select').val() == "bus"  ){
		jQuery('#bus_option_first_step').slideDown(250);
		
		if(jQuery('#bus_service_no').val()  != null && jQuery('#bus_service_no').val()  != "default"){
		jQuery('#bus_option_second_step').slideDown(250);
		}
		jQuery('#show_info_DFC').css("display" , "none");
		jQuery('#hide_info_DFC').css("display" , "block");
		
	}
	
	if (jQuery('#mode_type_select').val() == "mrt"  ){
		jQuery('#mrt_option_step').slideDown(250);
		jQuery('#show_info_DFC').css("display" , "none");
		jQuery('#hide_info_DFC').css("display" , "block");
	}
	
}


function hideInfo_DFC(){

	if (jQuery('#mode_type_select').val() == "bus"  ){
		//jQuery('#bus_option_first_step').slideUp(250);
		jQuery('#bus_option_second_step').slideUp(250);
		jQuery('#show_info_DFC').css("display" , "block");
		jQuery('#hide_info_DFC').css("display" , "none");
	}
	
	if (jQuery('#mode_type_select').val() == "mrt"  ){
		jQuery('#mrt_option_step').slideUp(250);
		jQuery('#show_info_DFC').css("display" , "block");
		jQuery('#hide_info_DFC').css("display" , "none");
	}
}

function resetBtn(){
jQuery('#show_info_DFC').css("display" , "none");
jQuery('#hide_info_DFC').css("display" , "none");
}






(function($){$(function(){
var pass = 0;
var busStopCode;
var delimiterIndex;
var ba_road_name;
var selectRoad;
var selectCode;

$(document).ready(function()
		{

	if ( $("#busArrivalTimePanel_content").html() != ""  ){
	var mouse_is_inside_BA;
	
				$('#busArrivalTimePanel').hover(function(){ 
				    mouse_is_inside_BA=true; 
				}, function(){ 
				    mouse_is_inside_BA=false; 
				});
				
				$("body").click(function(event){ 
					
					if (event.target.id == "busServices"){  mouse_is_inside_BA=true;}
					if (event.target.id == "busRoad"){  mouse_is_inside_BA=true;}
					if (event.target.id == "busStopCode"){  mouse_is_inside_BA=true;}
					
				    if(mouse_is_inside_BA == false)
				    {
			            $("#bus-info").animate( {height : "60px"} ,1000);
			         
			            if ( $("#busService-cont").html() != ""  ){
			            $("#show_info").css("display","block");
			            $("#hide_info").css("display","none");
			            }
			            
				    }
				});
				
		        $("#bus-info").css( "height" , "60px");
	}  
		});




//retrieve cookie and set the select list option value
getArrTime();


/*------------------------------------------------------------------------------------------------------------------------------------*/
function setArrTime(){
    
if(  $("#busServices").val() != "none"){
     var busServices =  $("#busServices").val()+"_"+$("#busServices option:selected").text();     
     var busRoad =  $("#busRoad").val()+"_"+$("#busRoad option:selected").text();     
     var busStopCode = $("#busStopCode").val()+"_"+$("#busStopCode option:selected").text();     
        
    $.get("/content/publictransport/en/homepage/cookie.html?operation=addcookie&name=busServices&value="+busServices, function(data){
           // cookie added successfully
    });

    $.get("/content/publictransport/en/homepage/cookie.html?operation=addcookie&name=busRoad&value="+busRoad, function(data){
        // cookie added successfully
    });

    $.get("/content/publictransport/en/homepage/cookie.html?operation=addcookie&name=busStopCode&value="+busStopCode, function(data){
        // cookie added successfully
    });

    }
}

function getArrTime(){

	 if ( $("#busArrivalTimePanel_content").html() != "null"  && $("#busArrivalTimePanel_content").html() != "" && $("#busArrivalTimePanel_content").html() != null){
			
    $.ajax({
        url: "/content/publictransport/en/homepage/cookie.html?operation=getcookie&name=busServices"  ,
        cache: false,
         success: function(data1){  
                var busServices = trim(data1);

                $.ajax({
                    url: "/content/publictransport/en/homepage/cookie.html?operation=getcookie&name=busRoad"  ,
                    cache: false,
                     success: function(data2){  
                        var busRoad = trim(data2);
                        
                        $.ajax({
                            url: "/content/publictransport/en/homepage/cookie.html?operation=getcookie&name=busStopCode"  ,
                            cache: false,
                             success: function(data3){  
                             var busStopCode = trim(data3);
                        
                             if ( busServices != "" && busRoad != "" && busStopCode != ""  ){
                                 
                                 var busServicesArr = busServices.split('_');
                                 var busRoadArr = busRoad.split('_');
                                 var busStopCodeArr = busStopCode.split('_');

                           
                        	 setOptionsBusServices(busServicesArr[0]);  // popular the select list 
                             setOptionsBusRoad(busRoadArr[0]);// popular the select list 
                          
                            
                            getTimeArrivalInfo(busStopCodeArr[0] , "init"); // get the arrival time info from json file
                            
                            $("#busServices").val(busServicesArr[0]);
                            $("#busRoad").val(busRoadArr[0]);
                            $("#busStopCode").val(busStopCodeArr[0]);
                           
                             }else{
                            	 $("#show_info").css("display","none");
                               	 $("#hide_info").css("display","none");  
                             }
                             
            
                        },
                        error: function(data3){
                       	 $("#show_info").css("display","none");
                          $("#hide_info").css("display","none"); 
                       }});
                     
                },
                error: function(data2){
               	 $("#show_info").css("display","none");
                  	 $("#hide_info").css("display","none"); 
               }});
        },
        error: function(data1){
        	 $("#show_info").css("display","none");
           	 $("#hide_info").css("display","none"); 
           	
        }});
	   }
	 
	
    }
/*------------------------------------------------------------------------------------------------------------------------------------*/
function refresh(nextRefresh){
    var t = setTimeout(function() {busTiming( "init")},nextRefresh);
    
}

function getTimeArrivalInfo(busStopCode , type){

    $("select#busServices option").remove();
    $("select#busRoad option").remove();
    $("select#busServices ").append('<option value="none">Select a Bus Stop Category</option>');
    $("select#busRoad").append('<option value="none">Select a Road/Bus Stop Name</option>');
    for(servicesIndex = 1; servicesIndex <= inAcademicBelt.length;servicesIndex++){
        delimiterIndex = inAcademicBelt[servicesIndex-1].indexOf(':');
        if(inAcademicBelt[servicesIndex-1].substring(delimiterIndex+1) == busStopCode){
            $("select#busServices").append("<option value=academicBelt selected=selected>Bus Stops along Academic Belt</option>");
            $("select#busServices").append("<option value=busWithTimePanel>Bus Stops with Arrival Time Panel</option>");
            $("select#busServices").append("<option value=sbsServices>Other Bus Stops</option>");
            ba_road_name = inAcademicBelt[servicesIndex-1].substring(0,delimiterIndex);
            setOptionsBusServices("academicBelt");
            selectRoad=document.getElementById("busRoad")
            for(var i=0; i<selectRoad.length; i++){
                if(ba_road_name == selectRoad.options[i].value){
                    $("#busRoad option:eq("+i+")").attr("selected","selected");
                    setOptionsBusRoad(ba_road_name);
                    selectCode=document.getElementById("busStopCode");
                    for(var j=0; j<selectCode.length; j++){
                        if(busStopCode == selectCode.options[j].value){
                            $("#busStopCode option:eq("+ j +")").attr("selected","selected");
                            break;
                        }
                    }
                break;
                }
            }
        break;
        }    
    }
    for(servicesIndex = 1; servicesIndex <= withPanel.length;servicesIndex++){
        delimiterIndex = withPanel[servicesIndex-1].indexOf(':');
        if(withPanel[servicesIndex-1].substring(delimiterIndex+1) == busStopCode){
            $("select#busServices").append("<option value=academicBelt>Bus Stops along Academic Belt</option>");
            $("select#busServices").append("<option value=busWithTimePanel selected=selected>Bus Stops with Arrival Time Panel</option>");
            $("select#busServices").append("<option value=sbsServices>Other Bus Stops</option>");
            ba_road_name = withPanel[servicesIndex-1].substring(0,delimiterIndex);
            setOptionsBusServices("busWithTimePanel");
            selectRoad=document.getElementById("busRoad")
            for(var i=0; i<selectRoad.length; i++){
                if(ba_road_name == selectRoad.options[i].value){
                    $("#busRoad option:eq("+i+")").attr("selected","selected");
                    setOptionsBusRoad(ba_road_name);
                    selectCode=document.getElementById("busStopCode");
                    for(var j=0; j<selectCode.length; j++){
                        if(busStopCode == selectCode.options[j].value){
                            $("#busStopCode option:eq("+ j +")").attr("selected","selected");
                            break;
                        }
                    }
                break;
                }
            }
        break;            
        }
    }
    for(servicesIndex = 1; servicesIndex <= withOutPanel.length;servicesIndex++){
        delimiterIndex = withOutPanel[servicesIndex-1].indexOf(':');
        if(withOutPanel[servicesIndex-1].substring(delimiterIndex+1) == busStopCode){
            $("select#busServices").append("<option value=academicBelt>Bus Stops along Academic Belt</option>");
            $("select#busServices").append("<option value=busWithTimePanel>Bus Stops with Arrival Time Panel</option>");
            $("select#busServices").append("<option value=sbsServices selected=selected>Other Bus Stops</option>");
            ba_road_name = withOutPanel[servicesIndex-1].substring(0,delimiterIndex);
            setOptionsBusServices("sbsServices");
            selectRoad=document.getElementById("busRoad")
            for(var i=0; i<selectRoad.length; i++){
                if(ba_road_name == selectRoad.options[i].value){
                    $("#busRoad option:eq("+i+")").attr("selected","selected");
                    setOptionsBusRoad(ba_road_name);
                    selectCode=document.getElementById("busStopCode");
                    for(var j=0; j<selectCode.length; j++){
                        if(busStopCode == selectCode.options[j].value){
                            $("#busStopCode option:eq("+ j +")").attr("selected","selected");
                            break;
                        }
                    }
                break;
                }
            }
        break; 
        }
    }

 

 $.getJSON("/busarrival/"+ busStopCode +".json", function(data) {
  
    	var real_time = String(new Date());
        var delimiter_minutes = real_time.indexOf(":");
        var real_hour = real_time.substring(delimiter_minutes -2,delimiter_minutes);
        var real_minutes = real_time.substring(delimiter_minutes + 1,delimiter_minutes + 3);
        var serv_down = data.count;
        var time = String(data.time);
        var hourJson = time.substring(9,11);
        var minJson = time.substring(11,13);
        var strTime = time.substring(13);
        var serv_lag_check;
        var busService;
        var arrNow;
        var arrLater;
        var arrNowDisFriendly;
        var arrLaterDisFriendly;
        var currentSeconds;
        var nextRefresh;
        var ampm;
        var date_day = time.substring(0,2);
        var date_month = time.substring(2,4);
        var date_year = time.substring(4,8);
        var date_month_str;
        var hourJson_short;
        var count = 0;
        
        serv_lag_check = real_minutes-minJson;

        $("div#bus_arrival_announcement").empty();
        $("div#bus_timestamp").empty();
        $("div#busService-cont").empty();
        $("div#arrNow-cont").empty();
        $("div#arrLater-cont").empty();

        if(serv_down == 0 || hourJson != real_hour || serv_lag_check >= 10 || data.info.length == 0 ){
           $("#count").html("0");
            $("#show_info").css("display","none");
            $("#hide_info").css("display","none");
        	$("div#bus_arrival_announcement").append("<p>The current bus arrival information is not available</p>");

       }
       else{
            if(date_month == "01"){date_month_str = "Jan";}
            else if(date_month == "02"){date_month_str = "Feb";}
            else if(date_month == "03"){date_month_str = "Mar";}
            else if(date_month == "04"){date_month_str = "Apr";}
            else if(date_month == "05"){date_month_str = "May";}
            else if(date_month == "06"){date_month_str = "Jun";}  
            else if(date_month == "07"){date_month_str = "Jul";} 
            else if(date_month == "08"){date_month_str = "Aug";}
            else if(date_month == "09"){date_month_str = "Sep";}
            else if(date_month == "10"){date_month_str = "Oct";}
            else if(date_month == "11"){date_month_str = "Nov";}
            else if(date_month == "12"){date_month_str = "Dec";}
            
            $("div#bus_timestamp").append("<p>"+ date_day +" "+ date_month_str + " " + date_year +" "
            + hourJson +"&#58;"+minJson+"</p>");
            
           
           
            $.each(data.info,function(i,infoValue){
           
                busService = infoValue.bsvc;
                arrNow = infoValue.arr1;
                arrLater = infoValue.arr2;
                arrNowDisFriendly = infoValue.wc1;
                arrLaterDisFriendly = infoValue.wc2;
                
                $("div#bus-info #busService-cont").append("<p class=ptp-info-busService>"+busService+"</p>");
                if(arrNowDisFriendly == 1){
                    arrNow = (arrNow == "")? "N.A.":arrNow;
                    if(arrNow == "N.A."){
                        $("div#bus-info #arrNow-cont").append("<p class=ptp-info-arrNow>"+arrNow+"</p>");
                    }
                    else{
                        arrNow = (arrNow > 0)? (arrNow+" Mins"):"Arr";
                        $("div#bus-info #arrNow-cont").append(
                        "<p class=ptp-info-arrNow>"+arrNow+
                        " <img class=handicap-friendly src=/etc/designs/publictransport/green/images/ic_wheelchair.gif /></p>");
                    }
                 }
                 else{
                    arrNow = (arrNow == "")? "N.A.":arrNow;
                    if(arrNow == "N.A."){}
                    else{
                        arrNow = (arrNow > 0)? (arrNow+" Mins"):"Arr";
                    }
                     $("div#bus-info #arrNow-cont").append("<p class=ptp-info-arrNow>"+arrNow+"</p>");
                 }
                
                 if(arrLaterDisFriendly == 1){
                     arrLater = (arrLater == "")? "N.A.":arrLater;
                     if(arrLater == "N.A."){
                         $("div#bus-info #arrLater-cont").append("<p class=ptp-info-arrLater>"+arrLater+"</p>");
                     }
                     else{
                         arrLater = (arrLater > 0)? (arrLater+" Mins"):"Arr";
                         $("div#bus-info #arrLater-cont").append(
                         "<p class=ptp-info-arrLater>"+arrLater+
                         " <img class=handicap-friendly src=/etc/designs/publictransport/green/images/ic_wheelchair.gif /></p>");
                     }
                     
                  }
                  else{
                      arrLater = (arrLater == "")? "N.A.":arrLater;
                      if(arrLater == "N.A."){}
                      else{
                          arrLater = (arrLater > 0)? (arrLater+" Mins"):"Arr";
                      }
                      $("div#bus-info #arrLater-cont").append("<p class=ptp-info-arrLater>"+arrLater+"</p>");
                  } 
                 
                 
             	 count+=1;
                });
            

         if (type != "init"){
            $("#bus-info").animate( {height : count*20+"px"} ,1000);
            $("#show_info").css("display","none");
            $("#hide_info").css("display","block");
         }
        
        $("#count").html(count);
    
        if ($("#count").html() < 4 || $("#count").html() == ""){ 	
       	 $("#show_info").css("display","none");
       	 $("#hide_info").css("display","none");
       }
        
            
                nextRefresh = 60-strTime;
                nextRefresh *= 1000; 
                  
                if(!pass){
                    refresh(nextRefresh);
                }   
          }
});
}

$("select#busStopCode").change(busTiming = function( type){
    busStopCode = $("select#busStopCode option:selected").val();
    if(busStopCode == 'none' || busStopCode == ''){ }
    else{
    setArrTime();
    if (type == "init"){
    getTimeArrivalInfo(busStopCode , "init");
    }else{
    getTimeArrivalInfo(busStopCode , "normal");	
    }
   
}});





$("#show_info").click(function(){

	 $("#show_info").css("display","none");
     $("#hide_info").css("display","block");
     $("#bus-info").animate( {height : parseInt($("#count").html())*20 + "px"} ,1000);
});

$("#hide_info").click(function(){
	 $("#show_info").css("display","block");
     $("#hide_info").css("display","none");
	 $("#bus-info").animate( {height : "52px"} ,1000);
	});



});
})($CQ || $);
(function($){jQuery.fn.liScroll = function(settings) {
        settings = jQuery.extend({
        travelocity: 0.05
        }, settings);
        return this.each(function(){
                var $strip = jQuery(this);
                $strip.addClass("newsticker")
                var stripWidth = 1;
                var outerBox = $(this).outerWidth(true);
                $strip.find("li").each(function(i){
                stripWidth += jQuery(this, i).outerWidth(true);
                if(jQuery(this, i).outerWidth(true) == outerBox){
                    stripWidth += 400;
                }
                else{
                    stripWidth += 10;
                }
                });
                var $mask = $strip.wrap("<div class='mask'></div>");
                var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");                            
                var containerWidth = $strip.parent().parent().width();
                $strip.width(stripWidth);
                var totalTravel = stripWidth+containerWidth;
                var defTiming = totalTravel/settings.travelocity;
                function scrollnews(spazio, tempo){
                $strip.animate({left: '-='+ spazio}, tempo, "linear", function(){$strip.css("left", containerWidth); scrollnews(totalTravel, defTiming);});
                }
                scrollnews(totalTravel, defTiming);
                $strip.hover(function(){
                jQuery(this).stop();
                },
                function(){
                var offset = jQuery(this).offset();
                var residualSpace = offset.left + stripWidth;
                var residualTime = residualSpace/settings.travelocity;
                scrollnews(residualSpace, residualTime);
                });         
        }); 
}; 

$(function(){
    $("ul#tickertext").liScroll({travelocity: 0.05});
});
})($CQ || $);
var json_add = "/content/dam/publictransport/mrt_map_data/MrtMapData.json";
var json_zone = "/content/dam/publictransport/mrt_map_data/trainload.json";
var prevZone = null;

function popParentMrtMap(){   
    var options = "status=1,height=750px,width=935px,location=no,resizable=0,scrollbars=1,titlebar=no";
    openwindow = window.open("/content/publictransport/en/homepage/trainload.html","_self",options);
}

/*-------------------------Monthly Zone Data-----------------------------*/
(function($){
    function strMonth(num){
        var month;
        switch(num){
        case 1: month = "Jan"; break;
        case 2: month = "Feb"; break;
        case 3: month = "Mar"; break;
        case 4: month = "Apr"; break;
        case 5: month = "May"; break;
        case 6: month = "Jun"; break;
        case 7: month = "Jul"; break;
        case 8: month = "Aug"; break;
        case 9: month = "Sep"; break;
        case 10: month = "Oct"; break;
        case 11: month = "Nov"; break;
        case 12: month = "Dec"; break;
        default: month = null; break;
        }
        return month;
    }
    $(document).ready(
            function(){
                $.ajax({
                    global:false,
                    url: json_zone,
                    dataType:'json',
                    async: true,
                    success: function(data){
                        $.each(data.mrt,function(first,mrt){
                            $("#mrt-zone-select").append("<option value='"+mrt.station+"'>"+mrt.station+"</option>");
                        });
                    }
                });
            }
        );
    $(window).load(
    function(){
        if(getUrlParam("MapType") == "stationusage"){
            $("#mrt-zone-select").val("Admiralty");
            $("#mrt-zone-select").trigger("change");
            $("div#mrt-crowd-img").trigger("click");
        }
    });
})($CQ || $);

//Hook Event
function hookEvent(element, eventName, callback)
{
    if(typeof(element) == "string")
        element = document.getElementById(element);
    if(element == null)
        return;
    if(element.addEventListener)
    {
        if(eventName == 'mousewheel')
            element.addEventListener('DOMMouseScroll', callback, false);  
        element.addEventListener(eventName, callback, false);
    }
    else if(element.attachEvent)
        element.attachEvent("on" + eventName, callback);
}

//Unhook Event
function unhookEvent(element, eventName, callback)
{
    if(typeof(element) == "string")
        element = document.getElementById(element);
    if(element == null)
        return;
    if(element.removeEventListener)
    {
        if(eventName == 'mousewheel')
            element.removeEventListener('DOMMouseScroll', callback, false);  
        element.removeEventListener(eventName, callback, false);
    }
    else if(element.detachEvent)
        element.detachEvent("on" + eventName, callback);
}

function cancelEvent(e)
{
    e = e ? e : window.event;
    if(e.stopPropagation)
        e.stopPropagation();
    if(e.preventDefault)
        e.preventDefault();
    e.cancelBubble = true;
    e.cancel = true;
    e.returnValue = false;
    return false;
}

function scrollZoom(e)
{
    e = e ? e : window.event;
    var raw = e.detail ? e.detail * -1:e.wheelDelta / 120;
    cancelEvent(e);
    if(raw == 1 || raw > 1){
        jQuery("div#size-add").trigger("click");
    }
    else{
        jQuery("div#size-subtract").trigger("click");
    }
}

//get URL GET MapType value
function getUrlParam(paramName){
    var searchedString = window.location.search.substring(1),
    i,val,params = searchedString.split("&");
    for (i=0;i<params.length;i++){
        val = params[i].split("=");
        if (val[0] == paramName){
            return unescape(val[1]);
        }
    }
    return null;
}

/*------------------------------disable MRT image from being selected---------------------------------*/
window.onload = init;

function init() {
    if(document.getElementById("mrt-img") != null){
        disableDraggingFor(document.getElementById("mrt-img"));
        disableDraggingFor(document.getElementById("size-add"));
        disableDraggingFor(document.getElementById("size-subtract"));
        disableDraggingFor(document.getElementById("control-up-img"));
        disableDraggingFor(document.getElementById("control-down-img"));
        disableDraggingFor(document.getElementById("control-left-img"));
        disableDraggingFor(document.getElementById("control-right-img"));
    }
}

function disableDraggingFor(element){
    // this works for FireFox and WebKit in future
    element.draggable = false;
    // this works for older web layout engines
    if(element.preventDefault){
        element.onmousedown = function(event){
            element.preventDefault();
            return false;
        };
    }
    else{
        element.onmousedown = function(event) {
            return false;    //IE fix
        };
    }             
}

/*-----------------------------------------JSON Information parsing------------------------------------------*/
(function($){$(function(){
    var hovered_id;
    var usage;
    var shuttle_bus_description;
    var taxi_stand;
    var bus_stop;
    var parknride;
    var nearby_lrt;
    var building;

    $("#mrt-cont map area").hover(function(event){
        hovered_id = this.id;
        $.ajax({
            global:false,
            url: json_add,
            dataType: 'json',
            async: false,
            success: function(data) {
                $("div#mrt-specific-info-cont").empty();
                $.each(data.mrt,function(first,mrts){
                    if(mrts.id == hovered_id){
                        usage = mrts.usage;
                        shuttle_bus_description = mrts.shuttlebus;

                        $("div#mrt-specific-info-cont").append("<p class=amenities-title>Transport Nodes</p>");
                        $.each(mrts.amenities,function(second,amenitiesValue){
                            taxi_stand = amenitiesValue.taxistand;
                            nearby_lrt = amenitiesValue.lrt;
                            bus_stop = amenitiesValue.busstop;
                            park_n_ride = amenitiesValue.parknride;

                            $("div#mrt-specific-info-cont").append("<div id=amenities-img-cont></div>");
                            if(taxi_stand == "1"){
                                $("div#mrt-specific-info-cont div#amenities-img-cont").append("<div class=taxi_stand_img></div>");
                            }
                            if(nearby_lrt == "1"){
                                $("div#mrt-specific-info-cont div#amenities-img-cont").append("<div class=nearby_lrt_img></div>");
                            }
                            if(bus_stop == "1"){
                                $("div#mrt-specific-info-cont div#amenities-img-cont").append("<div class=bus_stop_img></div>");
                            }
                            if(park_n_ride == "1"){
                                $("div#mrt-specific-info-cont div#amenities-img-cont").append("<div class=park_n_ride_img></div>");
                            }
                        });
                        $("div#mrt-specific-info-cont").append("<div class=cls></div>");

                        //$("div#mrt-specific-info-cont").append("<p class=shuttle-bus-title>Shuttle Bus Service</p><p>"+shuttle_bus_description+"</p>");

                        if(mrts.nearby != ""){
                            $("div#mrt-specific-info-cont").append("<p class=nearby-title>Nearby...</p>");

                            $("div#mrt-specific-info-cont").append("<ul>");
                            $.each(mrts.nearby,function(third,nearbyValue){
                                building = nearbyValue;
                                $("div#mrt-specific-info-cont ul").append("<li>"+building+"</li>");
                            });
                            $("div#mrt-specific-info-cont").append("</ul>");
                        }
                        else{$("div#mrt-specific-info-cont").append("<br />");}
                    }
                    else{}
                });
            }});
    });
});
})($CQ || $);

/*-----------------------------Avoiding the crowd----------------------------------*/
(function($){
    var ori_width;
    var ori_height;
    var ori_posX;
    var ori_posY;
    var moved = 0;
    var ani_speed = "def";
    $(document).ready(
            function(){
                $("div#mrt-crowd-img").click(function(){
                //popParentMrtMap();
                    if(!moved){
                        document.title = "PublicTransport@SG: MRT Station Loading";
                        $("#mrt-crowd-img").css("overflow","visible").animate({left:"400px",opacity:"0"},ani_speed,function(){
                            $("#mrt-crowd-img").attr("id","mrt-crowd-reverse-img").animate({left:"10px",opacity:"1"},ani_speed);
                            $(".dropdown-select").css("display","block");
                        });
                        $("#colored-overlay").animate({width:"900px"},ani_speed);
                        ori_width=$("#mrt-img").attr("width");
                        ori_height=$("#mrt-img").attr("height");
                        ori_posX=$("#mrt-cont").attr("scrollLeft");
                        ori_posY=$("#mrt-cont").attr("scrollTop");
                        $("#mrt-img").animate({width:"900px",height:"630px"},ani_speed);
                        $("select#mrt-zone-select").show();
                        $("select#mrt-zone-select").fadeTo(ani_speed,1);
                        $("#mrt-result").fadeOut(ani_speed,function(){$("#mrt-result").hide();});
                        $("#mrt-result-cont").fadeOut(ani_speed,function(){$("#mrt-result").hide();});
                        $("#mrt-legends").fadeOut(ani_speed,function(){
                            $("#mrt-legends").hide();
                            $(".heat-bar-cont").fadeTo(ani_speed,1,function(){$(".heat-bar-cont").show();});
                        });
                        $(".mrt-map-header-title").empty().append("&nbsp;&nbsp;MRT Station Usage");
                        $("#mrt-zone-select").val("Admiralty");
                        $("#mrt-zone-select").trigger("change");
                        $("#mrt-zone-select").val("none");
                        unhookEvent('mrt-cont', 'mousewheel', scrollZoom);
                        moved = 1;
                    }
                    else{
                        document.title = "PublicTransport@SG: Train Fare Calculator";
                        $(".dropdown-select").css("display","none");
                        $("#mrt-crowd-reverse-img").animate({left:"400px",opacity:"0"},ani_speed,function(){
                            $("#mrt-crowd-reverse-img").attr("id","mrt-crowd-img").animate({left:"760px",opacity:"1"},ani_speed);
                        });
                        $("#colored-overlay").animate({width:"0px"},ani_speed);
                        $("#mrt-img").animate({width:ori_width,height:ori_height},ani_speed,function(){
                            $("#mrt-cont").animate({scrollLeft:ori_posX,scrollTop:ori_posY},ani_speed);
                        });
                        $("select#mrt-zone-select").fadeTo(ani_speed,0,function(){$("select#mrt-zone-select").hide();});
                        $("#mrt-result").fadeTo(ani_speed,1,function(){$("#mrt-result").show();});
                        $("#mrt-result-cont").fadeTo(ani_speed,1,function(){$("#mrt-result").show();});
                        $(".heat-bar-cont").fadeTo(ani_speed,0,function(){
                            $(".heat-bar-cont").hide();
                            $("#mrt-legends").fadeTo(ani_speed,1,function(){$("#mrt-legends").show();});
                        });
                        $("#mrt-zone-cont").fadeOut();
                        if(prevZone != null){
                            prevZone = prevZone.toLowerCase();
                            $(prevZone).fadeOut();
                        }
                        $("#mrt-zone-select option:first").attr('selected','selected');
                        $(".mrt-map-header-title").empty().append("&nbsp;&#45;&nbsp;Train Fare Calculator");
                        hookEvent('mrt-cont', 'mousewheel', scrollZoom);
                        moved = 0;
                    }
                });
            });
})($CQ || $);

/*-------------------------------Scrolling for the image inside the container--------------------------------*/
(function($){
    var logXStart;
    var logYStart;
    var anon_call = false;
    var init_x; 
    var init_y;
    var _posLeft;
    var _posTop;
    var smoothness;
    function handleMouseDown(e){
        if(navigator.appName == "Microsoft Internet Explorer"){
            $(this).mousedown(init_x = e.pageX);
            $(this).mousedown(init_y = e.pageY);
        }
        else{
            $(e).mousedown(init_x = e.pageX);
            $(e).mousedown(init_y = e.pageY);
        }

        if(e){
            $(this).mousemove(function(event){         
                _posLeft = $('#mrt-cont').scrollLeft();
                _posTop = $('#mrt-cont').scrollTop();
                smoothness = 10;
                logXStart = event.pageX; 
                logYStart = event.pageY;
                logXStart -= init_x;
                logYStart -= init_y;
                logXStart *= -1;
                logYStart *= -1;
                $('#mrt-cont').animate({'scrollLeft': _posLeft+logXStart/smoothness,'scrollTop': _posTop+logYStart/smoothness},0).stop(true, true);
                handleMouseMove(event);
            });
        }
    }
    function handleMouseUp(e){
        $(this).unbind('mousemove');    
    }
    function handleMouseMove(e){

    }
    $("#mrt-img").ready(function(){
        $("#mrt-img").mousedown(handleMouseDown).mouseup(handleMouseUp);
    });

})($CQ || $);

/*-----------------------------Selected option info----------------------------------*/
(function($){
    var zone_name;
    var id_value;

    function zone_pop(event){
        if($("#mrt-zone-select option:selected").val() != "none"){
            id_value = $("#mrt-zone-select option:selected").val();
            zone_name = $("#mrt-zone-select option:selected").text();
            if(prevZone == null){
                prevZone = "#mrt-"+zone_name+"-zone";
            }
            else{
                $("#mrt-zone-cont").hide();
                prevZone = prevZone.toLowerCase();
                $(prevZone).fadeOut();
                prevZone = "#mrt-"+zone_name+"-zone";
            }
            $("#mrt-zone-cont #mrt-zone-title p").text("");
            $.ajax({
                global:false,
                url: json_zone,
                dataType:'json',
                async: true,
                success: function(data){
                    $("#mrt-zone-cont #mrt-zone-title p").text("Commuter Traffic at "+zone_name+" Station");
                    $("#mrt-zone-morning-cont .mrt-station-zone-data-cont").empty();
                    $("#mrt-zone-evening-cont .mrt-station-zone-data-cont").empty();
                    $.each(data.mrt,function(first,mrt){
                    if(mrt.station == id_value){
                        $.each(mrt.cal,function(second,cal){
                            $("#mrt-zone-morning-cont .mrt-station-zone-data-cont").append(
                                    "<div class=mrt-station-zone-name><p>" + cal.month + "</p></div>");
                            $("#mrt-zone-evening-cont .mrt-station-zone-data-cont").append(
                                    "<div class=mrt-station-zone-name><p>" + cal.month + "</p></div>");
                            $.each(cal.heatam,function(third,heatam){ //am 
                                zoneColorSelector(heatam,"morning");
                            });
                            $.each(cal.heatpm,function(third,heatpm){ //am 
                                zoneColorSelector(heatpm,"evening");
                            });
                            $("#mrt-zone-morning-cont .mrt-station-zone-data-cont .mrt-station-zone-heat:last").addClass("last-col");
                            $("#mrt-zone-evening-cont .mrt-station-zone-data-cont .mrt-station-zone-heat:last").addClass("last-col");  
                        });
                    }
                    });
                }
            });
            zoneZoom(zone_name,420,150,420,99,150,25);
        }
    }


    function zoneColorSelector(heat,time){
        var numeric;
        if(time == "morning"){
            var heat_cont = $("#mrt-zone-morning-cont .mrt-station-zone-data-cont").append("<div class=mrt-station-zone-heat></div>");
            var gen_heat = $("#mrt-zone-morning-cont .mrt-station-zone-data-cont .mrt-station-zone-heat:last");
        }
        else if(time == "evening"){
            var heat_cont = $("#mrt-zone-evening-cont .mrt-station-zone-data-cont").append("<div class=mrt-station-zone-heat></div>");
            var gen_heat = $("#mrt-zone-evening-cont .mrt-station-zone-data-cont .mrt-station-zone-heat:last");    
        }
        numeric = heat;
        if(numeric == "Peak" || numeric > -3){heat_cont; gen_heat.addClass("heat-17");}
        else if(numeric<=-48){heat_cont; gen_heat.addClass("heat-1");}
        else if(numeric<=-45 && numeric>-48){heat_cont; gen_heat.addClass("heat-2");}
        else if(numeric<=-42 && numeric>-45){heat_cont; gen_heat.addClass("heat-3");}
        else if(numeric<=-39 && numeric>-42){heat_cont; gen_heat.addClass("heat-4");}
        else if(numeric<=-36 && numeric>-39){heat_cont; gen_heat.addClass("heat-5");}
        else if(numeric<=-33 && numeric>-36){heat_cont; gen_heat.addClass("heat-6");}
        else if(numeric<=-30 && numeric>-33){heat_cont; gen_heat.addClass("heat-7");}
        else if(numeric<=-27 && numeric>-30){heat_cont; gen_heat.addClass("heat-8");}
        else if(numeric<=-24 && numeric>-27){heat_cont; gen_heat.addClass("heat-9");}
        else if(numeric<=-21 && numeric>-24){heat_cont; gen_heat.addClass("heat-10");}
        else if(numeric<=-18 && numeric>-21){heat_cont; gen_heat.addClass("heat-11");}
        else if(numeric<=-15 && numeric>-18){heat_cont; gen_heat.addClass("heat-12");}
        else if(numeric<=-12 && numeric>-15){heat_cont; gen_heat.addClass("heat-13");}
        else if(numeric<=-9 && numeric>-12){heat_cont; gen_heat.addClass("heat-14");}
        else if(numeric<=-6 && numeric>-9){heat_cont; gen_heat.addClass("heat-15");}
        else if(numeric<=-3 && numeric>-6){heat_cont; gen_heat.addClass("heat-16");}
        else{
            heat_cont;
        }
    }

    function zoneZoom(zone,oWidth,oHeight,oLeft,oTop,zLeft,zTop){
        var zone_attr_id;
        var nWidth;
        var mHeight;
        var zoomDiff = 2;

        $("#mrt-zone-cont").fadeIn();
        $("#mrt-zone-cont").css("top",zTop).css("left",zLeft);
        nWidth = oWidth + (oWidth/zoomDiff);
        nHeight = oHeight + (oHeight/zoomDiff);
        nLeft = (oLeft/1.5);
        nTop =(oTop/1.5);

        zone = zone.toLowerCase();
        zone_attr_id = "#mrt-"+zone+"-zone";
        $(zone_attr_id).show();
        $(zone_attr_id).css("z-index","102");
        $(zone_attr_id).css("width",oWidth).css("height",oHeight);
        $(zone_attr_id).css("left",oLeft).css("top",oTop);

        $(zone_attr_id).animate({width:nWidth,height:nHeight,left:nLeft,top:nTop},"slow",
                function(){$(this).animate({width:oWidth,height:oHeight,left:oLeft,top:oTop},"slow",
                        function(){$(this).css("z-index","101");});}
        );}

    $(document).ready(
            function(){
                $("#mrt-zone-select").change(function(){zone_pop("");});
                $(".month-zones").click(function(){
                    $(".month-zones").removeClass("month-zones-active");
                    $(".month-zones:contains("+$(this).text()+")").addClass("month-zones-active");
                    json_zone = "/content/dam/publictransport/mrt_map_data/";
                    json_zone += ($(this).text() + "Zone.json");
                    zone_pop("");
                    $("#mrt-zone-select").trigger("change");
                });
            });

})($CQ || $);

/*-----------------------------Hover info----------------------------------*/
(function($){
    var mrt_id;
    var mrt_name;
    var hide = false;
    var time = 125;
    var checked_start_name;
    var checked_end_name;
    var checked_start = false;
    var checked_end = false;
    var delimiter_index;
    var start_location;
    var end_location;
    var board_at;
    var board_at_location;
    var alight_at;
    var alight_at_location;
    var global_start_mrtId;
    var global_end_mrtId;
    var temp_start;
    var temp_end;
    var temp_index;

    var checker = function(str_name){
        var limit;
        var end_name;
        var extra_station;
        var extra_limit;
        var extra_start_str;

        limit = str_name.indexOf("_");
        str_name = str_name.substring(limit+1);
        limit = str_name.indexOf("/");

        if(limit != -1){
            end_name = str_name.substring(limit+1);
            extra_limit = end_name.indexOf("/");
            if(extra_limit != -1){
                extra_start_str = end_name.substring(0,extra_limit);
                end_name = end_name.substring(extra_limit+1);
                extra_start_str = extra_start_str.concat("\\/");
                end_name = extra_start_str.concat(end_name);
            }
            str_name = str_name.substring(0,limit);
            str_name = str_name.concat("\\/");
            str_name = str_name.concat(end_name);
        }
        return str_name;
    };

    var server_proc = function(start,end,start_loc,end_loc){
        var snippet;
        var ani_speed = "slow";
        $("#loading").ajaxStart(function(){$("#loading").show(); $("#colored-overlay").css("width","900px").css("background","black");});
        $("#loading").ajaxStop(function(){$("#loading").hide(); $("#colored-overlay").css("width","").css("background","");});
        $.ajax({
            type:"GET",
            global:true,
            url:"mrtresult.html",
            async:true,
            data:"mrtStart=" + start + "&mrtEnd=" + end + "&startLoc=" + start_loc + "&endLoc=" + end_loc ,
            success:function(msg){                 
                $("p.try-again").append("Try again?");
                $("#mrt-result-cont").empty();
                $("#mrt-result-cont").append("<div></div>");
                $("#mrt-legends").animate({height:"0px"},ani_speed,function(){$("#mrt-legends").hide();});
                $("#mrt-result-cont div").fadeOut(ani_speed,
                        function(){ 
                    $("#mrt-result-cont").html(msg); 
                    snippet = $("#mrt-comp-result-cont");
                    $("#mrt-result-cont").empty(); 
                    $("#mrt-result-cont").append("<div id=mrt-result-cont-bg></div>");
                    $("#mrt-result-cont").append(snippet); 
                    $("#mrt-result-cont #mrt-comp-result-cont").fadeTo(ani_speed,1);
                    $("#mrt-buttons-cont").fadeOut(ani_speed);
                    $("#mrt-cont").animate({height:"0px"},ani_speed);    
                    $("#mrt-crowd-bg").animate({height:"0px"},ani_speed);
                    $("#mrt-crowd-img").animate({height:"0px"},ani_speed);
                    $("p.try-again").click(
                            function(){
                                $("#mrt-crowd-bg").animate({height:"35px"},ani_speed);
                                $("#mrt-crowd-img").animate({height:"19px"},ani_speed);
                                $("#mrt-cont").animate({height:"630px"},ani_speed);
                                $("p.try-again").empty();
                                $("#mrt-buttons-cont").fadeTo(ani_speed,1);
                                $("#mrt-legends").animate({height:"85px"},ani_speed);
                                $("#mrt-legends").show();
                            }
                    );
                }
                );
            }
        });return true; 
    };

    $(document).ready(
            function(){
                $("area.mrt-map-area").mouseover(
                        function(event){
                            if(hide){clearTimeout(hide);}
                            mrt_id = $(this).attr("id");
                            mrt_name = $(this).attr("alt");
                            if(event.pageY > 580 && event.pageX > 700){
                                $("#mrt-info-cont").css("top",event.pageY-30).css("left",event.pageX-215).css("display","block");
                            }
                            else if(event.pageX > 700){
                                $("#mrt-info-cont").css("top",event.pageY-10).css("left",event.pageX-215).css("display","block");
                            }
                            else if(event.pageY > 580){
                                $("#mrt-info-cont").css("top",event.pageY-30).css("left",event.pageX+15).css("display","block");
                            }
                            else{
                                $("#mrt-info-cont").css("top",event.pageY-10).css("left",event.pageX+15).css("display","block");
                            }
                            $("#mrt-info-header").text(mrt_id + " " + mrt_name);
                            $("#mrt-control input:radio").attr("name","mrtAction_" + mrt_id);
                            if(checked_start){
                                delimiter_index = checked_start_name.indexOf("_");
                                if(checked_start_name.substring(delimiter_index+1) == mrt_id ){
                                    $("#mrt-control input").filter('[value=board]').attr("checked",true);
                                }
                                else{
                                    $("#mrt-control input").filter('[value=board]').attr("checked",false);
                                }
                            }
                            if(checked_end){
                                delimiter_index = checked_end_name.indexOf("_");
                                if(checked_end_name.substring(delimiter_index+1) == mrt_id ){
                                    $("#mrt-control input").filter('[value=alight]').attr("checked",true);
                                }
                                else{
                                    $("#mrt-control input").filter('[value=alight]').attr("checked",false);
                                }
                            }
                            if($("#mrt-info-cont").css("top").substring(0,3) >= 450){
                                if($("html,body").queue("fx").length > 1 || $(window).scrollTop() >= 200){
                                    $("html,body").stop();
                                }
                                else{
                                    $("html,body").animate({scrollTop:300},1000,function(){$("body").stop()});
                                }
                            }
                        }
                ).mouseout(
                        function(event){
                            hide = setTimeout(function(){$("#mrt-info-cont").css("display","none");},time);
                        }
                );
                $("#mrt-info-cont").mouseover(
                        function(event){if(hide)clearTimeout(hide);}
                ).mouseout(
                        function(event){
                            hide = setTimeout(
                                    function(){
                                        $("#mrt-info-cont").css("display","none");              
                                        if($("#mrt-control input:checked").attr("checked")){
                                            if($("#mrt-control input:checked").val() == "board"){
                                                if(checked_end_name != checked_start_name){
                                                    checked_start_name = $("#mrt-control input:checked").attr("name");
                                                    checked_start = true;

                                                    board_at = checker(checked_start_name);
                                                    board_at_location = $("map area#" + board_at).attr("id");
                                                    board_at_location += " "+$("map area#" + board_at).attr("alt");
                                                    $("div#mrt-result p.results-title").empty();
                                                    $("div#mrt-result p.results-title").append("Results &#124; ");
                                                    $("div#mrt-result p.results-title-destination").empty();
                                                    $("div#mrt-result p.results-title-destination").append("Board at "+ board_at_location);

                                                    if(checked_end_name != checked_start_name){
                                                        if(checked_end == checked_start){

                                                            temp_index = checked_start_name.indexOf("_");
                                                            temp_start = checked_start_name.substring(temp_index+1);
                                                            temp_index = checked_end_name.indexOf("_");
                                                            temp_end = checked_end_name.substring(temp_index+1);

                                                            checked_start_name = checker(checked_start_name);
                                                            checked_end_name = checker(checked_end_name);
                                                            start_location = $("map area#"+checked_start_name).attr("id");
                                                            start_location += " "+$("map area#"+checked_start_name).attr("alt");
                                                            end_location = $("map area#"+checked_end_name).attr("id");
                                                            end_location += " "+$("map area#"+checked_end_name).attr("alt");
                                                            $("div#mrt-result p.results-title").empty();
                                                            $("div#mrt-result p.results-title").append("Results &#124; ");
                                                            $("div#mrt-result p.results-title-destination").empty();
                                                            $("div#mrt-result p.results-title-destination").append(start_location + " to " + end_location);

                                                            $.ajax({
                                                                global:false,
                                                                url: json_add,
                                                                dataType: 'json',
                                                                async: true,
                                                                success: function(data){
                                                                    $.each(data.mrt,function(first,mrts){
                                                                        if(mrts.id == temp_start){
                                                                            global_start_mrtId = mrts.trainStationMarkerId;
                                                                        }
                                                                        if(mrts.id == temp_end){
                                                                            global_end_mrtId = mrts.trainStationMarkerId;
                                                                        }
                                                                    });
                                                                    server_proc(global_start_mrtId,global_end_mrtId,start_location,end_location);
                                                                    checked_start = false;
                                                                    checked_end = false;
                                                                    checked_start_name = null;
                                                                    checked_end_name = null;
                                                                    global_start_mrtId = null;
                                                                    global_end_mrtId = null;
                                                                    start_location = null;
                                                                    end_location = null;
                                                                }});
                                                        }
                                                    }
                                                    else{
                                                        checked_end = false;
                                                        checked_end_name = null;
                                                    }
                                                }
                                                else{
                                                    checked_start_name = $("#mrt-control input:checked").attr("name");
                                                    checked_end_name = null;
                                                    checked_end = false;
                                                    checked_start = true;

                                                    board_at = checker(checked_start_name);
                                                    board_at_location = $("map area#" + board_at).attr("id");
                                                    board_at_location += " "+$("map area#" + board_at).attr("alt");
                                                    $("div#mrt-result p.results-title").empty();
                                                    $("div#mrt-result p.results-title").append("Results &#124; ");
                                                    $("div#mrt-result p.results-title-destination").empty();
                                                    $("div#mrt-result p.results-title-destination").append("Board at "+ board_at_location);
                                                } 
                                            }
                                            else if($("#mrt-control input:checked").val() == "alight"){
                                                if(checked_end_name != checked_start_name){
                                                    checked_end_name = $("#mrt-control input:checked").attr("name");
                                                    checked_end = true;

                                                    alight_at = checker(checked_end_name);
                                                    alight_at_location = $("map area#" + alight_at).attr("id");
                                                    alight_at_location += " "+$("map area#" + alight_at).attr("alt");
                                                    $("div#mrt-result p.results-title").empty();
                                                    $("div#mrt-result p.results-title").append("Results &#124; " );
                                                    $("div#mrt-result p.results-title-destination").empty();
                                                    $("div#mrt-result p.results-title-destination").append("Alight at "+ alight_at_location);

                                                    if(checked_end_name != checked_start_name){
                                                        if(checked_end == checked_start){

                                                            temp_index = checked_start_name.indexOf("_");
                                                            temp_start = checked_start_name.substring(temp_index+1);
                                                            temp_index = checked_end_name.indexOf("_");
                                                            temp_end = checked_end_name.substring(temp_index+1);

                                                            checked_start_name = checker(checked_start_name);
                                                            checked_end_name = checker(checked_end_name);
                                                            start_location = $("map area#"+checked_start_name).attr("id");
                                                            start_location += " "+$("map area#"+checked_start_name).attr("alt");
                                                            end_location = $("map area#"+checked_end_name).attr("id");
                                                            end_location += " "+$("map area#"+checked_end_name).attr("alt");
                                                            $("div#mrt-result p.results-title").empty();
                                                            $("div#mrt-result p.results-title").append("Results &#124; ");
                                                            $("div#mrt-result p.results-title-destination").empty();
                                                            $("div#mrt-result p.results-title-destination").append(start_location + " to " + end_location);

                                                            $.ajax({
                                                                global:false,
                                                                url: json_add,
                                                                dataType: 'json',
                                                                async: true,
                                                                success: function(data){
                                                                    $.each(data.mrt,function(first,mrts){
                                                                        if(mrts.id == temp_start){
                                                                            global_start_mrtId = mrts.trainStationMarkerId;
                                                                        }
                                                                        if(mrts.id == temp_end){
                                                                            global_end_mrtId = mrts.trainStationMarkerId;
                                                                        }
                                                                    });
                                                                    server_proc(global_start_mrtId,global_end_mrtId,start_location,end_location);
                                                                    checked_start = false;
                                                                    checked_end = false;
                                                                    checked_start_name = null;
                                                                    checked_end_name = null;
                                                                    global_start_mrtId = null;
                                                                    global_end_mrtId = null;
                                                                    start_location = null;
                                                                    end_location = null;
                                                                }});
                                                        }
                                                    }
                                                    else{
                                                        checked_start = false;
                                                        checked_start_name = null;
                                                    }
                                                }
                                                else{
                                                    checked_start_name = null;
                                                    checked_end_name = $("#mrt-control input:checked").attr("name");
                                                    checked_start = false;
                                                    checked_end = true;

                                                    alight_at = checker(checked_end_name);
                                                    alight_at_location = $("map area#" + alight_at).attr("id");
                                                    alight_at_location += " "+$("map area#" + alight_at).attr("alt");
                                                    $("div#mrt-result p.results-title").empty();
                                                    $("div#mrt-result p.results-title").append("Results &#124; ");
                                                    $("div#mrt-result p.results-title-destination").empty();
                                                    $("div#mrt-result p.results-title-destination").append("Alight at "+ alight_at_location);
                                                }
                                            }
                                        }                     
                                        $("#mrt-control input").filter('[value=board]').attr("checked",false);
                                        $("#mrt-control input").filter('[value=alight]').attr("checked",false);
                                    }
                                    ,time);
                        }
                );
            });
})($CQ || $); 
/*---------------------------------------------------------------*/

(function($){
    var counter_resize = 1;
    var size_perIncrement = 50;
    var rel_size;
    var posNeg = 1;
    var capacity = 4; //times the image can be resized.
    var comma_split; //works only if the shape is circle.
    var circ_coord_x;
    var circ_coord_y;
    var circ_rad;
    var new_coord_str;

    $.fn.resizing = function(targetAction,targetImg){
        if(counter_resize > 0 && counter_resize <= capacity){
            if(targetAction == "size-subtract"){
                posNeg = posNeg < 0? posNeg:(posNeg *= -1);
            }
            else if(targetAction == "size-add"){
                posNeg = posNeg > 0? posNeg:(posNeg *= -1);
            } 
            counter_resize += posNeg;                            
            if(counter_resize == 0){
                counter_resize = 1;
            }
            else if(counter_resize > capacity){
                counter_resize = capacity;
            }
            else{
                var mrt_img = document.getElementById("mrt-img");
                var img_width = mrt_img.clientWidth;
                var img_height = mrt_img.clientHeight;

                if(posNeg == 1){
                    rel_sizex = img_width+img_width*(size_perIncrement*2/100)/counter_resize;
                    rel_sizey = img_height+img_height*(size_perIncrement*2/100)/counter_resize;
                    $(targetImg).css("width", rel_sizex + "px").css("height",rel_sizey + "px");
                }
                else{
                    rel_sizex = img_width/(size_perIncrement*2+(size_perIncrement*2/(counter_resize+1)))*100;
                    rel_sizey = img_height/(size_perIncrement*2+(size_perIncrement*2/(counter_resize+1)))*100;
                    $(targetImg).css("width", rel_sizex + "px").css("height",rel_sizey + "px");
                }

                /*where the dynamic sync of the coordinates comes in*/
                $("area").each(function() {
                    var pairs = $(this).attr("coords").split(', ');
                    for(var i=0; i<pairs.length; i++) {
                        var nums = pairs[i].split(',');
                        for(var j=0; j<nums.length; j++) {
                            if(j != nums.length-1){
                                nums[j] = parseFloat(nums[j]); 
                                if(posNeg >0){
                                    nums[j] = nums[j]+nums[j]*(size_perIncrement*2/100)/counter_resize;
                                    //only works for 50, logic has to be improved here. 
                                }
                                else{
                                    nums[j] = nums[j]/(size_perIncrement*2+(size_perIncrement*2/(counter_resize+1)))*100;
                                }
                            }
                            else{nums[j] = parseFloat(nums[j])+(2*posNeg);}
                        }
                        pairs[i] = nums.join(',');
                    }
                    $(this).attr("coords", pairs.join(', '));
                });
                $("#mrt-size-control div").removeClass("mrt-active-size");
                switch(counter_resize){
                case 1:
                    $("#mrt-size-four").addClass("mrt-active-size");
                    break;
                case 2:
                    $("#mrt-size-three").addClass("mrt-active-size");
                    break;
                case 3:
                    $("#mrt-size-two").addClass("mrt-active-size");
                    break;
                case 4:
                    $("#mrt-size-one").addClass("mrt-active-size");
                    break;
                }   
            }
        }
        else if(counter_resize > capacity){
            counter_resize= capacity;
        }
        else{
            counter_resize = 1;
        }
    };

    $(document).ready(
            function(){
                $("#mrt-size-four").addClass("mrt-active-size");
                $("div#size-add").click(function(event){$(this).resizing((event.target || event.srcElement).id,"#mrt-img");});
                $("div#size-subtract").click(function(event){$(this).resizing((event.target || event.srcElement).id,"#mrt-img");});
                $("#mrt-cont").dblclick(function(){$("div#size-add").trigger("click");});
                hookEvent('mrt-cont', 'mousewheel', scrollZoom); 
                $('#control-left-img').click(function(){scrollAround = $('#mrt-cont').scrollLeft();$('#mrt-cont').animate({'scrollLeft': scrollAround-200},1000);});
                $('#control-right-img').click(function(){scrollAround = $('#mrt-cont').scrollLeft();$('#mrt-cont').animate({'scrollLeft': scrollAround+200},1000);});
                $('#control-up-img').click(function(){scrollAround = $('#mrt-cont').scrollTop();$('#mrt-cont').animate({'scrollTop': scrollAround-200},1000);});
                $('#control-down-img').click(function(){scrollAround = $('#mrt-cont').scrollTop();$('#mrt-cont').animate({'scrollTop': scrollAround+200},1000);});
            }
    );
})($CQ || $);
(function($){
    var temp;
    var warning = "<p style='color:red; font-weight:bold; font-size:13px; height:14px;'>Please close this page and try again</p>";
    $(document).ready(
        function(){
        	if(navigator.appName == "Microsoft Internet Explorer"){
        		temp = window.location.hash.substring(1);
        	}
        	else{
        		temp = window.location.hash.substring(1);
        		if(document.URL.search(/emailurl.html/) >= 0){
        			window.location.hash = "";
        		}
        	}
            $("input#PTP_emailUrl_hidden-parent").attr("value",temp);
            if(temp == 'null' || temp == ""){
                $(".parent-link").append(warning);
            }
            else{
                $(".parent-link").append(temp);
            }
        }
    );
})($CQ || $);

(function($){
    $(document).ready(
        function(){
        	var i=1;
        	var j=1;
            $(".form_captcha_refresh input").attr("value","Refresh");
	        if(document.URL.search(/feedback.html/) > 0 || document.URL.search(/aggregator.html/) > 0){
	            $(document).keypress(function(e) {
	                if(e.keyCode == 13) {
	                	if(i>1){
	                		setTimeout(function(){$(".form_captcha_refresh .form_button").trigger("click");},1000);
	                	}
	                    i++;
	                }
	            });
	            $("input.form_button_submit").click(function(){
	            	if(j>1){
	            		setTimeout(function(){$(".form_captcha_refresh .form_button").trigger("click");},1000);
	            	}
	            	j++;
	            });
	        }
	        else if(document.URL.search(/emailurl.html/) > 0 ){
	            $(document).keypress(function(e) {
	                if(e.keyCode == 13) {
	                	if(i>1){
	                		setTimeout(function(){$(".form_captcha_refresh div.btn").trigger("click");},1000);
	                	}
	                    i++;
	                }
	            });
	            $("input.form_button_submit").click(function(){
	            	if(j>1){
	            		setTimeout(function(){$(".form_captcha_refresh div.btn").trigger("click");},1000);
	            	}
	            	j++;
	            });
	        }
        }
    );
})($CQ || $);
function setValue(textID,targetText){
    var textfieldvalue = document.getElementById(textID);
    if(textfieldvalue.value != ""){
        document.getElementById(targetText).innerHTML = textfieldvalue.options[textfieldvalue.selectedIndex].text;
        window.open(textfieldvalue.options[textfieldvalue.selectedIndex].value);
    }
    else{
        document.getElementById(targetText).innerHTML = "Other LTA Websites";
    }
}

(function($){$(document).ready(
		function(){
			$(".breadcrumb a:last").addClass("breadcrumbselect");
			$(".useful-sites-content a").attr("target","_blank");
			var global_cur_title = document.title;
			document.title = "PublicTransport@SG: " + global_cur_title;
		});
})($CQ || $);

(function($){
    $(document).ready(
        function(){
            $("form#PTP_Aggregator").removeAttr("action"); 
            $("form#PTP_Aggregator").attr("onSubmit","javascript:return doCheckForm();");
            $("form#PTP_Aggregator p:contains('*mandatory field')").addClass("mandatory-p");
            $("form#PTP_Aggregator p:contains('Contact* (atleast one preferred contact number)')").addClass("contact-p");
        }
    );
})($CQ || $);


function popfeedback(){   
	var options = "status=1,height=525px,width=302px,location=no,resizable=0,titlebar=no,scrollbars=1";
    openwindow = window.open("/content/publictransport/en/homepage/feedback.html","Feedback",options);
}

function popEmailToFriend(info){   
	var options = "status=1,height=635px,width=740px,location=no,resizable=0,titlebar=no,scrollbars=1";
    openwindow = window.open("/content/publictransport/en/homepage/emailurl.html#"+info,"EmailFriends",options);
}

function launchTrainMap(mapType){
   var options = "status=1,height=750px,width=935px,location=0,resizable=0,scrollbars=1";
   window.open("http://"+window.location.host+"/content/publictransport/en/homepage/trainmap.html?MapType="+mapType,'TrainMap',options);
}

function launchMap(mapType){
   var options = "status=1,height=750px,width=925px,location=0,resizable=0,scrollbars=1";
   if (mapType=='normal'){
	   window.open("http://"+window.location.host+"/content/publictransport/en/homepage/map.html",'Map',options);
   }else{
	   window.open("http://"+window.location.host+"/content/publictransport/en/homepage/map."+mapType+".html",'Map',options);
   }
}

function popAggregatorForm(){   
	var options = "status=1,height=700px,width=730px,location=no,resizable=0,scrollbars=1,titlebar=no";
    openwindow = window.open("/content/publictransport/en/homepage/aggregator.html","Aggregator",options);
}

(function($){$(document).ready(
		function(){
			if($(".email-img").length > 0){
				$(".email-img").click(function(){
					if(navigator.appName == "Microsoft Internet Explorer"){
						popEmailToFriend(document.URL);
					}
					else{
						popEmailToFriend(document.URL);
					}
				});
			}
		});
})($CQ || $);
(function($){$( 
   function(){
        var hide = false;
        var time = 0;
        var temp;
        var change;

        function parentNav(navId,cancel){ 
        if(navId != temp){
        $(".noleaf-child-cont").hide();
        $(".noleaf-child-subcont").hide();
        $(".noleaf a").removeClass("static-hover");
        }
            if(cancel != "true"){
                $(".noleaf-child-cont").show();
                $(".noleaf-child-subcont." + navId ).show();
                $("#topnav-mod-bg").show();
                $(".topnav li a#" + navId).addClass("static-hover");
            }
       
            else{
                $(".noleaf-child-cont").hide();
                $(".noleaf-child-subcont" ).hide();
                $("#topnav-mod-bg").hide();
                $(".noleaf a").removeClass("static-hover");
            }
        }
        
        $(".noleaf a").hover(function(event){if(hide){clearTimeout(hide);}; change = (event.target || event.srcElement).id; parentNav(change,"false");} 
        ,function(){temp = change; hide = setTimeout(function(){parentNav(temp,"true")},time);});
        $(".noleaf-child-subcont").hover(function(){if(hide)clearTimeout(hide);}, function(){hide = setTimeout(function() {parentNav(change,"true")}, time);});
    }
);})($CQ || $);

(function($){
    var p;
    var title;
    var subchild
    var nav;
    var parOfChild;
    var nav_index;
    var ori_title;

    $(document).ready(
        function(){
            title = document.title;
            title = title.substring(20); 
            ori_title = title;
            try{
                if(title == "Homepage" || title == "Home"){}
                else{
                    nav = $(".noleaf a:contains('" + title + "')").attr("id");
                    if(nav == undefined){
                        nav = $(".noleaf-child-subcont > .noleaf-child a:contains('"+ title +"')").parent().parent().attr("class");
                        if(nav == undefined){} //for links not in topnav
                        else{
                            nav_index = nav.indexOf(" ");
                            nav = nav.charAt(nav_index + 1);
                            p = $("div.noleaf-child-subcont." + nav).html(); 
                            title = $("li.noleaf a#"+ nav).text();
                            $("div.static-onpage").html(p);
                            $("div.static-onpage > .noleaf-child a").filter(function(){return $(this).text() == ori_title;}).addClass("topnav-child-nohover");      
                            $("li.noleaf a:contains('" + title + "')").addClass("hover-removed");
                            if($.browser.msie){
                                if($.browser.version == '7.0'){
                                    $("div.static-onpage div.noleaf-child a").addClass("topnav-sync");
                                }
                            }
                        }
                    }
                    else{
                        p = $(".noleaf-child-subcont." + nav).html();
                        $("div.static-onpage").html(p);
                        $("li.noleaf a:contains('" + title + "')").addClass("hover-removed");
                        if($.browser.msie){
                            if($.browser.version == '7.0'){
                                $("div.static-onpage div.noleaf-child a").addClass("topnav-sync");
                            }
                        }
                    }
                }
            }
            catch(err){alert(err);}
        }
    );
})($CQ || $);

function doCheckForm()
{ 
    var formDOM = document.PTP_Aggregator;
    var errors = "";

    if ( isBlank(formDOM.homeNo.value) && isBlank(formDOM.officeNo.value) && isBlank(formDOM.mobileNo.value) && isBlank(formDOM.email.value))
    {   
        errors += "Please specify at least one preferred contact no.\n";
    } 
    else 
    {
        if( !isBlank(formDOM.homeNo.value) && !isValidTel(formDOM.homeNo.value) )
        {
            errors += "Invalid Home Tel no.\n";
        }
        if( !isBlank(formDOM.officeNo.value) && !isValidTel(formDOM.officeNo.value) )
        {
            errors += "Invalid Office Tel no.\n";
        }
        if( !isBlank(formDOM.mobileNo.value) && !isValidTel(formDOM.mobileNo.value) )
        {
            errors += "Invalid Mobile no.\n";
        }
        if( !isBlank(formDOM.email.value) && !isValidEmail(formDOM.email.value) )
        {
            errors += "Invalid E-Mail Address.\n";
        }
    }

    if ( errors == "")
    {           
        return true;
    } 
    else
    {
        alert(errors);
        return false;
    }           
} 

function isBlank(s)
{
    for(var i =0;i < s.length; i++)
    {
        var c = s.charAt(i);
        if((c != ' ') && (c != '\n') && (c != '\t') && (c != "" ))
            return false;
    }
    return true;
}

function isValidTel(str)
{
    var i;
    //Check phone no length.
    if (str.length < 8)
    {
        return false;
    }
    else
    {
        for (i = 0; i < str.length; i++)
        {   
            // Check that current character is number.
            var c = str.charAt(i);
            if (((c < "0") || (c > "9"))) return false;
        }
    }
    // All characters are numbers.
    return true;
}

function isValidEmail(str) 
{
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

