var $j = jQuery.noConflict();

if (!TL) { var TL = {}; }
if (!TL.components) { TL.components = {}; }

/*Query string Function from 
http://www.nabble.com/method-plugin-for-getting-query-string-vars--to6919130.html
examples:
$.query() to get the raw values ... 

$.query().zip -> 125 (number) 
$.query(false).zip -> 00125 (string) 

$.query().hasOwnProperty('special') -> false 
$.query(false).hasOwnProperty('special') -> true 

Begin
*/


/*
 * TripPlannerWidgetEmbeded is similiar to TripPlannerWidget, 
 * but the widget is in an iframe, so submissions will try to replace the parent window
 * */

TL.components.TripPlannerWidgetEmbeded = function() {
	var _action = 'http://tripplanning.translink.ca/hiwire' ;

	return {
		/* Setup the Schedules navigation, 
		tabbing and set drop downs to current time */
		init: function() {
			this.initSchedulesNav();
			this.initDatePicker() ;
			this.selectCurrentTime() ;
		},
		// Enables rollovers for Schedules navigation
		initSchedulesNav: function() {
			var index = null ;
			var that = this ;
			$j('#schedules .menu li a').hover(
				function(){
					if ( that.index != null ) {
						$j('#schedules-info ul li:eq('+that.index+')').toggle() ;
					}
					that.index = $j('#schedules .menu li a').index(this) ;
					$j('#schedules-info ul li:eq('+that.index+')').toggle() ;
				}, function(){});
		},
		// Enable datepickers
		initDatePicker: function() {
			$j('#txtDate, #txtDateBus').datepicker({
				showOn: 'button',
				buttonImage: '/translink/images/calendar-icon.gif',
				buttonImageOnly: true,
				dateFormat: 'mm-dd-yy',
				buttonText: 'Choose'
			});
		},
		// Called when a Submit button is pressed
		submit: function( type ) {			
			switch( type ) {
				case 'TripPlanner':
					this.submitTripPlanner() ;
					break ;
				case 'NextBus':
					this.submitNextBus() ;
					break ;
				case 'LookupClosest':
					this.submitLookupClosest() ;
					break ;
				default: alert('Form couldn\'t be submitted, please contact us.') ;
			}
	
			return false ; // ignore default form action
		},
		// Submit the form on the Trip Planner tab
		submitTripPlanner: function() {
		
		    var focusedField = jQuery.trim($j('#mainform input[name=focusedField]').attr('value'));
		    
		    if (focusedField!= 'PublicNum' && focusedField != 'FindBusId')
		    {
		        var startFrom = jQuery.trim($j('#mainform input[name=Start]').attr('value'));
		        var goingTo = jQuery.trim($j('#mainform input[name=End]').attr('value'));
    		    
		        if ( startFrom == "From?" || startFrom =="" )
		        {
		            alert("Please enter where you depart from");
		            return false;
		        }
    		    
		        if (goingTo == "Going to?" || goingTo == "" )
		        {
		            alert("Please enter where you plan to go");
		            return false;
		        }
		    }else
		    {
		        this.submitNextBus() ;
		        return false;
		    }
		
			var time = this.getTimeParameters( $j('#mainform select[name=time] option:selected').text()  ) ;

      var loc = _action +"?";

      loc += "&" + '.a=iTripPlanning';
	
			loc += "&" + '.a=iItinerary';
	
			loc += "&" + '.s=' + '{$SID}';
	
			loc += "&" + 'FormState=' + 'Valid';
	
			loc += "&" + 'Start=' + $j('#mainform input[name=Start]').attr('value');
	
			loc += "&" + 'End=' + $j('#mainform input[name=End]').attr('value');
	
			loc += "&" + 'Date=' + $j('#mainform input[name=Date]').attr('value');
	
			loc += "&" + 'TripDirection=' + $j('#mainform input[name=TripDirection]:checked').val();
	
			loc += "&" + 'HourDropDown=' + time.hour;
	
			loc += "&" + 'MinuteDropDown=' + time.minute;
	
			loc += "&" + 'MeridiemDropDown=' + time.meridiem.toLowerCase();
			
			loc += "&" + 'Option=' + $j('#mainform select[name=selAdvSearch] option:selected').val();
	
	    window.top.location = loc;
	
		},
		// Submits form when Find Next Button is pressed
		submitNextBus: function() {
		
		    var stopNum = jQuery.trim($j('#mainform input[name=PublicNum]').attr('value'));
		    
		    if (jQuery.trim($j('#mainform input[name=FindBusId]').attr('value')) != '' && jQuery.trim($j('#mainform input[name=focusedField]').attr('value')) == 'FindBusId')
		    {
		        this.submitLookupClosest() ;
		        return;		    
		    }
		    else
		    {
		        if ( stopNum == '' || stopNum == 'Bus/Stop ID')
		        {
		            alert("Please enter a route (bus) number or stop ID");
		            return false;
		        }
		    }
	
			var time = this.getTimeParameters( $j('#mainform select[name=BusTime] option:selected').text()  ) ;

      var loc = _action +"?";
			
      // the field can be used for both "Bus Stop ID" or "Bus Route ID"
			if (stopNum.length > 3)	{	
          // Bus Stop ID, must be 5 digits
          if (stopNum - 0 != stopNum || stopNum.length != 5) {
            alert("Bus stop ID must be 5 digits.");
            return false;
          }
	  		  loc += "&" + '.a=' + 'iNextBusFind';
          loc += "&" + 'PublicNum=' + stopNum;
			} else {
          // Bus Route ID, 3 digits, like "001" or "C51", "N15"
          loc += "&" + '.a=' + 'iHeadwaySheet';
          if (stopNum.length == 1) {
			        stopNum = "00" + stopNum;
			    }
			    var reg =/^([0-9])*$/;
			    if (stopNum.length == 2 && reg.test(stopNum)) {
			        stopNum = "0" + stopNum;
			    }
			    loc += "&" + 'LineAbbr=' + stopNum.toUpperCase();			
			}					
	
			loc += "&" + '.s=' + '{$SID}';

			loc += "&" + 'ShowTimes=' + '1';

			loc += "&" + 'useGoogleMap=' + '1';

      loc += "&" + 'NumStopTimes=' + '5';

      loc += "&" + 'LineDirId=' + '';

      loc += "&" + 'GetSchedules=' + '1';

      loc += "&" + 'Geocode=' + '1';

      loc += "&" + 'FormState=' + '0';
						
      loc += "&" + 'FromHourDropDown=' + time.hour;

      loc += "&" + 'FromMinuteDropDown=' + time.minute;

      loc += "&" + 'FromMeridiemDropDown=' + time.meridiem;

      loc += "&" + 'SB=' + 'Search';

      loc += "&" + '.a=' + 'iTripPlanning';
	  
	  loc += "&" + 'StopDisplay=' + 'All';	  
	
			window.top.location = loc;
	
		},
		// Submits the form when Find Stop button is pressed
		submitLookupClosest: function() {
		
		    if (jQuery.trim($j('#mainform input[name=FindBusId]').attr('value')) == '')
		    {
		        alert("Please enter a location");
		        return false;
		    }
		    
	
			var loc = _action + "?";

      loc += "&" + '.a=' + 'iStopLookupClosest';

      loc += "&" + '.s=' + '{$SID}';

      loc += "&" + 'FormState=' + '0';

      loc += "&" + 'useGoogleMap=' + '1';

      loc += "&" + 'MaxDistance=' + '1000';

      loc += "&" + 'StartGeo=' + '0';

      loc += "&" + 'Start=' + $j('#mainform input[name=FindBusId]').attr('value');

      loc += "&" + '.a=' + 'iTripPlanning';
	
      window.top.location = loc;
	
		},
		
		getTimeParameters: function( t ) {
			var hour ;
			var minute ;
			var meridiem ;
			
			hour = t.substring(0, t.indexOf(":")) + "00" ;
			minute = t.substring(t.indexOf(":")+1, t.indexOf(" ")) ;
			meridiem = t.substr(t.indexOf(" ")+1, 1) ;
			
			return new Object({
				hour: hour,
				minute: minute,
				meridiem: meridiem
			}) ;
		},
		clearDefaultText:function( str, obj ) {
			if ( obj.value == str ) {
				obj.value = '' ;
			}
		},
		setFocusedField:function(str) {
		    $j('#mainform input[name=focusedField]').attr('value', str ) ;
		},
		showHelp: function( tab ) {
			$j('#'+tab+' .tab-help').removeClass('hide-tab-help') ;
			$j('select').hide() ; // hide for ie select control showing on overlays
		},
		hideHelp: function( tab ) {
			$j('#'+tab+' .tab-help').addClass('hide-tab-help') ;
			$j('select').show() ;
		},
		selectCurrentTime: function() {
			
			time = new Date() ;
			hours = time.getHours() ;
			minutes = time.getMinutes() ;
			diff = minutes%5 ;
			minutes = (minutes-diff).toString() ;
			meridiem = 'AM' ;
			
			if ( minutes.length==1 ) {
				minutes = '0' + minutes ;
			}
			
			if ( hours == 0 ) {
				hours = 12 ;
			} else if ( hours > 12 ) {
				hours = hours-12 ;
				meridiem = 'PM' ;
			}else if ( hours == 12 ) {
				meridiem = 'PM' ;
			}
	
			val = hours+":"+minutes+" "+meridiem ;
			$j("#selTime option[value='"+val+"'], #selTimeBus option[value='"+val+"']").attr('selected', 'selected') ;
		}
	} // end return
}() ;

TL.components.Rollovers = function() {
	return {
		init: function() {
			$j.preload('.rollover', { find: '-off.', replace: '-over.' });
			$j('.rollover').hover(function() {
				this.src = this.src.replace('-off.', '-over.'); // rollover
			},
			function() {
				this.src = this.src.replace('-over.', '-off.'); // rollout
			});
		}
	}
}();

// Shortcuts
var tl = TL.components ;
var TripEmbeded = TL.components.TripPlannerWidgetEmbeded ;

function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
      
$j(document).ready(function(){
	
	  //WIDGET TABS
		
		/*$j("#translinktrip_widget_accordion").accordion({
			fillSpace:true, 
			header:'h3',  
			alwaysOpen: false,
			event: 'mouseover'
		});*/
		
		// Enable datepickers
		//initDatePicker: 
		$j('#txtDate, #txtDateBus').datepicker({
			showOn: 'button',
			buttonImage: '/translink/images/calendar-icon.gif',
			buttonImageOnly: true,
			dateFormat: 'mm-dd-yy',
			buttonText: 'Choose'
		});

		// show/hide travel smart
    travelsmart = gup("travelsmart");

    if (travelsmart != 'on') {
      $j(".translinktrip_widget_travelsmart").hide();
    }
    else {
      $j(".translinktrip_widget_travelsmart").show();
    }
				
		$j('#translinktrip_trip_planner_content a.translinktrip_more_tips_link').click(function () {
      // for tabbing accessibility, hide the other elements 
      //$j('#translinktrip_trip_planner_content').hide();
      $j('#translinktrip_next_bus_content').hide();
      $j('#translinktrip_transit_system_maps_content').hide();
        
			$j('.tab-help1').removeClass('hide-tab-help');
			$j('select').hide(); // hide for ie select control showing on overlays								  
		});
		
		$j('a.translinktrip_closeOverlay').click(function () {
			$j('.tab-help1').addClass('hide-tab-help');
			$j('select').show();							  
		});
		
		$j('#translinktrip_next_bus_content a.translinktrip_more_tips_link2').click(function () {
			$j('.tab-help2').removeClass('hide-tab-help');
			$j('select').hide(); // hide for ie select control showing on overlays								  
		});
		
		$j('a.translinktrip_closeOverlay2').click(function () {
			$j('.tab-help2').addClass('hide-tab-help');
			$j('select').show();					  
		});
		
		$j('#translinktrip_transit_system_maps_content a').attr("target", "blank");
		
		//setTimeout( 'onDocumentReady()', 1 );
		
		$j('#translinktrip_widget_accordion').accordion({
			autoHeight: false,
			header:'h3'
		}); 
		

	
});

