<?php
  require('inc/sessionStart.php');
?>
<?php
  if(isset($_GET['a'])){
    if($_GET['a'] == "add"){
	  $action = "add";
    }else if($_GET['a'] == "new"){
	  $action = "newItem";
	  require_once($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/class.features.inc.php");
	  $storeObj = new stores();
	  $addItem = $storeObj->addDeliItem();
	}else if($_GET['a'] == "manage"){
	  $action = "manageItems";
	  require_once($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/class.features.inc.php");
	  $storeObj = new stores();
	  $theItems = $storeObj->getDeliItems();
	}else{
	  $action = "base";
	}
  }else{
	$action = "base";
  }
?>
<?php
  require('inc/lunchSpecialsConfig.php');
?>

<?php
  $pageTitle = "Administration: " . $lunchConfig['branded'] . " Management";
  $pageDescription = "";
  $pageKeywords = "";
?>

<?php
  include_once($_SERVER['DOCUMENT_ROOT'] . "/common/header.php");
?>
<script async src="//afsshareportal.com/js/moment.min.js"></script>
<script type="text/javascript" src="/Kickstrap/js/nicEdit.js"></script>
<link rel="stylesheet" href="//afsshareportal.com/colorbox/colorbox.css" />
<script src="//afsshareportal.com/colorbox/jquery.colorbox.js"></script>

<?php
  include_once($_SERVER['DOCUMENT_ROOT'] . "/common/mainNav.php");
?>

    <section class="container">
      <div id="blankBuffer" class="carousel-buffer"></div>
      <section class="container" id="storePortal">
	    <div class="row">
		  <div class="span3 sideNav">
			<?php include('inc/sideNav.php'); ?>
			<br><br>
			<div id="addDeli">
			  <a id="addDeliItem" href="lunchSpecials.php?a=add" class="btn btn-large">Add a deli item</a>
			</div>
		  </div>
		  
		  <div class="span9 portalContent">
			<div class="contentContain">
			  <script>
				var config = <?php echo json_encode($lunchConfig); ?>;
				delete config['branded'];
			  </script>
			  <?php
				if($action == "base" || $action == "newItem"){
				  if($action == "newItem" && $addItem != false){
			  ?>
					<div id="addSuccess">
					  <div class="alert alert-success">
						<a class="close" data-dismiss="alert" href="#">x</a>You successfully added the item to the database.
					  </div>
					</div>
			  <?php
				  }else if($action == "newItem" && $addItem == false){
			  ?>
					<div id="addError">
					  <div class="alert alert-error">
						<a class="close" data-dismiss="alert" href="#">x</a>There was a problem adding your item to the database.
					  </div>
					</div>
			  <?php
				  }
			  ?>
				<h2><?php echo $lunchConfig['branded']; ?> Assignment <span class="pull-right"><a href="?a=manage" class="btn">Manage Items</a></span></h2>
				<div id="lunchContain">
				  <div class="clearfix">
					<div id="calendar">
					  <?php include('inc/calendar.php'); ?>
					  
					  <div style="clear:both;"></div>
					  <div id="changeSpecialContainer"></div>
					</div>
					<div id="viewLunch">
					  <div id="changeLunchContain">
						
					  </div>
					</div>
				  </div>
				  
				  
				</div>
				
				<script>
					
					$("body").on("click", ".day", function(){
					  $(".pickedDay").removeClass("pickedDay");
					  $(this).addClass("pickedDay");
					  var theDate = $(this).attr("rel");
					  
					  
					  $.ajax({
						type: "POST",
						url: "interactions.php",
						data: "action=getLunchDay&date=" + theDate,
						dataType: "json",
						success: function(theResponse){
						  var theHTML = "";
						  var localConfig = jQuery.extend(true, {}, config);
						  
						  if(theResponse != false){
							//console.log(theResponse);
							
							theHTML += "<h3>" + formatDateNice(theDate) + "</h3>";
							
							$.each(theResponse, function(){
							  localConfig[this['deli_type']]["has-special"] = true;
							  localConfig[this['deli_type']]['item'] = this;
							  
							});
							
							
							var currentType = "";
							$.each(localConfig, function(key){
								if(this['common-name'] != currentType){
									if(currentType != ""){
										theHTML += "</div>";
									}
									theHTML += "<div id='container_" + key + "'>";
								}
								
								if(this['has-special'] !== false){
									var deliID = this['item']['deli_id'];
									theHTML += "<div id='option_" + key + "'>";
									theHTML += "<h3>" + this['common-uc'] + " Special</h3>";
									theHTML += "<img class='floatLeftImg' src='/" + deliItems[deliID]['photo'] + "' width='50%' alt='" + this['common-uc'] + "'>";
									theHTML += "<h3>" + deliItems[deliID]['name'] + "</h3>";
									theHTML += "<h4>" + this['item']['item_price'] + "</h4>";
									theHTML += "<p class='clearfix'>" + this['item']['item_desc'] + "</p>";
									theHTML += "<hr>";
									theHTML += "<p><a class='btn btn-primary removeLunch' href='#'>Remove " + this['common-name'] + " special</a></p>";
									theHTML += "</div>";
									theHTML += "<hr>";
								}else{
									theHTML += "<div class='alert alert-error' id='option_" + key + "'>";
									theHTML += "There is no " + this['common-name'] + " special for this day.";
									theHTML += "</div>";
								}
								
								currentType = this['common-name'];
							});
							//close the last container div from the each loop
							theHTML += "</div>";
						  }else{
							var currentType = "";
							
							$.each(localConfig, function(key){
								if(this['common-name'] != currentType){
									if(currentType != ""){
										theHTML += "</div>";
									}
									theHTML += "<div id='container_" + key + "'>";
								}
								
								theHTML += "<div class='alert alert-error' id='option_" + key + "'>";
								theHTML += "There is no " + this['common-name'] + " special for this day.";
								theHTML += "</div>";
								
								currentType = this['common-name'];
							});
							//close the last container div from the each loop
							theHTML += "</div>";
						  }
						  
						  //theHTML += deliDropdown;
						  $("#changeSpecialContainer").html(deliDropdown);
							
						  $("#viewLunch").html(theHTML);
						  
						  $("#viewLunch").attr("rel", theDate);
						  
						  delete localConfig;
						}
					  });
					});
					
					$("body").on("click", ".removeLunch", function(e){
						e.preventDefault();
						var changeWhich = $(this).closest("div").attr("id").replace("option_", "");
						var theDate = $("#viewLunch").attr("rel");
						var theType = changeWhich;
				  
						$.ajax({
						  type: "POST",
						  url: "interactions.php",
						  data: "action=removeLunchDay&date=" + theDate + "&type=" + theType,
						  dataType: "json",
						  success: function(theResponse){
							theHTML = "";
							
							if(theResponse == true){
							  theHTML += "<div id='option_" + changeWhich + "'>";
							  theHTML += "<div class='alert alert-error'>";
							  theHTML += "There is no " + config[changeWhich]['common-uc'] + " special for this day.";
							  theHTML += "</div>";
							  theHTML += "</div>";
							  
							  $("#option_" + changeWhich).replaceWith(theHTML);
							}else{
							  theHTML += "<div class='alert alert-error'>";
							  theHTML += "<a class='close' data-dismiss='alert' href='#'>x</a>There was an error when trying to remove this item. Please try again.";
							  theHTML += "</div>";
							  $("#option_" + changeWhich).append(theHTML);
							}
							
						  }
						});
					  });
					  
					  $("body").on("click", "#changeLunchBtn", function(e){
						e.preventDefault();
						var changeWhich = $("#changeType").attr("value");
						var deliID = $("#changeLunch").attr("value").replace("deli_", "");
						var theDate = $("#viewLunch").attr("rel");
						var dollars = $("input[name='priceDollars']").val();
						dollars = dollars.substr(0, dollars.length > 3 ? 3 : dollars.length);
						var cents = $("input[name='priceCents']").val();
						cents = cents.substr(0, cents.length > 3 ? 3 : cents.length);
						var thePrice = "$" + dollars + "." + cents;
						var theDesc = $("#itemDesc").val();
						//console.log(theDesc);
						var theType = changeWhich;
						
						$.ajax({
						  type: "POST",
						  url: "interactions.php",
						  data: "action=updateLunchDay&date=" + theDate + "&deli_id=" + deliID + "&price=" + thePrice + "&desc=" + theDesc + "&type=" + theType,
						  dataType: "json",
						  success: function(theResponse){
							
							var theHTML = "";
							theHTML += "<div id='option_" + changeWhich + "'>";
							theHTML += "<h3>" + config[changeWhich]['common-uc'] + " Special</h3>";
							theHTML += "<img class='floatLeftImg' src='/" + deliItems[deliID]['photo'] + "' width='50%' alt='" + config[changeWhich]['common-uc'] + "'>"
							theHTML += "<h3>" + deliItems[deliID]['name'] + "</h3>";
							theHTML += "<h4>" + thePrice + "</h4>";
							theHTML += "<p class='clearfix'>" + theDesc + "</p>";
							theHTML += "<p><a class='btn btn-primary removeLunch' href='#'>Remove " + config[changeWhich]['common-name'] + " special</a></p>";
							theHTML += "</div>";
							theHTML += "<hr>";
							
							//theHTML += deliDropdown;
							
							$("#container_" + changeWhich + " #option_" + changeWhich).replaceWith(theHTML);
							
						  }
						});
					  });
					  
					  $("body").on("click", "#nextMonth, #prevMonth", function(){
						$("#viewLunch").html("Select a date to see the special");
						
						var type = $(this).attr("id");
						var months = [ "January", "February", "March", "April", "May", "June", 
								 "July", "August", "September", "October", "November", "December" ];
						//var theDate = "20130701";
						var theDate = $(".calendar").attr("id");
						
						if(type == "nextMonth"){
						  var dateComponents = moment(theDate).add('M', 1);
						}else{
						  var dateComponents = moment(theDate).subtract('M', 1);
						}
						
						
						var monthNum = ("0" + (dateComponents.month() + 1)).slice(-2);
						var month = dateComponents.format("MMMM");
						var year = dateComponents.year();
						var dayDate = ("0" + dateComponents.date()).slice(-2);
						var refDate = year + "-" + monthNum + "-" + dayDate;
						var newCalendar = buildCalendar(month, year, refDate);
						
						$("#calendar").html(newCalendar);
						$("#calendar").append("<div style='clear:both'></div>" + deliDropdown);
					});
				</script>
			  <?php
				}// end if($action == "base")
				else if($action == "manageItems"){
			  ?>
				<h1>Manage Items</h1>
			  <?php
				  foreach($theItems as $anItem){
			  ?>
				  <table class="addFeature" id="deliItem_<?php echo $anItem['deli_id']; ?>">
					<tr>
					  <td class="aLabel">
						Item Name:
						<span class="featureControls">
							  <a href="#" class="ajaxEdit" id="name_<?php echo $anItem['deli_id']; ?>"><i class="icon-edit" title="Change the Deli Item's Name"></i></a>&nbsp;&nbsp;&nbsp;
						</span>
					  </td>
					  <td><?php echo $anItem['deli_name']; ?></td>
					</tr>
					<tr class="photo">
					  <td class="aLabel">
						Photo:
						<span class="featureControls">
							  <a href="#" class="ajaxEdit" id="photo_<?php echo $anItem['deli_id']; ?>"><i class="icon-edit" title="Change the Photo"></i></a>&nbsp;&nbsp;&nbsp;
						</span>
						<br><br>
						<a href="#" class="btn deleteDeliItem" id="deli_<?php echo $anItem['deli_id']; ?>">Delete Item</a>
					  </td>
					  <td><img src="/<?php echo $anItem['deli_photo']; ?>" width="200" class="<?php echo $anItem['deli_name']; ?>"></td>
					</tr>
				  </table><br>
				  
			  <?php
				  }//foreach($theItems as $anItem)
			  ?>
				  <script>
					$(".ajaxEdit").bind("click", function(e){
					  e.preventDefault();
					  $("#theAjaxUpdateDiv").remove();
					  var $this = $(this);
					  var theID = $this.attr("id");
					  //var theValue = "This will be the value";
					  
					  var appendHere = $this.parents(".aLabel").siblings();
					  
					  var underIndex = theID.indexOf("_");
					  var theColumn = theID.substring(0, underIndex);
					  var featureID = theID.substring(underIndex+1, theID.length);
					  
					  //Create an input based on the value they want to change
					  switch(theColumn){
						case "name":
						  var updateText = "<p>Enter the new Deli Item Name: <span class='floatRight'><a href='#' id='killAjaxBox'><i class='icon-remove'></i></a></span></p>";
						  var newInput = "<input type='text' name='newUpdate' id='newUpdate'>";
						  break;
						case "photo":
						  var updateText = "<textarea id='photoUpdate' name='photoUpdate' style='width:100%; height:150px;'></textarea>";
						  var newInput = "";
						  var photoLoc = "photoUpdate";
						  break;
						default:
						  break;
					  }
					  
					  var theHTML = "";
					  theHTML += "<div id='theAjaxUpdateDiv'>";
					  theHTML += updateText;
					  
					  theHTML += newInput;
					  
					  if(theColumn == "photo"){
						theHTML += "<br><p><a href='#' id='" + photoLoc + "' class='btn photoUpdateBtn'>Update</a></p>";
						theHTML += "</form>";  
					  }else{
						theHTML += "<p><a id='newUpdateSubmit' href='#' class='btn'>Update</a></p>";
					  }
					  theHTML += "</div>";
					  
					  appendHere.append(theHTML);
					  
					  if(theColumn == "photo"){
						  //console.log(photoLoc);
						  createNicEdit(photoLoc);
					  }
					  
					  //$("#theAjaxUpdateDiv .datepicker").datepicker();
					});
					
					
					
					$("body").on("click", ".photoUpdateBtn", function(e){
					  e.preventDefault();
					  var $this = $(this);
					  var theID = $this.attr("id");
					  var theImg = $("#" + theID + "NewContent").find("img").attr("src").replace("/", "");
					  if(typeof theImg != "undefined"){
							//theImg = theImg.substr(0,1) == "/" ? theImg.substr(1, theImg.length) : theImg;
							//console.log(theImg);
							
							var $theParent = $(this).parents("tr");
							var theID = $(".aLabel span a", $theParent).attr("id");
							
							var updateLocation = $(this).parents("tr").children("td")[1];
							//console.log($updateLocation);
							var underIndex = theID.indexOf("_");
							var theColumn = theID.substring(0, underIndex);
							$.ajax({
								  type: "POST",
								  url: "interactions.php",
								  data: "action=updateDeliPic&column_ID=" + theID + "&value=" + theImg,
								  dataType: "json",
								  success: function(theResponse){
										var updateVal = theResponse['value'];
										
										$("#theAjaxUpdateDiv").remove();
										
										//$(updateLocation).text(updateVal).addClass("text-success").removeClass('text-error');
										
										$("img", updateLocation).attr("src", "/" + updateVal);
										
										setTimeout(function(){
											  $(updateLocation).removeClass("text-success");
										}, 2000);
										
								  },
								  error: function(){
									  
								  }
							});  
					  }else{
							$("#theAjaxUpdateDiv").html("Please choose a file to replace the current file.").addClass("text-error");
							setTimeout(function(){
								  $("#theAjaxUpdateDiv").remove();
							}, 2000);
					  }
					});
					
					$("body").on("click", "#newUpdateSubmit", function(e){
					  e.preventDefault();
					  var $theParent = $(this).parents("tr");
					  var theID = $(".aLabel span a", $theParent).attr("id");
					  
					  var updateLocation = $(this).parents("tr").children("td")[1];
					  //console.log($updateLocation);
					  var underIndex = theID.indexOf("_");
					  var theColumn = theID.substring(0, underIndex);
					  
					  var theValue = $("#newUpdate").val();  
					  
					  
					  //console.log(theID + "\n" + theValue + "\n" + theColumn);
					  //THIS IS THE CODE FOR UPDATING ONCE THE VALUE IS DETERMINED
					  $.ajax({
						type: "POST",
						url: "interactions.php",
						data: "action=updateDeliItem&column_ID=" + theID + "&value=" + theValue,
						dataType: "json",
						success: function(theResponse){
						  var updateVal = theResponse['value'];
						  
						  $("#theAjaxUpdateDiv").remove();
						  $(updateLocation).text(updateVal).addClass("text-success").removeClass('text-error');
						  
						  setTimeout(function(){
						  $(updateLocation).removeClass("text-success");
						  }, 2000);
						  
						}
					  });
					});
					
					$("body").on("click", "#killAjaxBox", function(e){
					  e.preventDefault();
					  $("#theAjaxUpdateDiv").remove();
					});
					
					function createNicEdit(theLoc){
					  //console.log(theLoc);
					  new nicEditor({
						  fullPanel : false,
						  buttonList : ['image', 'upload']
					  }).panelInstance(theLoc,{hasPanel : true});	
					}
					
					$(".deleteDeliItem").bind("click", function(e){
						  e.preventDefault();
						  $(".deleteAlert").remove();
						  $(this).parents("tr").after("<tr><td colspan='2'><div class='deleteAlert alert alert-error'>Are you sure you want to delete this deli item?<br><br><a href='#' class='deleteDeliItemConfirm btn'>Yes</a> &nbsp;&nbsp;<a href='#' class='deleteDeliItemNo btn'>No</a></div></td></tr>");
					});
					
					$("body").on("click", ".deleteDeliItemNo", function(e){
						  e.preventDefault();
						  $(".deleteAlert").parents("tr").remove();
					});
					
					$("body").on("click", ".deleteDeliItemConfirm", function(e){
					  e.preventDefault();
					  var deliID = $(this).parents(".addFeature").attr("id").replace("deliItem_", "");
					  
					  $.ajax({
						type: "POST",
						url: "interactions.php",
						data: "action=deleteDeliItem&deli_id=" + deliID,
						dataType: "json",
						success: function(theResponse){
						  //console.log($.type(theResponse));
						  //console.log(theResponse);
						  if(theResponse == true){
								$("#deliItem_" + deliID).remove();
						  }
						}
					  });
					  
					});
				  </script>
			  <?php
				}//else if($action == "manageItems")
				else if($action == "add"){
			  ?>
				<h2>Add a Deli Item</h2>
				<div id="lunchContain">
				  <form action="lunchSpecials.php?a=new" method="post" name="newDeliItem" id="newDeliItem">
					<!--<input type="hidden" name="action" value="newDeliItem">-->
					<div>
					  <label for="itemName">Item Name:</label>
					  <input type="text" name="itemName" id="itemName">
					</div>
					<div>
					  <label for="lunchPicHolder" class="formTitles">Photo: (ideally 350 px. wide)</label>
					  <textarea id='lunchPicHolder' name='lunchPicHolder' style='width:257px; height:150px;'></textarea>
					  <input type="hidden" name="photo" id="photo" value="">
					</div>
					<br><br>
					<input type="submit" id="submit" name="submit" value="Submit" class="btn" />
				  </form>
				</div>
				<script>
				  new nicEditor({
						fullPanel : false,
						buttonList : ['image', 'upload']
				  }).panelInstance("lunchPicHolder",{hasPanel : true});
				  
				  $("body").on("submit", "#newDeliItem", function(e){
					//e.preventDefault();
					
					$("#photo").attr("value", $("#lunchPicHolderNewContent").find("img").attr("src").substring(1));
					
					return true;
				  });
				</script>
			  <?php
				}//end else if($action == "add")
			  ?>
			</div>
		  </div>
	    </div>
	    
      </section>
      
    </section>
      
    
  
  <script src="js/includeJS.js"></script>
  
  <script>
	var deliItems = new Array();
	var deliDropdown = "";
	
	getLunchOptions();
	
	
   $(document).ready(function() {
      // JavaScript placed here will run only once Kickstrap has loaded successfully.
      $("#today_date").click();
   });
  </script>
  
<?php require($_SERVER['DOCUMENT_ROOT'] . '/common/footer.php'); ?>
