/*
 *station_lines_data.js
 *This provides helper functions to query a webservice for station and line information.  It
 *is currently setup to call a local service to obtain data.  It will eventually get its data
 *from CQ. 
 */

/*This is used to cache dropdown values so the service doesn't get hit constantly.
 * Currently the cache is reset upon reset.  We may want to improve this in the future.
 */
var cache = [];
var jsHost = (("https:" == document.location.protocol) ? "https://" : "http://");
var lineLoading = "";
var lineDefault = "";
var stationLoading = "";
var stationDefault = "";
var needLineSelect = "";


function getLabelValues()
{
	lineLoading = $("label#lineLoadingLabel").html();
	lineDefault = $("label#lineDefaultLabel").html();
	stationLoading = $("label#stationLoadingLabel").html();
	stationDefault = $("label#stationDefaultLabel").html();
	needLineSelect = $("label#needLineSelect").html();


	if(lineLoading == null)
	{
		lineLoading = "";
	}
	if(lineDefault == null)
	{
		lineDefault = "";
	}
	if(stationLoading == null)
	{
		stationLoading = "";
	}
	if(stationDefault == null)
	{
		stationDefault = "";
	}
	if(needLineSelect == null)
	{
		needLineSelect = "";
	}
}
/*
 * updateStations is used in order to populate start and end station drop downs based upon a selected line
 * 
 * PARAMS:
 * lineSelect: this is the dropdown object that contains the selected line
 * 
 * startStationSelect: This is one of the dropdowns that will be updated
 * 
 * endStationSelect: This is one of the dropdowns that will be updated
 * 
 * markSelect: This will take the current dropdown value, and make a matching value
 * the default selected value upon re-population. Set this to true basically only if
 * you are trying to default the dropdown to a previous value upon page refresh.
 * 
 */
function updateStations(lineSelect, startStationSelect, endStationSelect, markSelect){

	//The value here is irrelevant is markSelect is false, otherwise it is the default value
	 var loadOption1 = '<option value="' + startStationSelect.val() + '">' + stationLoading +'</option>';
	 var loadOption2 = '<option value="' + endStationSelect.val() + '">' + stationLoading + '</option>';
	 startStationSelect.html(loadOption1);
     endStationSelect.html(loadOption2);
	 
	 var lineValue = lineSelect.val();
	 if (lineValue) { //Make sure a line is selected
        if(cache[lineSelect.val()])
        {
        	//if value is already in the cache
            handleStationUpdate(cache[lineSelect.val()],lineSelect,startStationSelect, endStationSelect, markSelect);
        }else{
        	//if we need to get the value from the service
			lineValue = lineValue.split('_');
			
		    $.getJSON(jsHost + "metrarail.com/metra/data/metra_stations.bm?callback=?",{LineID: lineValue[0]}, function(data){
		        cache[lineSelect.val()] = data; //cache it for next time
		        handleStationUpdate(data,lineSelect,startStationSelect, endStationSelect, markSelect);
				})
			}
			}else{
			     var options = '<option value="">' + needLineSelect + '</option>';
				 var options2 = '<option value="">' + needLineSelect+ '</option>';
				 
				 startStationSelect.html(options);
				 endStationSelect.html(options2);
			}
			
		}
		

/*
 * This is used internally by updateStations.  This is called after the data has
 * been obtained either from the cache or the service
 */
function handleStationUpdate(data, lineSelect, startStationSelect, endStationSelect, markSelect)
{    
     var options = '';
     var options2 = '';

     //Start creating new dropdowns for the stations
     options += '<option value="">' + stationDefault + '</option>';
     options2 += '<option value="">' + stationDefault + '</option>';
     
        $.each(data.metra_stations, function(objectName,stations) {  
	        $.each(stations, function(stationID,station)
	        {
	        var selectValue="";
	        var selectValue2="";
	
			//This is the current station being added to the dropdown
			var selectedStation="";
				var zoneID = '';
				var stopName = '';	
				var exactTarget = '';

				//Because of how the JSON is formatted it is necessary to loop through and determine which value goes to which attribute
				$.each(station, function(item,theValue){
					if(theValue.stop_name != undefined){
					stopName = theValue.stop_name.replace(/\s+/g,'-');
					}
					if(theValue.zone_id != undefined){
					zoneID = theValue.zone_id;
					}
					
					if (theValue.exact_target != undefined) {
					exactTarget = theValue.exact_target.replace(/\s+/g,'');
					}
				})
			
			selectedStation = zoneID + "_" + stopName + "_" + stationID + "_" + exactTarget;
	
	        //Start Station
			if(selectedStation != endStationSelect.val()){ //If value isn't the same as the end station value
	         if(markSelect && selectedStation == startStationSelect.val())
	              {
	                  selectValue="selected";
	              }
	          options += '<option  ' + selectValue + ' value="' + selectedStation + '">' + station[0].stop_name + '</option>';
			  }
	          
	         //End Station 
			 if( selectedStation != startStationSelect.val()){ //If value isn't the same as the start station value
	          if(markSelect && selectedStation == endStationSelect.val())
	              {
	                  selectValue2="selected";
	              }
	          options2 += '<option  ' + selectValue2 + ' value="' + selectedStation + '">' + station[0].stop_name + '</option>';
			  }
	        })
        })
      startStationSelect.html(options);
      endStationSelect.html(options2);
}

/*
 * Grabs the lines from a service and populates a dropdown
 * 
 * PARAMS
 * lineSelect: the dropdown to populate
 * markSelect: Should a default value be set (based on existing dropdown value)
 */
function updateLines(lineSelect, markSelect){

	 var loadOption = '<option value="' + lineSelect.val() + '">' + lineLoading + '</option>';
	 lineSelect.html(loadOption);
		 
		 $.getJSON(jsHost + "metrarail.com/metra/data/metra_lines.bm?callback=?",{}, function(data){
			 var options = '';

			
			 options += '<option value="">' + lineDefault + '</option>';
				$.each(data.metra_lines, function(objectName,lines) {  
					
					$.each(lines, function(lineID,line) {     
					  var selectValue="";
					  var selectedLine = "";
					  var lineDescription = "";
					  var exactTarget = "";
					  
						$.each(line, function(item,theValue){
							if(theValue["jcr:description"] != undefined){
							lineDescription = theValue["jcr:description"].replace(/\s+/g,'-');
							}													
							if (theValue.exact_target != undefined) {
							exactTarget = theValue.exact_target.replace(/\s+/g,'');
							}
						})
					  
					  selectedLine = lineID + "_" +  lineDescription + "_" + exactTarget;

					  if(markSelect && selectedLine == lineSelect.val())
					  {
						  selectValue="selected";
					  }
					  options += '<option ' + selectValue + ' value="' + selectedLine + '">' + line[0]["jcr:description"] + '</option>';
					})
				})
			  lineSelect.html(options);
			})
		
 		}
