(function($) {

    // Trip Controls

    // - Max travel per day -> JS, PHP (also grid controls)
    // - Number of trip games/days -> PHP
    // - Starting location? - > PHP
    // - Stadium revisit? -> PHP
    // - select different algorithms?

    // Grid Controls?

    // - Max games to show (on dist?)
    


    $.fn.tripgenerator = function() {

       return this.each(function() {
			   
			   var $this = $(this);
			   var allHTML = "";
			   allHTML += "<div id=\"tripgenerator-title\">Build Your Baseball Trip</div>";
/*
			   allHTML += "<table id=\"tripgenerator-div\">";
			   allHTML += "<tr>";
			   allHTML +=   "<td class=\"tripgenerator-leftalign\"><b>Starting Location</b></td>";
			   allHTML +=   "<td class=\"tripgenerator-input-cell\"><input id=\"tripgenerator-startlocinput\" size=\"20\" type=\"text\" value=\"\"/></td>";
			   allHTML += "</tr>";
			   allHTML += "<tr>";
			   allHTML +=   "<td class=\"tripgenerator-leftalign\"><b>Starting Date</b></td>";
			   allHTML +=   "<td class=\"tripgenerator-input-cell\"><input id=\"tripgenerator-startdateinput\" size=\"20\" type=\"text\" value=\"Start date\"/></td>";
			   allHTML += "</tr>";
			   allHTML += "<tr>";
			   allHTML +=   "<td><b>Trip Length</b></td><td id=\"tripgenerator-trip-length-cell\"class=\"tripgenerator-input-cell\"><input type=\"text\" id=\"tripgenerator-length\" value=\"0\" size=\"2\"/>";
			   allHTML +=          "<select id=\"tripgenerator-length-type\">";
			   allHTML +=          "<option value=\"days\" id=\"tripgenerator-days\">Days</option><option value=\"games\" id=\"tripgenerator-games\">Games</option>";
			   allHTML +=          "</select>";
			   allHTML +=   "</td>";
			   allHTML += "</tr>";
			   allHTML += "<tr>";
			   allHTML +=   "<td colspan=2><div id=\"tripgenerator-button\"></div></td>";
			   allHTML += "</tr>";
			   allHTML += "<tr>";
			   allHTML +=   "<td  id=\"tripgenerator-footer\" colspan=2><span id=\"tripgenerator-more-options\">More Options</span></td>";
			   allHTML += "</tr>";
			   allHTML += "</table>";
*/
			   allHTML += "<table id=\"tripgenerator-div\">";
			   allHTML += "<tr>";
			   allHTML +=   "<td class=\"tripgenerator-leftalign\"><b>Starting Location</b></td>";
			   allHTML +=   "<td class=\"tripgenerator-input-cell\"><input id=\"tripgenerator-startlocinput\" class=\"btp-form\" size=\"20\" type=\"text\" value=\"\"/></td>";
			   allHTML += "<td class=\"tripgenerator-gutter\"></td>";
			   allHTML +=   "<td><b>Trip Length</b></td><td id=\"tripgenerator-trip-length-cell\"class=\"tripgenerator-input-cell\"><input type=\"text\" id=\"tripgenerator-length\" value=\"0\" size=\"2\"/>";
			   allHTML +=          "<select id=\"tripgenerator-length-type\">";
			   allHTML +=          "<option value=\"days\" id=\"tripgenerator-days\">Days</option><option value=\"games\" id=\"tripgenerator-games\">Games</option>";
			   allHTML +=          "</select>";
			   allHTML +=   "</td>";
			   allHTML += "</tr>";
			   allHTML += "<tr>";
			   allHTML +=   "<td class=\"tripgenerator-leftalign\"><b>Starting Date</b></td>";
			   allHTML +=   "<td class=\"tripgenerator-input-cell\"><input id=\"tripgenerator-startdateinput\" size=\"20\" type=\"text\" value=\"Start date\"/></td>";
			   allHTML += "<td class=\"tripgenerator-gutter\"></td>";
			   allHTML +=   "<td rowspan=2 colspan=2><div id=\"tripgenerator-button\"></div></td>";
			   allHTML += "</tr>";
			   allHTML += "<tr>";
			   allHTML +=   "<td  id=\"tripgenerator-footer\" colspan=2><span id=\"tripgenerator-more-options\">More Options</span></td>";
			   allHTML += "</tr>";
			   allHTML += "</table>";

			   var optHTML = "";
			   optHTML += "<div id=\"tripgenerator-options\" class=\"hidden popup\">";
			   optHTML += "<div id=\"tripgenerator-options-header\">More Baseball Trip Options</div>";

			   // options to add

			   optHTML += "<div id=\"tripgenerator-options-dist\">";
			   optHTML += "<table><tr><td><div class=\"text-div\">Maximum distance per day: </div></td>";
			   optHTML += "<td class=\"input-div\"><input type=\"text\" id=\"tripgenerator-max-dist\" class=\"btp-form\" value=\"400\" size=\"4\"/></td></tr></table>";
			   optHTML += "</div>";

			   // max visits to park (total, consecutive)
			   optHTML += "<div id=\"tripgenerator-options-visits\">";
			   optHTML += "<table><tr><td><div class=\"text-div\">Maximum stadium visits: </div></td>";
			   optHTML += "<td class=\"input-div\"><input type=\"text\" id=\"tripgenerator-max-visits\" class=\"btp-form\" value=\"1\" size=\"2\"/></td></tr></table>";
			   optHTML += "</div>";

			   optHTML += "<div id=\"tripgenerator-options-consecutive-visits\">";
			   optHTML += "<table><tr><td><div class=\"text-div\">Max. consecutive stadium visits: </div></td>";
			   optHTML += "<td class=\"input-div\"><input type=\"text\" id=\"tripgenerator-max-consec-visits\" class=\"btp-form\" value=\"1\" size=\"2\"/></td></tr></table>";
			   optHTML += "</div>";

			   optHTML += "<div id=\"tripgenerator-options-max-idle-days\">";
			   optHTML += "<table><tr><td><div class=\"text-div\">Maximum idle days: </div></td>";
			   optHTML += "<td class=\"input-div\"><input type=\"text\" id=\"tripgenerator-max-idle-days\" class=\"btp-form\" value=\"1\" size=\"2\"/></td></tr></table>";
			   optHTML += "</div>";

			   optHTML += "<div id=\"tripgenerator-options-allow-doubleheader\">";
			   optHTML += "<table><tr><td><div class=\"text-div\">Allow Doubleheaders: (beta)</div></td>";
			   optHTML += "<td class=\"input-div\"><input type=\"checkbox\" id=\"tripgenerator-allow-doubleheader\"></td></tr></table>";
			   optHTML += "</div>";

			   optHTML += "<div id=\"tripgenerator-options-close\" class=\"popup-button\">Close</div>";

			   optHTML += "</div>";

			   // append to lower level parent?
			   $("#main").append(optHTML);
			   
			   //$("#tripgenerator-options").draggable();			   			   
			   //$this.append(allHTML);

			   $("#tripgenerator-more-options").click(function() {
								     $("#tripgenerator-options").toggleClass("hidden");
								  });
			   $("#tripgenerator-options-close").click(function() {
					      $("#tripgenerator-options").toggleClass("hidden");
					   });

			   $("#tripgenerator-allow-doubleheader").click(function() {
										   if($(this).attr("checked")) {
										      $.setMultipleSelect();
										   } else {
										      $.unsetMultipleSelect();
										   }
										});

			   $("#tripgenerator-button").mouseover(function() { $(this).addClass("tripgenerator-button-hover"); });
			   $("#tripgenerator-button").mouseout(function() { $(this).removeClass("tripgenerator-button-hover"); });

			   $("#tripgenerator-button").mousedown(function() { $(this).addClass("tripgenerator-button-click"); });
			   $("#tripgenerator-button").mouseup(function() { $(this).removeClass("tripgenerator-button-click"); });

			   $("#tripgenerator-button").click(function() { 
							       // start with first selected game, or starting location
							       if(!STARTINFO.game.set) {
								  if(!STARTINFO.loc.loaded) {
								     // Prompt for Starting Location
								     $.popupWindow("<b>Where is your trip starting?</b><br/>Set your starting location or <br/>pick the game on the schedule where<br/>you'll  start your trip.");
								  } else {
								     var start_team;
								     start_team = $.getClosestGame(STARTINFO.date.mmdd);
								     if(start_team !== "none") {
									$.setStartGame(STARTINFO.date.mmdd, start_team);
									$.generateTrip(); 
								     } else {
									// FIXME: error here
									alert("no start team found");
								     }
								  }
							       } else {
								  // First game is already set, generate trip
								  $.generateTrip(); 
							       }
							    });
			});

    };

    $.generateTrip = function() {
       var exclude_list = "";
       var days = $("#tripgenerator-length").attr("value");
       var games = $("#tripgenerator-length").attr("value");
       var length_type = $("#tripgenerator-length-type").attr("value");
       var start_loc = STARTINFO.game.home;
       var start_date = STARTINFO.game.date;
       var miles = $("#tripgenerator-max-dist").attr("value");
       var max_visits = $("#tripgenerator-max-visits").attr("value");
       var max_consec_visits = $("#tripgenerator-max-consec-visits").attr("value");
       var max_idle_days = $("#tripgenerator-max-idle-days").attr("value");

       if(length_type != "days" && length_type != "games") {
	  // FIXME: ERROR here
	  length_type = "games";
       }

       // Indicates to trip builder to measure in games or days
       if(length_type == "days") { games = 0; }
       if(length_type == "games") { days = 0; }

       // Check for bad values and replace with default
       if(length_type == "days"  &&  (days < 1 || isNaN(days)))   { days = 1; }
       if(length_type == "games" && (games < 1 || isNaN(games))) { games = 1; }
       if(miles < 1 || isNaN(miles)) { miles = 400; }
       if(max_visits < 1 || isNaN(max_visits)) { max_visits = 1; }
       if(max_consec_visits < 1 || isNaN(max_consec_visits)) { max_consec_visits = 1; }
       if(max_idle_days < 1 || isNaN(max_idle_days)) { max_idle_days = 1; }
       
       $(".teamfilter-team-include").each(function() {
					     if(!$(this).attr('checked')) {
						var team = /[A-Z]+/.exec($(this).attr("id"));
						exclude_list += team + ",";
					     }
					  });

       var trip = new Array();
       // if trip params verified:
       $.getJSON("getBTBTrip.php", { date: start_date, 
				     team: start_loc, 
				     num_days: days, 
				     num_games: games,
				     max_daily_travel: miles,
				     max_visits : max_visits,
				     max_consec_visits : max_consec_visits,
				     max_idle_days : max_idle_days,
				     exclude_list : exclude_list
				},
		 function(json) {
		    for(var i = 0; i < json.num_games; i++) {
		       var gdate = json.games[i].date;
		       var gteam = json.games[i].team;
		       var gamecellid = $.getGameCellId(gdate, gteam);
		       if(!gamecellid) {
			  $.loadDayInfo(gdate);
			  gamecellid = $.getGameCellId(gdate, gteam);
		       }
		       trip.push(gamecellid);
		    }
		    $.loadTrip(trip);
		    //$("#tripviewer-map-link").attr("href", "http://maps.google.com/maps?saddr=" + json.maplink);
		 });
    };

    // Utils class?
    function dateToString(a_date) {
       var date  = a_date % 100; 
       var month = (a_date - date) / 100;
       var date_string = month + "/" + date;
       return date_string;
    }

 })(jQuery);




