// VIA BOXES ---------------------------------------------------------------------------------
var via_count = 0;

// Add a via box
function addVia() {
	if (via_count==0) {
		show_the_div($("#via1"));
//rem		$("#via1").show();
	}
	if (via_count==1) {
		show_the_div($("#via2"));
//rem		$("#viaPoints div:hidden").show();
		//swapVias();
	}
	via_count++;
	if (via_count>=2) {	
	hide_the_div($('#addViaPoint'));
	show_the_div($('#optimizeRoute'));
//rem		$('#addViaPoint').hide();
//rem		$('#optimizeRoute').show();
	}
	return false;
}

// Remove a via box
function removeVia() {
	if (via_count==1 || via_count==2) {
		var parent=$(this).parents(".viaBox");
		$(parent).find("input:text").val("").change();
		$(parent).find("select").val("United Kingdom").change();
		hide_the_div($(parent));
//rem		$(this).parents(".viaBox").hide();
	}
	if (via_count >=0) {
		show_the_div($('#addViaPoint'));
		hide_the_div($('#optimizeRoute'));
//rem		$('#addViaPoint').show();
//rem		$('#optimizeRoute').hide();
	}
	via_count--;
	return false;
}

// HISTORY FUNCTIONS -------------------------------------------------------------------------------------
function updateHistoryArea(refreshed) {
	//added refreshed to be called when removing items. if called with an arg it will redraw the checkboxes with the new styles
	getCurrentHistory();
	
	var content = '';
	if( routeHistory.length == 0 ) {
		content = '<ul><li id="emptyHistory">No route history available</li></ul>';
	} else {
		content = '<ul>';
		for (i=0; i<routeHistory.length; i++) {
			var from = routeHistory[i][1];
			var to = routeHistory[i][2];
			var via = routeHistory[i][3];
			var date = routeHistory[i][4];
			
			if (via != '') {
				via = '<br/>Via: '+ via;
			}
			
			content += '<li class="clearFix"><div class="historyPlace clearFix styledInputs"><input class="checkbox" type="checkbox" id="history'+ (i+1) +'" name="history'+ (i+1) +'" value="'+ (i) +'" /><label for="history'+ (i+1) +'">From: '+ from +'<br/>To: '+ to + via +'</label></div><div class="historyDate">'+ date +'</div></li>';
		}
		content += '</ul>';
		
	}
	
	$('#mapHistory .inner').html(content);
	
	if (refreshed){
		$('#mapHistory input').customInput(); // refresh the inputs	
	}
}

function RequestQueryString( strName, strQuery ) {
	  // return the query string value
	  var strResult = "" ;
	  var intPos = strQuery.indexOf( strName );
	  if (intPos > 0) {
		 intPos += strName.length + 1 ;
		 strResult = intPos ;
		 var intEnd = strQuery.indexOf( "&", intPos )
		 // value could be at the end of the QueryString
		 if (intEnd <= 0) intEnd = strQuery.length ;
		 strResult = strQuery.substring( intPos, intEnd ) ;
	  }
	  return URLDecode(strResult) ;
}

function URLDecode( strQuery ) {
	  // decodes the URL encoding of special characters and spaces
   
	  var intPos = 0 ;
	  var strResult1 = "" ;
	  var strResult2 = "" ;
	  var intOldPos
   
	  // replace + (spaces)
	  intPos = strQuery.indexOf( "+" ) ;
	  if (intPos == -1) strResult1 = strQuery ;
	  else strResult1 = strQuery.substring(0, intPos) ;
	  while (intPos >= 0) {
		 strResult1 += " " ;
		 intOldPos = intPos + 1 ;
   
		 // get next + (space)
		 intPos = strQuery.indexOf( "+", intOldPos ) ;
		 if (intPos == -1) strResult1 += strQuery.substring( intOldPos, strQuery.length ) ;
		 else strResult1 += strQuery.substring( intOldPos, intPos ) ;
	  }
   
	  // replace character codes
	  intPos = strResult1.indexOf( "%" ) ;
	  if (intPos == -1) strResult2 = strResult1 ;
	  else strResult2 = strResult1.substring(0, intPos) ;
	  while (intPos >= 0) {
		 strResult2 += unescape(strResult1.substring( intPos, intPos + 3 )) ;
		 intOldPos = intPos + 3 ;
   
		 // get next character code
		 intPos = strResult1.indexOf( "%", intOldPos ) ;
		 if (intPos == -1) strResult2 += strResult1.substring( intOldPos, strResult1.length ) ;
		 else strResult2 += strResult1.substring( intOldPos, intPos ) ;
	  }
	  return strResult2 ;
   }

function fillValues( strQuery ) {

	var locations = new Array();
	for(var i=1; i<=4; i++) {
		var qs = RequestQueryString( ("qs_"+i), strQuery );
		var countryCode = RequestQueryString( ("countryCode_"+i), strQuery );
		if (qs != "") {
			locations.push( [qs,countryCode] );
		}
	}
	
	$("#id_qs_1").attr("value", locations[0][0]);
	$("#id_countryCode_1").val(locations[0][1]).change();
	
	$('.viaBox input:text').val("");
	$('.viaBox select').val("United Kingdom").change();
	hide_the_div($('.viaBox'),true);
	show_the_div($('#addViaPoint'));
	hide_the_div($('#optimizeRoute'));

	via_count = 0;
	if ( locations.length > 2 ) {
		for(var i=1; i<locations.length-1; i++)
		{
			addVia();
			$("#id_qs_"+(i+1)).val(locations[i][0]);
			$("#id_countryCode_"+(i+1)).val(locations[i][1]).change();
		}
	}
	$("#id_qs_4").val(locations[locations.length-1][0]);
	$("#id_countryCode_4").val(locations[locations.length-1][1]).change();
	
	var rtype = RequestQueryString( ("rtype"), strQuery );
	if (rtype == 'true'){
		$('#driving').attr('checked', true);
	} else {
		$('#walking').attr('checked', true);
	}
	
	
	var rpref = RequestQueryString( ("rpref"), strQuery );
	if (rpref == 'true'){
		$('#fastest').attr('checked', true);
	} else {
		$('#shortest').attr('checked', true);
	}
	
	
	var optimize_intermediates = RequestQueryString( ("optimizeIntermediates"), strQuery );
	if (optimize_intermediates == 'true'){
		$('#optimize_intermediates').attr('checked', true);
	} else {
		$('#optimize_intermediates').attr('checked', false);
	}
	
	
	var maptype = RequestQueryString( ("mapType"), strQuery );
	if (maptype == 'interactive'){
		$('#interactive').attr('checked', true);
	} else {
		$('#simple').attr('checked', true);
	}

}

// REVERSE ROUTE --------------------------------------------------------------------
function reverseRoute() {
	var destination = $('#id_qs_4').val();
	var destinationArea = $('#id_countryCode_4').val();
	var startPoint = $('#id_qs_1').val();
	var startPointArea = $('#id_countryCode_1').val();
	if (via_count==2) { 
		swapVias();
	}
	$('#id_qs_1').val(destination);
	$('#id_countryCode_1').val(destinationArea);
	$('#id_qs_4').val(startPoint);
	$('#id_countryCode_4').val(startPointArea);
	$('select').change();
	return false;
}

//Swap Via points - Also used in /hide via code
function swapVias() {
	$('#viaPoints').html($('.viaBox:visible').get().reverse());
	$('.removeVia').bind('click', removeVia);
	if ('function' == typeof nonIE6Function){
		$('select').selectmenu({style:'dropdown',maxHeight: 200});
	}
}


// DOCUMENT.READY --------------------------------------------------------------------------------------
$(document).ready(function() {
	// Set to use js version
	$('#jsOption').val('true');
	// Set Javascipt map option
	$('#interactive').attr('checked',true);
	$('#interactive2').val('interactive');
	$('.interactiveMapOptions label').click( function() {
		if ($(this).attr('for') == 'interactive')	{
			$('#jsOption').val('true');
		}
		else {
			$('#jsOption').val('false');
		}
	});
	
	$('.interactiveMapOptions input:radio').click( function() {
		if ($(this).val() == 'interactive')	{
			$('#jsOption').val('true');
		}
		else {
			$('#jsOption').val('false');
		}
	});
	
	// Show elements for js version
	$("#additionalOptionsHelp,#mapType,.tabs,#routeControls,.viaBox .inputWide p").show();
	
	// Setup history
	updateHistoryArea();
	$('#mapHistory').removeClass('hidden');
	
	
	// Setup remove box ready for future use
	var removeOneBox = 'You are about the delete the selected item(s) from your search history<br/><br/><a href="" class="smallBut greyBut left" id="closeRemoveBox"><img src="/library/images/btn/btn-small-grey-60.png" alt=""/><span class="text">close</span></a> <a href="" id="removeItemsRemoveBox" class="smallBut greyBut left leftGap"><img src="/library/images/btn/btn-small-grey-80.png" alt=""/><span class="text">remove</span></a>';
	
	// Setup remove box ready for future use
	var tooManySelectedRoutesBox = 'You have too many routes selected. Please select only one route.<br/><br/><a href="" class="smallBut greyBut" id="closeTooManySelectedRoutesBox"><img src="/library/images/btn/btn-small-grey-60.png" alt=""/><span class="text">close</span></a>';

	
	// Remove and selected history items with alert popup
	$("#mapHistory #removeSelected").click( function() {
		// There is
		if (($('.popupBox').length < 1 ) && ($('#mapHistory input:checked').length > 0)) {
			//$(this).parent().append(removeOneBox);
			showBubble($(this), removeOneBox, false, '220px');
			$('.popupBox #closeRemoveBox').bind("click",function(){
				$(".popupBox").css('display','none');
				$(".popupBox").remove();
				return false;
			});
			$('.popupBox #removeItemsRemoveBox').bind("click",function(){
				var checkboxID = $('#mapHistory input:checked');
				var removalArray = new Array();	
				checkboxID.each(function() {
										 
					removalArray.push(checkboxID.val());
					removeRoutes(removalArray);
					updateHistoryArea("refresh");					 
				
				});
				$(".popupBox").css('display','none');
				$(".popupBox").remove();
				return false;
			});
		}
		return false;
	});
	
	// When the clear all button is clicked uncheck all history items and remove hightlighting
	$("#mapHistory #clearAll").click( function(){
		$('#mapHistory input').each(function() {
			if($(this).is(':checked')) {
				$(this).attr('checked',false).trigger('updateState');
			}
		});
		return false;
	});
	
	// use selected route with alert popup
	$("#mapHistory #useRoute").click( function() {
		if ($('.popupBox').length < 1 ) {
			if ($('#mapHistory input:checked').length > 1) {
				showBubble($(this), tooManySelectedRoutesBox, false, '220px');
				$('.popupBox #closeTooManySelectedRoutesBox').bind("click",function(){
					$(".popupBox").css('display','none');
					$(".popupBox").remove();
					return false;
				});
			} else {
				var checkboxID = $('#mapHistory input:checked');
				checkboxID.each(function() {
				fillValues( routeHistory[$(this).val()][0] );
				});
			}
		} 
		return false;
	});
	
	// Hide via points and add click events to add/close
	hide_the_div($("#via2, #via1"),true);
	if ( $('#id_qs_3').val() != ""  && $('#id_qs_3').val() != "Enter a location or postcode") {
			addVia();
			addVia();
		
	} else if ($('#id_qs_2').val() != "" && $('#id_qs_2').val() != "Enter a location or postcode") {
			addVia();
	}
	$('#addViaPoint').bind('click', addVia);
	$('.removeVia').bind('click', removeVia);
	
	// Hide additional options
	hide_the_div($('#optimizeRoute'));
	hide_the_div($('#optimizeRouteInfoText'));
	
	// Setup reverse the route
	$('#reverseRoute').bind('click', reverseRoute);
	
	// Tabs
	$(".ui-tabs").tabs();
	
	// Set Find a map to interactive
	$('#findMap #mapType').val('interactive');
	
});