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
*/

    (function(){ 
        
        var after_type_cast = {}; 
        var before_type_cast = {}; 
        var cached = false; 
        
        jQuery.query = function(cast) { 
                if(!cached) { 
                        // remove leading ? and trailing & 
                        var q = location.search.replace(/^\?/,'').replace(/\&$/,'').split('&'); 
                        for( var i = q.length - 1; i >= 0; i-- ) { 
                                var p = q[i].split('='), key = p[0], val = p[1]; 
                                before_type_cast[key] = val; 
                                // convert floats 
                                if(/^[0-9.]+$/.test(val)) 
                                        val = parseFloat(val); 
                                // convert booleans 
                                if(/^(true|false)$/.test(val)) 
                                        val = (val == 'true'); 
                                // ingnore empty values 
                                if(val) 
                                        after_type_cast[key] = val; 
                        } 
                        cached = true; 
                } 
                return cast === false ? before_type_cast : after_type_cast; 
        }; 

        })(); 
/*End*/

TL.components.TripPlannerWidget = 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: '/transitpolice/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 == "Departing 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 form = $j('<form></form>') ;
	
			form.attr('name', 'TripPlanner') ;
			form.attr('action', _action) ;
			form.attr('method', 'post') ;
	
			$j('<input type="hidden"></input>')
					.attr('name', '.a')
					.attr('value', 'iTripPlanning')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', '.a')
					.attr('value', 'iItinerary')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', '.s')
					.attr('value', '{$SID}')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'FormState')
					.attr('value', 'Valid')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'Start')
					.attr('value', $j('#mainform input[name=Start]').attr('value'))
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'End')
					.attr('value', $j('#mainform input[name=End]').attr('value'))
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'Date')
					.attr('value', $j('#mainform input[name=Date]').attr('value'))
					.appendTo(form) ;
					
					
			//alert($j('#mainform input[name=TripDirection]:checked').val());
	
			$j('<input type="hidden"></input>')
					.attr('name', 'TripDirection')
					.attr('value', $j('#mainform input[name=TripDirection]:checked').val())
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'HourDropDown')
					.attr('value', time.hour)
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'MinuteDropDown')
					.attr('value', time.minute)
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'MeridiemDropDown')
					.attr('value', time.meridiem.toLowerCase() )
					.appendTo(form) ;
	
	
			if ( $j('form[name=TripPlanner]').length > 0 ) {
				$j('form[name=TripPlanner]').remove() ;
			}	
	
			form.hide().appendTo('body').submit() ;
	
		},
		// 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 form = $j('<form></form>') ;
	
			form.attr('name', 'NextBus') ;
			form.attr('action', _action) ;
			form.attr('method', 'get') ;
			
			if (stopNum.length > 3)
			{	
			    $j('<input type="hidden"></input>')
					    .attr('name', '.a')
					    .attr('value', 'iNextBusFind')
					    .appendTo(form) ;
			}else
			{
				$j('<input type="hidden"></input>')
					.attr('name', '.a')
					.attr('value', 'iScheduleLookup')
					.appendTo(form) ;			
			}
	
			$j('<input type="hidden"></input>')
					.attr('name', '.s')
					.attr('value', '{$SID}')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'ShowTimes')
					.attr('value', '1')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'NumStopTimes')
					.attr('value', '5')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'LineDirId')
					.attr('value', '')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'GetSchedules')
					.attr('value', '1')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'Geocode')
					.attr('value', '1')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'FormState')
					.attr('value', '0')
					.appendTo(form) ;
					
			if (stopNum.length > 3)
			{
			    $j('<input type="hidden"></input>')
					    .attr('name', 'PublicNum')
					    .attr('value', stopNum )
					    .appendTo(form) ;
			}else
			{
			    if (stopNum.length == 1)
			    {
			        stopNum = "00" + stopNum;
			    }
			    
			    var reg =/^([0-9])*$/;
			    
			    if (stopNum.length == 2 && reg.test(stopNum))
			    {
			        stopNum = "0" + stopNum;
			    }
			    
			    $j('<input type="hidden"></input>')
					    .attr('name', 'LineAbbr')
					    .attr('value', stopNum.toUpperCase() )
					    .appendTo(form) ;			
			}					
	

	
			$j('<input type="hidden"></input>')
					.attr('name', 'FromHourDropDown')
					.attr('value', time.hour)
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'FromMinuteDropDown')
					.attr('value', time.minute)
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'FromMeridiemDropDown')
					.attr('value', time.meridiem)
					.appendTo(form) ;
	
	
			$j('<input type="hidden"></input>')
					.attr('name', 'SB')
					.attr('value', 'Search')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', '.a')
					.attr('value', 'iTripPlanning')
					.appendTo(form) ;
	
			if ( $j('form[name=NextBus]').length > 0 ) {
				$j('form[name=NextBus]').remove() ;
			}	
	
			form.hide().appendTo('body').submit() ;
	
		},
		// 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 form = $j('<form></form>') ;
	
			form.attr('name', 'FindBus') ;
			form.attr('action', _action) ;
			form.attr('method', 'post') ;
	
			$j('<input type="hidden"></input>')
					.attr('name', '.a')
					.attr('value', 'iStopLookupClosest')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', '.s')
					.attr('value', '{$SID}')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'FormState')
					.attr('value', '0')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'MaxDistance')
					.attr('value', '1000')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'StartGeo')
					.attr('value', '0')
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', 'Start')
					.attr('value', $j('#mainform input[name=FindBusId]').attr('value'))
					.appendTo(form) ;
	
			$j('<input type="hidden"></input>')
					.attr('name', '.a')
					.attr('value', 'iTripPlanning')
					.appendTo(form) ;
	
			if ( $j('form[name=FindBus]').length > 0 ) {
				$j('form[name=FindBus]').remove() ;
			}	
	
			form.hide().appendTo('body').submit() ;
	
		},
		
		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
			}) ;
		},
		addLocations: function() {
			var start = $j('input[name=FromLocation]:checked').val() ;
			var end = $j('input[name=ToLocation]:checked').val() ;
			if (start == end)
			{
			    alert("The departure and destination locations can't be the same");
			    return;
			}
			$j('#mainform input[name=Start]').attr('value', start ) ;
			$j('#mainform input[name=End]').attr('value', end ) ;
			$j.facebox.close() ;
		},
		addLocation: function() {
			var end = $j('input[name=ToLocation]:checked').val() ;
			$j('#mainform input[name=FindBusId]').attr('value', end ) ;
			$j.facebox.close() ;
		},
		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.Captions = function() {
	
	return {
		init: function( obj, radius ) {
			var bottomOffset = 30 ;
			var w = $j(obj).width() ;
			var h = $j(obj).height()+bottomOffset ;

			// Wrap the svg/canvas in a div element and append after caption text
			//$j('<div class="bg"></div>').width(w).appendTo($j(obj)) ;

			var clr = $j(obj).css('background-color') ;
			var r = new Raphael( $j(obj).get(0) , w, h) ;
		
			// Remove background color from obj
			$j(obj).css('background', 'none') ;
		
			$j(obj).css('height', h) ;
		
			r.path({fill:clr})
				.moveTo(0, (0+radius))
				.addRoundedCorner( radius, 'ur' )
				.lineTo(w-radius, 0)
				.addRoundedCorner( radius, 'rd' )
				.lineTo(w, (h-bottomOffset)-radius)
				.addRoundedCorner( radius, 'dl' )
				.lineTo(Math.round(w/2), (h-bottomOffset))
				.curveTo(Math.round(w/2), (h-bottomOffset), radius,(h-bottomOffset), 0, h)
				.andClose();
		}
	}
}() ;

TL.components.ModuleCorners = function() {

	return {
		init: function() {
			$j('.rc-module').each(function(){
				if ( $j(this).is('a') ) {
					if ($j('img', this).length == 0 ) return ;
					$j('img', this).css('padding', '0');
					var w = $j('img', this).width();
					var h = $j('img', this).height();
				} else {
					$j(this).css('padding', '0');
					var w = $j(this).width();
					var h = $j(this).height();					
				}
				var container = $j('<div class="holder-module"></div>').width(w).height(h) ;
				$j(this).wrap( container );
			});
			
			$j('.rc-module-bottom').each(function(){
				if ( $j(this).is('a') ) {
					var w = $j('img', this).width();
					var h = $j('img', this).height();
				} else {
					var w = $j(this).width();
					var h = $j(this).height();					
				}
				var container = $j('<div class="holder-module-bottom"></div>').width(w).height(h) ;
				$j(this).wrap( container );
			});
			
			$j('.holder-module').cornerz({radius:15, background: '#FFFFFF', fixIE:false}) ;
			$j('.holder-module-bottom').cornerz({radius:15, background: '#F7F8F8', corners:'bl br'}) ;
		}
		
	}
	
}();

TL.components.ImageCorners = function() {
	var _bgSmall = 'rgb(237,237,237)' ;
	var _bgMedium = 'rgb(226,239,237)' ;
	var _bgLarge = 'rgb(255,255,255)' ;
	var _bgProfile = 'rgb(237,237,237)' ;
	return {
		init: function() {
			$j('.rc-small').each(function(){
										  
				if ($j('img', this).length == 0 ) return ;
				var w = $j('img',this).width() ;
				var h = $j('img',this).height() ;
	
				var container = $j('<div class="holder-small"></div>').width(w).height(h) ;
				$j(this).wrap( container );
			});
	
			$j('.rc-medium').each(function(){
				if ($j('img', this).length == 0 ) return ;
				var w = $j('img',this).width() ;
				var h = $j('img',this).height() ;
	
				var container = $j('<div class="holder-medium"></div>').width(w).height(h) ;
				$j(this).wrap( container );
			});
	
			$j('.rc-large').each(function(){
				
				if ($j('img', this).length == 0 ) return ;
				var w = $j('img',this).width() ;
				var h = $j('img',this).height() ;
	
				var container = $j('<div class="holder-large"></div>').width(w).height(h) ;
				$j(this).wrap( container );
			});
			
			$j('.rc-feature').each(function(){
				
				if ($j('img', this).length == 0 ) return ;
				$j('img', this).css('padding', '0');
				
				var w = $j('img',this).width() ;
				var h = $j('img',this).height() ;
	
				var container = $j('<div class="holder-feature"></div>').width(w).height(h) ;
				$j(this).wrap( container );
			});
	
			$j('.rc-caption-large').each(function(){
												  
				var w = $j(this).width() ;
				var h = $j(this).height() ;		
				
				if ( $j(this).parent().is('a') ) {
					var color = $j(this).parent().parent().parent().css('background-color') ;
					var container = $j('<div class="holder-caption-large"></div>').width(w).height(h).css('background-color', color) ;
					$j(this).parent().wrap( container );
				} else {
					var color = $j(this).parent().parent().css('background-color') ;
					var container = $j('<div class="holder-caption-large"></div>').width(w).height(h).css('background-color', color) ;
					$j(this).wrap( container );
				}
				
			});
	
			$j('.rc-caption-small').each(function(){
				var w = $j(this).width() ;
				var h = $j(this).height() ;
				
				if ( $j(this).parent().is('a') ) {
					var color = $j(this).parent().parent().parent().css('background-color') ;
					var container = $j('<div class="holder-caption-small"></div>').width(w).height(h).css('background-color', color) ;
					$j(this).parent().wrap( container );
				} else {
					var color = $j(this).parent().parent().css('background-color') ;
					var container = $j('<div class="holder-caption-small"></div>').width(w).height(h).css('background-color', color) ;
					$j(this).wrap( container );
				}
				
			});
			
			$j('.rc-profile').each(function(){
				var w = $j(this).width() ;
				var h = $j(this).height() ;
	
				var container = $j('<div class="holder-profile"></div>').width(w).height(h) ;
				$j(this).wrap( container );
			});
	
			$j('.holder-profile').cornerz({radius:15, background: _bgProfile}) ;
			$j('.holder-small').cornerz({radius:15, background: _bgSmall }) ;
			$j('.holder-medium').cornerz({radius:15, background: _bgMedium }) ;
			$j('.holder-feature').cornerz({radius:15, background: _bgSmall }) ;
			
			$j('.holder-large').cornerz({radius:15, background: _bgLarge, corners: 'tl tr'}) ;
			$j('.holder-caption-large').each(function(){
				$j(this).cornerz({radius:20, background: $j(this).css('background-color')}) ;
			});
			$j('.holder-caption-small').each(function(){
				if($j(this).next().is('.small-text')) {
					$j(this).cornerz({radius:20, background: $j(this).css('background-color'), corners: 'tl tr'}) ;
				} else {
					// remove the bottom padding so the bottom corners are displayed properly
					$j(this).css('padding', '0');
					// Round all corners if small image has no caption text
					$j(this).cornerz({radius:20, background: $j(this).css('background-color')}) ;
				}
			});
		}
	} // 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
			});
		}
	}
}();

TL.components.Corners = function() {
	return {
		init: function() {
			
			/** 
			* Initialize corners from the inside most elements
			* and work outwards to resolve temporarily bottom artifacts in IE6
			*/
			
			$j('.form-message').cornerz({radius:15, background: '#F7F8F8'}) ;
			
			$j('.cameras h2').cornerz({radius:8, background: '#FFF'}) ;
			
			$j('.cameras .details .scroll-container').cornerz({radius:8, background: '#dedede'}) ;
			$j('.cameras .details h2').cornerz({radius:8, background: '#dedede'}) ;
			$j('.cameras .details').cornerz({radius:15, background: '#FFF'}) ;
			$j('.cameras').cornerz({radius:15, background: '#ededed'}) ;
			
			$j('#login-search-box li.bg').cornerz({radius:3, background: '#FFFFFF' }) ;
			$j('.call-to-action').cornerz({ radius: 15, background: '#F7F8F8' });
			$j('.call-to-action-ol').cornerz({ radius: 15, background: '#FFFFFF' });
			$j('.ol-list-op').cornerz({ radius: 5, background: '#FFFFFF' });
			$j('.ol-list-op2').cornerz({ radius: 5, background: '#FFFFFF' });
			
			$j('.index-title-module').cornerz({ radius: 20, background: '#F7F8F8' });
			
			$j('.feature-format-link').cornerz({ radius: 10, background: '#F7F8F8' });
			$j('.feature-format-link h2').cornerz({ radius: 5, background: '#EDEDED' });
			$j('.medium-format-link').cornerz({ radius: 10, background: '#F7F8F8' });
			$j('.small-format-link').cornerz({ radius: 10, background: '#F7F8F8' });
			$j('.external-links h2').cornerz({ radius: 5, background: '#ededed' });
			$j('.external-links').cornerz({ radius: 15, background: '#F7F8F8' });
			
			
			$j('.caption .text').cornerz({ radius: 25, corners: "tl, tr, br", background: '#F7F8F8' });
			$j('.page-module-rss-list').cornerz({ radius: 15, background: '#EDEDED' });
			$j('.callout-large').cornerz({ radius: 15, background: '#EDEDED' });
			
			// When class is applied directly to p tag in content editor
			$j('p.inline-callout').each(function(){
				$j(this).removeClass('inline-callout');
				$j(this).wrap('<div class="inline-callout"></div>') ;
			});
			$j('.inline-callout').cornerz({ radius: 15, background: '#EDEDED' });
			
			
			$j('.externalLinks h2').cornerz({ radius: 5, background: '#EDEDED' });
			$j('.callout-large h2, .table-wrapper-wide h2, .table-wrapper-mid h2').cornerz({ radius: 5, background: '#FFFFFF' });
			$j('.subsidiaryLinks h2').cornerz({ radius: 5, background: '#F7F8F8' });

			$j('.footer h2').cornerz({ radius: 8, background: '#EDEDED' });
			
			$j('.person').cornerz({radius:15, background:'#EDEDED'});
			$j('.alertFilterBox').cornerz({radius:15, background:'#FFF'});
			$j('.alertListGrey').cornerz({radius:10, background:'#FFF'});
			
			$j('.inner-gray-box').cornerz({radius:15, background:'#FFF'});
			$j('.trip-planner-tips').cornerz({radius:15, background:'#edf5f4'});
			
			$j('.tab-help-middle-grey').cornerz({radius:5, background:'#FFF'});
			
			
			$j('.job .thumb').cornerz({ radius: 15, background: '#FFF'});
			$j('.jobs-online .featured').cornerz({ radius: 15, background: '#E2EFED' });
			$j('.jobs-online h2').cornerz({ radius: 5, background: '#E2EFED' });
			
			
			$j('.how-to-apply h2:first').cornerz({ radius: 5, background: '#ededed' });
			$j('.how-to-apply .callout').cornerz({ radius: 15, background: '#ededed' });	
			$j('.jobs-online, .how-to-apply').cornerz({ radius: 15, background: '#F7F8F8' });
			
			$j('.road-details .status-box .status, .road-details .status-box .schedule').cornerz({ radius: 5, background: '#fff' });
			
			$j('.related-docs h2.bg').cornerz({radius:7, background: '#F7F8F8', corners:"tr tl"}) ;
			$j('.small-promo h2.bg, .popularTopics h2.bg, .related-items h2.bg, .external-links-small h2.bg, .module-recent-posts h2.bg, .module-blog-archives h2.bg').cornerz({radius:7, background: '#F7F8F8'}) ;
			
			$j('#content .page-not-found .white-bg').cornerz({radius:15, background:'#E2EFED'}) ;
			
			$j('#content .pr').cornerz({radius:15, background:'#EDEDED'}) ;
			$j('#content .pr h2').cornerz({radius:8, background:'#fff'}) ;
			
			$j('.find-stop').cornerz({radius:10, background: '#edf5f4'}) ;
			$j('.road-details').cornerz({radius:15, background: '#ededed'}) ;
			
			$j('.sitemap .section').cornerz({radius:15, background: '#F7F8F8'}) ;
			$j('#content .page').cornerz({ radius: 15, background: '#F7F8F8' });
			
		}
	}
}();

TL.components.Popup = function() {
	return {
		open: function( opts ) {
			var options = new Array() ;
			for(feature in opts.features) {
				options.push(feature+'='+opts.features[feature]) ;
			}
			var popup = window.open(opts.href, opts.wname, options.join(',')) ;
			popup.focus() ;
		}
	}
}() ;

// Adds corners to images and text in .page .callout
TL.components.CalloutCorners = function() {
	return {
		init: function() {
	
			$j('.callout').each(function(){
				var hasText = ( $j('.txt', this).length > 0 ) ? true : false ;
				var hasImages = ( $j('img', this ).length > 0 ) ? true : false ;
				
				if ( !hasImages ) {
					// No images, just round the corners for text callout
					if ( hasText ) {
						$j('.txt', this).css('margin', '10px 0').cornerz({ radius: 15, background: '#EDEDED'});
					}
					return ;
				} else {
					if ( !hasText ) {
						// No text call out, just round all image corners
						$j('img', this).each(function(){
							var w = $j(this).width() ;
							var h = $j(this).height() ;
							var container = $j('<div></div>').width(w).height(h).css('margin', '10px 0') ;
							
							$j(this).wrap(container).parent().cornerz({ radius: 15, background: '#EDEDED' });
						});
					} else {
						// .txt doesn't need tl or tr corners
						$j('.txt', this).cornerz({ radius: 15, background: '#EDEDED', corners: 'bl br'});
						
						// round all image corners, and only the top corners of 
						// the image which is directly above the text callout
						$j('img', this).each(function(){
							var siblingIsText = $j(this).next().is('.txt') ;
							var w = $j(this).width() ;
							var h = $j(this).height() ;
							
							if ( siblingIsText ) {
								var container = $j('<div></div>').width(w).height(h).css('margin-top', '10px') ;
								$j(this).wrap(container).parent().cornerz({ radius: 15, background: '#EDEDED', corners: 'tl tr' });
		
							} else {
								var container = $j('<div></div>').width(w).height(h).css('margin', '10px 0') ;
								$j(this).wrap(container).parent().cornerz({ radius: 15, background: '#EDEDED'});
							}
						});
					}
				}
			});
		} // end init
	} // end return
}() ;

TL.components.Search = function() {
    return {
//            init: function() {
//                //alert('search init');
//                if($j('.search-pagination').length > 0)
//                {
//                    //alert('pagination element found');
//                    $j('.search-pagination a').click = function() {
//                        //alert('pager clicked');
//                        //var intervalJob = setInterval(this.searchResultsLoaded, 1);
//                    }
//                }
//            },
//            searchResultsLoaded: function() {
//                if($j('.search-pagination').length > 0) 
//                {
//                    clearInterval(intervalJob);
//                    //alert('results loaded');
//                }
//            },
            submit: function() {
                var tzOffset = -new Date().getTimezoneOffset();
                var searchString = $j.trim(document.getElementById('ctl02_ctl01_TXTQuery').value);
                
                if (searchString == '')
                {
                    alert('Search string is empty');
                }
                else
                {
                    location.href = '/site-info/search-results.aspx?&amp;lcid=9&amp;q=' + encodeURIComponent(searchString) + '&amp;t=' + tzOffset;
                }
            },
			update: function() {
				$j('.search-heading').cornerz({radius:5, background:'#EDEDED'}) ;
				$j('.result .success').cornerz({radius:10, background:'#EDEDED'}) ;	
			}
        }
}();

TL.components.TableWrappers = function() {
    return {
            init: function() {
				/** Table Styling **/
				if ( $j('.table-wrapper table, .table-wrapper-wide table, .table-wrapper-mid table').length == 0 ) {
					return ;
				}
				
				$j('.table-wrapper table, .table-wrapper-wide table, .table-wrapper-mid table').each( function( i ) {
				
					// Make sure there is content in the cell otherwise the inserted round corners won't display
					if ( $j('thead th:first', this).html() == '' ) {
						 $j('thead th:first', this).html('&nbsp;') ;
					}
				
					if ( $j('thead th:last', this).html() == '' ) {
						 $j('thead th:last', this).html('&nbsp;') ;
					}
					
					// Set the first column to a fixed width for alignment
					if ($j('thead th', this).length > 1) {
						$j('thead th:first', this).css('width', '120px' ) ;
					}

					// Add corners to the first and last TH cell in the THEAD
					
					// .css('padding') is not reliable
					var t = $j('thead th', this).css('padding-top') ;
					var r = $j('thead th', this).css('padding-right') ;
					var b = $j('thead th', this).css('padding-bottom') ;
					var l = $j('thead th', this).css('padding-left') ;
					
					var theadCornerLeft = $j('<div class="thead-corner-left"></div>');
					
					$j('thead th:first', this)
						.css('background', 'none')
						.css('padding', '0px')
						.css('color', '#FFF')
						.wrapInner( theadCornerLeft );
					
					
					// Only add the right corner if there is more then one column
					if ($j('thead th', this).length > 1) {
						var theadCornerRight = $j('<div class="thead-corner-right"></div>');
							
						$j('thead th:last', this)
							.css('padding', '0px')
							.wrapInner( theadCornerRight ) ;
					}	
						
					// set the inner divs to equal heights
					var h = 0 ;
					$j('thead th', this).each(function(){
						if ( $j(this).height() > 0 ) {
							h = $j(this).height() ;	
						}
					});
					
					
					$j('.thead-corner-left, .thead-corner-right', this).each(function(){
						$j(this).height(parseInt(h)-parseInt(t)-parseInt(b)) ;
					});
					
					if ( $j('.table-wrapper-wide table .olympic-thead').length == 0 ) {
					// Add row striping on odd rows
					    $j(this).find('tbody tr:odd').css('background-color', 'rgb(237,245,244)') ;
					}
										
					$j(this).css('width', '100%') ;
				
				}) ;
				
				// Initialize all corners on table related markup
				$j('.thead-corner-left').cornerz({radius:5, background:'#fff'}) ;
				$j('.thead-corner-right').cornerz({radius:5, background:'#fff', corners: 'tr, br'}) ;
				$j('.tbody-corner-left').cornerz({radius:5, background:'#fff'}) ;
				//$j('.row-corner-left').cornerz({radius:5, background:'#fff', corners: 'tl, bl' }) ;
				//$j('.row-corner-right').cornerz({radius:5, background:'#fff', corners: 'tr, br' }) ;
				$j('.table-wrapper').cornerz({ radius: 15, background: '#EDEDED' });
				$j('.table-wrapper-mid').cornerz({ radius: 15, background: '#EDEDED' });
				$j('.table-wrapper-wide').cornerz({ radius: 15, background: '#EDEDED' });
            }
        }
}();

TL.components.OlympicPledge = function() {
    return {
        adjustValues: function(curObj, week1, week2) {
            var wk1 = $j(week1);
            var wk2 = $j(week2);
            if ( $j(curObj).is(':checked') )
            {
                for(i=0; i < wk1.length; i++)
                {
                    $j(wk2[i]).val( $j(wk1[i]).val() );
                    $j(wk2[i]).attr("disabled",true);
                }
                
            }
            else
            {
                for(i=0; i < wk1.length; i++)
                {
                    //$j(wk2[i]).val("");
                    $j(wk2[i]).removeAttr("disabled");
                }	            
            }
            this.calculateOPSummary();
        },
        calculateOPSummary: function() {
            var ttlTrips = 0;
            var noCommute = 0;
            var sustainTrips = 0;
            
            $j('.OPwk0').each(function() {
                ttlTrips += ( $j(this).val()=='' ) ? 0 : (+$j(this).val());
            });
            ttlTrips = ttlTrips*2*3;
            
            var driveAloneTrips = $j('.OPwk0.driveAlone').val()*2*3;
            var driveAloneTripsOlympics = 0;
            var driveAloneTripsPct = 0;
           
            $j('.OPwk1.driveAlone, .OPwk2.driveAlone, .OPwk3.driveAlone').each(function() {
                driveAloneTripsOlympics += ( $j(this).val()=='' ) ? 0 : (+$j(this).val());
            });
            
            driveAloneTripsOlympics = driveAloneTripsOlympics*2;
            
            if ((driveAloneTrips-driveAloneTripsOlympics)!=0 && driveAloneTrips != 0)
            {
                $j('.tripsReduced').val(driveAloneTrips-driveAloneTripsOlympics);
                driveAloneTripsPct = Math.round((driveAloneTrips-driveAloneTripsOlympics)/driveAloneTrips*100);
                $j('.tripsReducedPct').val(Math.round((driveAloneTrips-driveAloneTripsOlympics)/driveAloneTrips*100));
            }
            else
            {
                $j('.tripsReduced').val(0);
                $j('.tripsReducedPct').val(0);
            }
            
            $j('.OPwk1.noTrips, .OPwk2.noTrips, .OPwk3.noTrips').each(function() {
                noCommute += ( $j(this).val()=='' ) ? 0 : (+$j(this).val());
            });
            
            noCommute = noCommute*2;
            
            $j('.sustainableTrips').val(ttlTrips-driveAloneTripsOlympics);
            
            if ((ttlTrips-driveAloneTripsOlympics) > 0)
            {
                $j('.sustainablePct').val(Math.round((ttlTrips-driveAloneTripsOlympics)/ttlTrips*100));
            }
            else
            {
                $j('.sustainablePct').val(0);
            }
            
            if (noCommute > 0) 
            {
                $j('.ttlReducedTrips').val(noCommute);
                $j('.ttlReducedTripsPct').val(Math.round(noCommute/ttlTrips*100));
            }
        },
		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() ;
		},        
        init: function() {
            $j("th.ttipTarget").mouseenter(function(){
                $j("div.op-help",this).removeClass("hide-op-help");
            }).mouseleave(function(){
                $j("div.op-help",this).addClass("hide-op-help");
            });
		}
    }
}();

// Shortcuts
var tl = TL.components ;
var Trip = TL.components.TripPlannerWidget ;
var OP = TL.components.OlympicPledge ;


/**
* On DOM Ready, execute any initialization scripts that are required
*/

$j(document).ready(function() {

	// superfish can be called for every page
	$j('ul.sf-menu').superfish({
			autoArrows: false,
			dropShadows: false
	});
	
	// Apply styles to content editor tables
	tl.TableWrappers.init() ;
	
	// Add corners to images using jquery cornerz
	tl.ImageCorners.init() ;
	
	// Add corners to images used in modules
	tl.ModuleCorners.init() ;
	
	// Add corners to Callout elements
	tl.CalloutCorners.init() ;	
	
	// Initialize corners
	tl.Corners.init() ;

	// Preloads hover states and adds rollovers
	tl.Rollovers.init() ;


	
	//tl.Search.init() ;
	
	// Draw speech bubbles for pages with captions
	if ( $j('.captions').length > 0 ) {
		tl.Captions.init('.captions', 30) ;
	}
	
	// init Trip Planner Widget
	if ( $j('#tripDashboard').length > 0 ) {
		Trip.init() ;
	}
	
	if ( $j('#alerts').length > 0 ) {
		var active_panel = function() {
			var index = 0 ;
			$j('h3', '#alerts').each(function( i ) {
				if ( $j(this).hasClass('active') ) {
					index = i ;
					return false ;
				}
			}) ;
			return index ;	
		}() ;
		
		$j('#alerts').accordion({fillSpace:true, header:'h3', active: active_panel, alwaysOpen: false });
	}
	
	
	
	
	if ( $j('#tabs').length > 0 ) {
	    //alert($j.query().tab);
		$j('#tabs > ul').tabs({ selected: $j.query().tab });
	}

	// ** Important:** Facebox must be initialized after Corners
	if ( $j('a[rel*=facebox]').length > 0 ) {
		$j('a[rel*=facebox]').facebox({
			loading_image : '/transitpolice/images/facebox/loading.gif',
			close_image   : '/transitpolice/images/facebox/closelabel.gif'
		});
	}
	

	// Equal heights for Sitemap sections
	if ( $j('.sitemap').length > 0 ) {
		$j('.sitemap .row').each(function(i){
			var h = 0 ;
			$j(this).children().each(function(){
				if ( $j(this).height() > h ) { h = $j(this).height() ; }
			}) ;
			$j(this).children().css('height', Math.round(h)) ;
		}) ;
	}

	$j('.popup-careers').click(function(){

		TL.components.Popup.open({
			href: this.href,
			wname: 'Careers',
			features: {
				width: 700,
				height: 600,
				resizable: true,
				scrollbars: false
			}
		}) ;

		return false ;
	}) ;
	
	/* Olympic Pledge */
	if ($j('.OPwk0').length > 0) 
	{
	    OP.init();
	    tl.OlympicPledge.calculateOPSummary();
	    
	    $j('.OPwk0, .OPwk1, .OPwk2, .OPwk3').blur(function () {
	        tl.OlympicPledge.calculateOPSummary();
//	        if ($j(".sameAsWk1 input[type='checkbox']").is(":checked"))
//	        {
//	            tl.OlympicPledge.adjustValues(".sameAsWk1 input[type='checkbox']", '.OPwk1', '.OPwk2');
//	        }
//	        if ($j(".sameAsWk2 input[type='checkbox']").is(":checked"))
//	        {
//	            tl.OlympicPledge.adjustValues(".sameAsWk2 input[type='checkbox']", '.OPwk2', '.OPwk3');
//	        }
	    });
//	    $j(".sameAsWk1 input[type='checkbox']").click(function() {
//	        tl.OlympicPledge.adjustValues(this, '.OPwk1', '.OPwk2');
//	        if ($j(".sameAsWk1 input[type='checkbox']").is(":checked"))
//	        {
//	            tl.OlympicPledge.adjustValues(".sameAsWk2 input[type='checkbox']", '.OPwk2', '.OPwk3');
//	        }
//	    });
//	    $j(".sameAsWk2 input[type='checkbox']").click(function() {
//	        tl.OlympicPledge.adjustValues(this, '.OPwk2', '.OPwk3');
//	    });	    
	}

});

