/*
* code specifically for journey_planner.cfm
*/ 

var $jq = jQuery.noConflict();
$jq(document).ready(function() {
	
	var currSelectedArrow = $jq('#currSelectedArrow');
	var curr_option = $jq('.journeyMenu .journeyOption:first');
	var optionIndex = $jq('[data]').attr('index');
	var map_fromStreet, fms_fromStreet, map_toStreet, fms_toStreet;
	
	map_fromStreet = $jq('#map_fromStreet').fms({
		stopClickedCallBack: function (stop) {
			$jq('#fromLoc').val('');
			$jq('#fromStreet').val(stop['number']);
			fms_fromStreet.dialog( "close" );
			pageTracker._trackEvent('Find My Stop', 'Origin Stop Selected', stop['number']);
		},
		mapSearchCallBack: function (searchString) {
			pageTracker._trackEvent('Find My Stop', 'Search', searchString);
		}
	});
	
	fms_fromStreet = $jq("#fms_fromStreet").dialog({
		title: 'Enter a location to find your bus stop, then simply click on the stop icon',
		height: 420,
		width: 700,
		minHeight: 400,
		minWidth:700,
		modal: true,
		autoOpen: false,
		open: function(event, ui) {
			map_fromStreet.trigger('updateStopText', $jq('#fromStreet').val());
			map_fromStreet.trigger('show');
		},
		close: function () {
			map_fromStreet.trigger('close');
		},
		resize: function() {
			map_fromStreet.trigger('resize');
		}
	});
	
	map_toStreet = $jq('#map_toStreet').fms({
		stopClickedCallBack: function (stop) {
			$jq('#fromLoc').val('');
			$jq('#toStreet').val(stop['number']);
			fms_toStreet.dialog( "close" );
			pageTracker._trackEvent('Find My Stop', 'Destination Stop Selected', stop['number']);
		},
		mapSearchCallBack: function (searchString) {
			pageTracker._trackEvent('Find My Stop', 'Search', searchString);
		}
	});
	
	fms_toStreet = $jq("#fms_toStreet").dialog({
		title: 'Enter a location to find your bus stop, then simply click on the stop icon',
		height: 420,
		width: 700,
		minHeight: 400,
		minWidth:700,
		modal: true,
		autoOpen: false,
		open: function(event, ui) {
			map_toStreet.trigger('updateStopText', $jq('#toStreet').val());
			map_toStreet.trigger('show');
		},
		close: function () {
			map_toStreet.trigger('close');
		},
		resize: function() {
			map_toStreet.trigger('resize');
		}
	});
	
	$jq('#fromStreetMapButton').click(function () {
		fms_fromStreet.dialog('open');
	});
	$jq('#toStreetMapButton').click(function () {
		fms_toStreet.dialog('open');
	});
	
	$jq('.journeyDetails').each(function (i, n) {
		
		$jq('.mapRow', n).each(function(j, m) {
			
			var leg = $jq('tr.leg[data-legIndex=' + $jq(m).attr('data-legIndex') + ']', n);
			var legDetails = $jq('.legDetails', leg);
			
			if ( legDetails.attr('data-leg') ) {
				var legMap = $jq('.map', m).journeyLegMap({
					details: $jq.parseJSON(legDetails.attr('data-leg'))
				});
				
				$jq('h3', m).click(function () {
					if ( $jq('span', this).hasClass('ui-icon-triangle-1-e') ) {
						$jq('.ui-accordion-content', m).show().find('.map').show();
						$jq('h3', m)
							.removeClass('ui-corner-all')
							.removeClass('ui-state-default')
							.addClass('ui-state-active')
							.addClass('ui-corner-top');
						$jq('span', this).removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
						$jq('a', this).html('Hide Map');
						legMap.trigger('show');
						pageTracker._trackEvent('Journey Planner Map', 'Open');
					} else {
						$jq('.ui-accordion-content', m).hide().find('.map').hide();
						$jq('h3', m)
							.removeClass('ui-state-active')
							.removeClass('ui-corner-top')
							.addClass('ui-corner-all')
							.addClass('ui-state-default');
						$jq('span', this).removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
						$jq('a', this).html('Show Map');
					}
					return false;
				});
			}
			
		});
	});
	
	$jq('#fromStreet').autocomplete({
		source: function(request, response) {
			$jq('#fromLoc').val('');
			$jq.ajax({
				url: '/iptis/ajax/locations-json.asp',
				dataType: "json",
				data: request,
				success: function(data) {
					response(data);
				}
			});
		},
		select: function(event, ui) {
				$jq('#fromLoc').val(ui.item.id);
		}
	});
	
	$jq('#toStreet').autocomplete({
		source: function(request, response) {
			$jq('#toLoc').val('');
			$jq.ajax({
				url: '/iptis/ajax/locations-json.asp',
				dataType: "json",
				data: request,
				success: function(data) {
					response(data);
				}
			});
		},
		select: function(event, ui) {
			$jq('#toLoc').val(ui.item.id);
		}
	});
			
	//$jq('.input').isUsed();
	$jq('.input input').hasText();
	
	//$jq().initJourneySearchFormAjax();
	
	$jq('.journeyPlanner .mover').ppdrag();
	var offset = $jq('.preferencesButton').offset();
	var current = $jq('.journeyPlanner').offset();
	$jq('.preferences').css({
		'left': offset.left - 70 - current.left + 'px',
		'top': offset.top + 30 - current.top + 'px'
	});
	
	$jq(".preferencesButton").toggle (
		function () {
			$jq('.preferencesHolder').show();
			return false;
		}, function () {
			$jq('.preferencesHolder').hide();
			return false;
		}
	);
	
	$jq('.journeyMenu .journeyOption').hover(function () {
		if ( $jq(this).hasClass('clickable') ) {
			$jq(this).addClass('hilight');
		}
	}, function () {
		$jq(this).removeClass('hilight');
	});
	
	$jq('.print').click(function () {
		var thisWindow = $jq(this).parents('.journeyDetails');
		var otherPanels = thisWindow.siblings().each(function (){
			$jq(this).hide();
		});
		window.print();
	});
	
	$jq('.viewAll').click(function() {
		var visableDetails = $jq('.journeyDetails:visible');
		
		if ( visableDetails.length == 1 ) {
			var jDet = $jq('.journeyDetails');
			jDet.show(300);
			$jq(this).html('Hide All');
			return false;
		} else {
			curr_option = $jq('.journeyMenu .journeyOption').filter('.disabled');
			curr_option.addClass('clickable');
			curr_option.find('ol *').css({'opacity': '1'});
			curr_option.click();
			return false;
		}
	});
	
	$jq('.printAll').click(function () {
		var jDet = $jq('.journeyDetails');
		var len = jDet.length;
		var i = 1;
		jDet.show(300, function () {
			if ( i == len ) {
				window.print();
			}
			i++;
		});
	});
	
	var animating = false;
	var queryString = '';
	var journeyIndex = 1;
	var initState = true;
	
	$jq('.journeyMenu .journeyOption').bind('click', function() {
		if( $jq(this).hasClass('clickable') && animating == false) {
			animating = true;
			
			var curr_panel = curr_option.attr('panel');
			var curr_trip = curr_option.attr('trip');
			
			queryString = curr_option.attr('queryString');
			journeyIndex = $jq(this).attr('journey');
			//This is to set the route diagram default link to the first 
			//option when the trip option is changed
			optionIndex = journeyIndex;
			
			var new_trip = $jq(this).attr('trip');
			var new_content = $jq(this).find('ol').html();
			var new_panel = 'detail';
								
			curr_option.attr('journey', journeyIndex);
			curr_option.attr('trip', new_trip);
			
			var target = curr_option.find('ol');
			target.fadeOut('300', function () {
				target.html(new_content);
				target.fadeIn('300');
			});
			
			var curr_journeyDetail = $jq('.journeyDetails[trip=' + curr_trip + '][panel=' + curr_panel + ']');
			var new_journeyDetail = $jq('.journeyDetails[trip=' + new_trip + '][panel=' + new_panel + ']');
			var curr_height = curr_journeyDetail.outerHeight();
			if ( initState ) {
				var new_height = '0px';
			} else { 
				var new_height = new_journeyDetail.outerHeight();
			}
			var panel_support = $jq('.support');
			
			$jq('.journeyDetails:visible').fadeOut(100, function () {
				panel_support.animate({'height': new_height}, 100, function () {
					new_journeyDetail.fadeIn(100, function () {
						//gmaps.trigger('resize');
						return;
					});
				});
			});
			
			//alert(currSelectedArrow.position().left);
			//alert($jq(this).position().top);
			currSelectedArrow.css({
				'top':$jq(this).position().top+'px'
			});
			
			$jq('html, body').animate({scrollTop: '0px'}, 300);
			
			$jq('.viewAll').html('Show All');
			
			$jq(this).siblings().addClass('clickable').removeClass('disabled').find('ol *');/*.animate({'opacity': '1.0'}, 300);
			$jq(this).find('ol *').animate({'opacity': '0.1'}, 300);*/
			$jq(this).removeClass('clickable').addClass('disabled').removeClass('hilight');
			
			var mapDiv = $jq('.map');
			var closeDiv =$jq('.closebar');
			mapDiv.hide();
			closeDiv.hide();			
		}
		
		animating = false;
		return false;
	});
	
	/*on-click set the url and pop-up in a new window*/
	$jq('body').delegate('.routeDiagram', 'click', function () {
		var url = $jq(this).attr('href').split("?", 1);
		var host = $jq(this).attr('data-host');
		var querystring = $jq(this).attr('data-querystring');
		url = 'http://' + host + "/journeyDiagram.asp?journey=" + optionIndex + querystring;
		var w = window.open(url, $jq(this).attr('target'), 
			"height=700,width=550,scrollbars=yes,resizable=yes,location=no");
		w.focus(); 
		return false;
	});
	
	/*on-click set the url and pop-up in a new window*/
	$jq('body').delegate('.pannelMenu a.popup', 'click', function () {
		var url = $jq(this).attr('href').split("?", 1);
		url = url + "?journey=" + journeyIndex + queryString;
		var w = window.open(url, $jq(this).attr('target'), 
			"height=580,width=1000,scrollbars=yes,resizable=yes,location=no");
		w.focus(); 
		return false;
	});	

	/* resets the journey planner search form */
	$jq('#reset').click(function () {
		$jq('#fromStreet').attr('value', '');
		$jq('#toStreet').attr('value', '');
		$jq('#fromLoc').attr('value', '');
		$jq('#toLoc').attr('value', '');
		
		/********************************************************************************************************
			//Code to reset the time and date
		*********************************************************************************************************/
		var now = new Date();
		var nowHour = now.getHours() < 13 ? now.getHours(): now.getHours() - 12;
		var nowMinutes =  Math.round(now.getMinutes()/10)*10 == 6 ?  0 : Math.round(now.getMinutes()/10)*10;
		var nowAmPm = (now.getHours() - 12 ) < 0 ? 'AM' : 'PM';
		
		$jq('#hh').val(nowHour);
		$jq('#mm').val(nowMinutes);
		$jq('#ampm').val(nowAmPm);
		$jq('#date').val( $jq('#date option:first').val() );
	});
	
	$jq('form[name=\'journeyForm\']').loadFormDetails({'cookieName' : 'mySavedPreferences'});
	$jq(".returnJourney").click(function (){
		var tempStreet = $jq('#fromStreet').val();
		var tempLocation = $jq('#fromLoc').val();
		
		$jq('#fromStreet').val($jq('#toStreet').val());
		$jq('#fromLoc').val($jq('#toLoc').val());	
		$jq('#toStreet').val(tempStreet);
		$jq('#toLoc').val(tempLocation);
		$jq('#journeyForm').submit();
		
		return false;			
	});
	
	$jq(".preferencesDetails").append($jq().getCookiePreferencesSummary());
	$jq('.timeList tr').hover(function () {
		if ( $jq(this).hasClass('clickable') ) {
			$jq(this).addClass('hilight');
		}
	}, function () {
		$jq(this).removeClass('hilight');
	});
	
	//Register the onclick events for the different departs at times on the journey planner results panel
	$jq('[data]').each(function(){
		$jq(this).click(function(){
			$jq('[data]').addClass('clickable');
			$jq(this).removeClass('clickable');
			
			var parentPanel = $jq(this).parents('[panel]');		
			var data = $jq.evalJSON($jq(this).attr('data'));
			var departTimes  = parentPanel.find('.departTime');
			var arriveTimes  = parentPanel.find('.arriveTime');
			//Build link using the index attribute, optionIndex is set as a global
			optionIndex = $jq(this).attr('index');
			var link = $jq('.routeDiagram').attr('onclick');
			
			departTimes.fadeOut(200, function () {
				var i = 0;
				departTimes.each(function(){
					$jq(this).empty();
					$jq(this).append(data[i++].depart);
				});
				departTimes.fadeIn(200);
			});
			
			arriveTimes.fadeOut(200, function () {
				i = 0;
				arriveTimes.each(function(){
					$jq(this).empty();
					$jq(this).append(data[i++].arrive);
				});
				arriveTimes.fadeIn(200);
			});
		});
	});
	
	/*allows the user to see why the first element is disabled*/
	$jq('.journeyMenu .journeyOption[trip=1]').click();
});
