<?php include_once($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/sessionStartGeneral.php") ?>
<?php
  require_once($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/class.users.inc.php");
  require_once($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/class.features.inc.php");
    
?>
<?php
  $pageTitle = "Shopping List";
  $pageDescription = "Make your visit to the store a better experience by using our shopping list application that will map your route throught the store.";
  $pageKeywords = "Shopping list, map, route, aisles";
?>
<?php
  //var_dump($_SESSION);
  include_once($_SERVER['DOCUMENT_ROOT'] . "/common/header.php"); 
?>

<style>
	  #mainContent .row .span12{
			width: 95%;
	  }
	  
	  
	  
	  /*TAKE THESE TO BOOTSTRAP.LESS*/
	  
	  
	  
</style>
<script src="/Kickstrap/js/jquery-ui-1.9.0.custom.min.js"></script>
<link href="/Kickstrap/css/smoothness/jquery-ui-1.9.0.custom.css" rel="stylesheet">

<?php require($_SERVER['DOCUMENT_ROOT'] . '/common/mainNav.php'); ?>
<?php
  if($loggedIn == true){
	if($_GET){
	  $theScreen = isset($_GET['a']) ? $_GET['a'] : false;
	  if($theScreen !== false){
		switch($theScreen){
		  case "account":
			$action = "account";
			break;
		  case "share":
			$action = "share";
			break;
		  case "view":
			$action = "view";
			$wantedList = isset($_GET['list']) ? $_GET['list'] : false;
			if($wantedList !== false){
				$users = new users($db);
				$theList = $users->showOneList("view", $wantedList);
				if(!isset($theList['Error']) || $theList['Error'] == "The list you are trying to access does not have any items"){
					$theListName =  $theList['ListName'];
				}else{
					$action = "login";
				}
				
			}else{
				$action = "login";
			}
			break;
		  case "list":
			$action = "list";
			$wantedList = isset($_GET['list']) ? $_GET['list'] : false;
			if($wantedList !== false){
				$users = new users($db);
				$theList = $users->showOneList("list", $wantedList);
				
				if(!isset($theList['Error']) || $theList['Error'] == "The list you are trying to access does not have any items"){
					$theListName =  $theList['ListName'];
				}else{
					$action = "account";
				}
				
			}else{
				$action = "account";
			}
			break;
		  default:
			$action = "account";
			break;
		}
	  }
	}else if($_POST){
	  $users = new users($db);
	  $theResult = $users->accountLogin();
	  
	  if($theResult == true){
		  $action = "account";
	  }else{ //If it couldn't register
		  $action = "login";
		  $theError = true;
	  }
	}else{
		if(isset($_SESSION['LoggedIn']) && isset($_SESSION['Username']) && $_SESSION['LoggedIn'] == 1){
			$action = "account";
		}else{
			$action = "login";
			$theError = false;
		}
	}
  }else{
	if($_SERVER['REQUEST_METHOD'] === 'GET'){
	  $theScreen = isset($_GET['a']) ? $_GET['a'] : false;
	  if($theScreen !== false){
		if($theScreen == "view"){
		  $wantedList = isset($_GET['list']) ? $_GET['list'] : false;
			if($wantedList !== false){
				$users = new users($db);
				$theList = $users->showOneList("view", $wantedList);
				
				$action = "view";
				if(!isset($theList['Error']) || $theList['Error'] == "The list you are trying to access does not have any items"){
					$theListName =  $theList['ListName'];
				}else{
					$action = "login";
				}
				
			}else{
				$action = "login";
			}
		}else{
			if($theScreen == "signup"){
			  $action = "signup";
			}else{
			  $action = "login";
			}
		}
	  }else{
		if($theScreen == "signup"){
		  $action = "signup";
		}else{
		  $action = "login";
		}
	  }
	}else if($_SERVER['REQUEST_METHOD'] === 'POST'){
	  $users = new users($db);
	  
	  if($_POST['whichForm'] == "login"){
		$theResult = $users->accountLogin();
	  
		if($theResult == true){
			$action = "account";
		}else{ //If it couldn't register
			$action = "login";
			$theError = true;
		}
	  }else if($_POST['whichForm'] == "signup"){
		if(!empty($_POST['useremail']) && !empty($_POST['password'])){
		  $theResult = $users->createAccount();
		  
		  if($theResult == true){
			  $action = "account";
		  }else{ //If it couldn't register
			  $action = "account";
			  $theResult = $users->accountLogin();
		  }
		}else{
		  $action = "signup";
		  $theError = true;
		  $errorMessage = "Please enter an email and a password";
		}
	  }
	  
	}else{
	  $action = "login";
	  $theError = false;
	}
  }
  
  if($_GET['a'] == "print"){
	$action = "print";
	$wantedList = isset($_GET['list']) ? $_GET['list'] : false;
	if($wantedList !== false){
		$users = new users($db);
		$theList = $users->showOneList("view", $wantedList);
		if(!isset($theList['Error']) || $theList['Error'] == "The list you are trying to access does not have any items"){
			$theListName = $theList['ListName'];
		}else{
			$errorMessage = "There was a problem accessing your list.";
		}
		
	}else{
		$errorMessage = "This list no longer exists.";
	}
  }
  
  if($action != "login" && $action != "view" && $action != "signup"){
?>
  <script>
	var userID = <?php echo $_SESSION['UserID'] != NULL ? $_SESSION['UserID'] : false; ?>;
  </script>
<?php
  }
?>

<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/common/constants.php'); ?>


    
    <section class="container">
      <div id="blankBuffer"></div>
      <section class="container" id="mainContent">
	    <div class="row">
		  <div class="span12">
			  <div id="shoppingOffset">
				<?php
				  //echo $loggedIn . ": theScreen = " . $theScreen . " & action= " . $action;
				  if($action == "list" || $action == "print"){
				?>
				  <p class="btn-group">
					<a class="btn" href="/shoppingList">Back to all lists</a>
				  </p>
				<?php
				  }//end nav to get back to account home
				  if($action == "login"){
				?>
					<div class="loginBox clearfix">
						<div class="span5 offset3 clearfix">
							<div class="well">
								<legend>Sign in</legend>
								<?php if($theError): ?>
									<div class="alert alert-error">
										<a class="close" data-dismiss="alert" href="#">x</a>Incorrect Username or Password!
									</div>
								<?php endif;//end if($theError) ?>
								<form method="POST" action="/shoppingList" name="loginform" id="loginform" class="clearfix" accept-charset="UTF-8">
									<input type="hidden" name="whichForm" id="whichForm" value="login"/>
									<input class="span4" placeholder="User Email" type="text" name="useremail" id="useremail"><br>
									<input class="span4" placeholder="Password" type="password" name="password" id="password" ><br>
									<button class="btn" type="submit">Login</button>
								</form>
							</div>
						</div>
						
						<div class="span5 offset3">
							<div class="well alert">
								<p>Your shopping list will be saved to a database so that you are able to access and share your list(s) across all of your devices. Only an item identifier and quantity will be saved to the database. We will never access or share this information with any 3rd party company.</p>
							</div>
						</div>
						
						<div class="span5 offset3">
							<div class="well info">
								<p>Don't have an account? <a href="/shoppingList/signup">Click here to sign up.</a></p>
							</div>
						</div>
					</div>
				<?php
				  }//if($action == "login")
				  else if($action == "signup"){
				?>
				  <div class="loginBox">
					<div class="span5 offset3">
						<div class="well">
							<legend>Sign up</legend>
							<?php if($theError): ?>
								<div class="alert alert-error">
									<a class="close" data-dismiss="alert" href="#">x</a><?php echo $errorMessage; ?>
								</div>
							<?php endif;//end if($theError) ?>
							<form method="POST" action="/shoppingList" name="signupForm" id="signupForm" class="clearfix" accept-charset="UTF-8">
								<input type="hidden" name="whichForm" id="whichForm" value="signup"/>
								<input type="hidden" name="passMatch" id="passMatch" value="false"/>
								<label for="useremail">Email Address</label>
								<input class="span4" placeholder="User Email" type="text" name="useremail" id="useremail">
								<label for="password">Password</label>
								<input class="span4" placeholder="Password" type="password" name="password" id="password" >
								<label for="passwordCheck">Confirm Password</label>
								<input class="span4" placeholder="Confirm Password" type="password" name="passwordCheck" id="passwordCheck" >
								<div id="passNote" class="alert alert-error hideObject">Your passwords do not match</div>
								<button class="btn" type="submit">Sign up</button>
								<br><br><div id="completFormAlert" class='alert alert-error hideObject'>Please fill out the form and make sure your passwords match.</div>
							</form>
						</div>
					</div>
				  </div>
				  <script>
					$(document).ready(function(){
						$("#passwordCheck").on("input", function(){
							checkPasswords();
						});
						
						$("#signupForm").submit(function(e){
							e.preventDefault();
							var passwordMatch = $("#passMatch").val();
							//console.log(passwordMatch);
							if(passwordMatch == "true") {
							  $(this).unbind("submit").submit();
							}else{
							  checkPasswords();
							  var passwordMatchRecheck = $("#passMatch").val();
							  if(passwordMatchRecheck == "true") {
								$(this).unbind("submit").submit();
							  }else{
								$("#completFormAlert").removeClass("hideObject")
							  }
							}
						});
						
						function checkPasswords(){
						  var firstPassword = $("#password").val();
						  var passCheck = $("#passwordCheck").val();
						  
						  if (firstPassword == passCheck) {
								  $("#passNote").addClass("hideObject");
								  $("#passMatch").val("true");
						  }else{
								  $("#passNote").removeClass("hideObject");
								  $("#passMatch").val("false");
						  }
						}
					});
				  </script>
				<?php
				  }//end else if($action == "signup")
				  else if($action == "account" || $action == "share"){
					if($action == "share"){
					  $share = new users();
					  
					  $theShare = $share->shareList($_POST['senderEmail'], $_POST['receiveEmail'], $_POST['message'], $_POST['listURL']);
				?>
				  <div id="shareSuccess">
					<div class="alert alert-success">
					  <a class="close" data-dismiss="alert" href="#">x</a>You shared the list successfully.
					</div>
				  </div>
				<?php
					}//if($action == "share")
				?>
				  <div id="mailContain" class="hideObject">
					<div id="mailForm">
					  <form method="post" action="/shoppingList/share" name="shareform" id="shareform">
						<div>
						  <h3 id="formListName"></h3>
						  <input type="hidden" name="listURL" id="listURL">
						  <label for="username">Your Email*</label><br />
						  <input type="text" name="senderEmail" id="senderEmail"/>
						  <br />
						  <label for="receiveEmail">Receiving Email*</label><br />
						  <input type="text" name="receiveEmail" id="receiveEmail" required/>
						  <br />
						  <label for="message">Your Message</label><br />
						  <textarea name="message" id="message" /></textarea>
						  <br />
						  <input type="submit" name="send" id="send" value="Send Email" class="button" />
						  <input type="submit" name="cancel" id="cancel" value="Cancel" class="button" />
						</div>
					  </form><br />
					</div>
				  </div>
				  <div id="accountContain">
					<p id="sharedMessage" class="hideObject">Congratulations! You have shared your list!</p>
					<p id="addFailed" class="hideObject">Your new list was not created. You may have up to 5 lists at one time. Delete an existing list and then add a new list if you want to start a new list.</p>
					<h3>Your Shopping Lists <i id="addList" class="muted icon-plus-sign"></i></h3>
					  <ul id="accountLists">
						<?php 
						  include_once($_SERVER['DOCUMENT_ROOT'] . "/admin/inc/class.users.inc.php");
						  $users = new users($db);
						  $userLists = $users->getLists($_SESSION['Username']);
								  
						  if($userLists !== false){
							foreach($userLists as $aList){ 
						?>
						<li class="listContainer">
						  <div class="listContents">
							<p class="listName"><a href="/shoppingList/list/<?php echo $aList['ListID']; ?>"> <?php echo $aList['ListName']; ?></a></p>
							<p id="editBtns" class="clearfix">
							  <span class="editContain" id="edit<?php echo $aList['ListID']; ?>" >
								<a href="/shoppingList/list/<?php echo $aList['ListID']; ?>">
								  <i class="icon-search" title="View <?php echo $aList['ListID']; ?>"></i>
								</a>
								<i class="icon-edit edit" title="Edit the list's name"></i>
								<i class="delete icon-trash" title="Delete the list"></i>
								<i class="icon-share share" id="<?php echo $aList['ListURL']; ?>" title="Email the list"></i>
								<a href="/shoppingList/print/<?php echo $aList['ListURL']; ?>">
								  <i class="icon-print hidden-phone" title="Print the list"></i>
								</a>
							  </span>
							</p>
							<p class="createdDate">Created <?php echo date("M j, Y", strtotime($aList['created'])); ?></p>
							<p class="deleteMessage hideObject" id="delete<?php echo $aList['ListID']; ?>">Are you sure you want to delete this list?<br><span class="deleteYes btn">Yes, delete the list</span> &nbsp;&nbsp;&nbsp;<span class="deleteNo btn">Don't delete</span></p>
							<p class="nameChange hideObject"><label for='newName'>Enter the new name for your list: </label><br><input type='text' name='newName' id="newName"><br><span class="save btn">Save</span> &nbsp;<span class="cancelName btn">Cancel</span></p>
							
							<p class="saveMsg hideObject"></p>
						  </div>
						</li>
						<?php
							}
							}else{
								echo "You don't have any lists";	
							}
						?>
					  </ul>
					  
					  <?php
						  $allStores = $users->getAllStoreLocations();
						  
						  if(count($allStores) > 1){
					  ?>
					  
						<h3>Your Store <i class="icon-refresh muted changeLoc"></i></h3>
						<?php 
							$storeName = $users->getStoreLocation($_SESSION['Username']);
						?>
								<h4 class="storeName offsetPadLeft"><?php echo !isset($storeName['Error']) ? $storeName['storeName'] : "No preferred location"; ?></h4>	
						
						<div id="allLocations" class="hideObject">
							<h4>Choose your preferred store location</h4>
							<select id="chooseLocations" name="chooseLocations">
								<option value="none">Select Location</option>
						<?php
							foreach($allStores as $oneStore){
						?>
								<option value="<?php echo $oneStore['store_id']; ?>"><?php echo $oneStore['store_name']; ?></option>
						<?php	
							}
						?>
							</select>
						
						
						</div>
						<p id="locationMsg" class="hideObject">You have updated your preferred location</p>
						
					  <?php
						}//if(count($allStores > 1))
					  ?>
				  </div>
				<?php
				  }//else if($action == "account")
				  else if($action == "list"){
					$users = new users();
					$theUser = $users->getUserInfo($_SESSION['UserID']);
					$storeObj = new stores();
					//echo "<pre>";
					//var_dump($theList);
					//echo "</pre>";
				?>
				  <div id="pickItems" class="clearfix">
					  <!--<h1 id="list_<?php echo $theList['ListID']; ?>"><?php echo $theList['ListName']; ?></h1>-->
					  
					  <div id="droppable">
						  <div id="dropContainer">
							  <h2><?php echo $theListName; ?></h2>
							  <p id="itemCount"><?php if(count($theList['items']) > 1){ echo "(" . count($theList['items']) . " items)";}; ?></p>
							  <p class="hideObject" id="theListNumber"><?php echo $theList['ListID']; ?></p>
							  <div>
								  <ul id="dropHere" class="connectList">
									  <li class="placeholder">Drag your items here</li>
								  </ul>
							  </div>
							  <p id="mapButtonContain">
								  <a href="#" id="mapButton" class="btn hideObject">Map Your Route</a>
								  <a href="#" id="saveBtn1" class="saveList btn hideObject">Save Your List</a>
							  </p>
							  <p id="saveMsgAJAX" class="hideObject"></p>
						  </div>
					  </div>
					  
					  <div id="draggable">
						  <h2>Pick items for your shopping list</h2>
						  <div id="searchContainer">
							  <label for="autocomplete">Find an item: </label>
							  <input id="autocomplete" size="15"><br><br>
						  </div>
						  <?php
							  $theItems = $storeObj->getDirectoryItemsStore($theUser['pref_store']);
							  //$theItems = $storeObj->getUsedDirectoryItems($theUser['pref_store']);
							  $allItems = array();
							  //echo "<pre>";
							  //var_dump($theItems);
							  //echo "</pre>";
							  
						  ?>
						  <ul id="fromHere" class="connectList">
						  <?php
							  foreach($theItems as $anItem){
								//echo "<pre>";
								//var_dump($anItem);
								//echo "</pre>";
								$theAisle = is_null($anItem['aisle']) ? "null" : $anItem['aisle'];
						  ?>
							  <li id="<?php echo str_replace( " ", "_", $anItem['item_name']); ?>" class="setDrag clickable clearfix <?php echo $theAisle; ?>"><div width="50%" id="item<?php echo $anItem['item_id']; ?>" class="sortName itemName"><?php echo $anItem['item_name']; ?></div><i class="icon-plus-sign toDropHere directionIcon"></i></li>
						  <?php
							  }
						  ?>
						  </ul>
					  </div>
				  </div>
				  <div id="chosenItems" class="hideObject">
					  <!--<h1>Map your route in <?php //echo $thisLocation['store_name']; ?></h1>-->
					  <h1>Your route for <?php echo $theListName; ?></h1>
					  <input type="hidden" id="listNumber" value="No List">
					  <div class="functionBtns">
						  <a href="#" id="reverseList" class="btn">Reverse the List</a><br><br>
						  <a href="#" id="showMainList" class="btn">Add More Items</a><br><br>
						  <a href="#" id="saveBtn2" class="saveList btn">Save Your List</a>
					  </div>
					  <div id="theMap"></div>
				  </div>
				  
				  
				  <script>
					$(function() {
						//$( ".setDrag" ).draggable({ revert: "invalid" });
						//myAutocompleteMap("/storeDirectories/search.php");
						myAutocompleteShopping();
						
						var myWantedList = "<?php echo $wantedList;?>";
						//$("input#listNumber").val(myWantedList);
						
						
						if(myWantedList !== false){
							var listCount = <?php echo count($theList['items']); ?>;
							var theItems = <?php echo json_encode($theList['items']); ?>;
							
							$.each(theItems,function(){
								var theItem = this.item_id;
								$("#item" + theItem).parent("li").detach().appendTo("#dropHere");
								$("#item" + theItem).siblings("i.toDropHere").removeClass("toDropHere icon-plus-sign").addClass("toFromHere icon-minus-sign");
							});
							
							if(theItems.length > 1){
								$("#mapButton, #saveBtn1").removeClass("hideObject");
								$("#dropHere .placeholder").addClass("hideObject");
							}
						}
						
						$("#showMainList").bind("click", function(e){
							e.preventDefault();
							$("#chosenItems").addClass("hideObject");
							$("#pickItems").removeClass("hideObject");
						});
						
						$("#reverseList").bind("click", function(e){
							e.preventDefault();
							$top = $('#theMap');
							$top.children('div').slice(1).each(function() {
								$(this).insertBefore($top.children().eq(0));
							});
						});
						
						$("#saveBtn1, #saveBtn2").bind("click", function(e){
							e.preventDefault();	
							var listNum = $("#theListNumber").text();
							//console.log("The list number before ajax call is: " + listNum);
							//var userName = $("#userName").text();
							var theList = $("#dropHere").children("li").not(".placeholder").map(function() {
									return $("div.itemName", this).attr("id").replace("item", "");
								}).get();;
							//theList.push({"userName": userName});
							//console.log(theList);
							$.ajax({        
							   type: "POST",
							   url: "/admin/lookUp.php",
							   data: { action : "saveList", list : theList, listID: listNum },
							   success: function(data) {
									//alert(data.theList);
									if(data == true){
									  //$("#listNumber").val(data.listNumber);
									  $("#saveMsgAJAX").html("Your list has been saved!").addClass("label-success").removeClass("hideObject");
									}else{
									  //$("#listNumber").val(data.listNumber);
									  $("#saveMsgAJAX").html("Your list was not saved!").addClass("label-important").removeClass("hideObject");
									}
									
									setTimeout(function () {
										$("#saveMsgAJAX").addClass("hideObject");
									}, 3000);
									//console.log(data.added);
									//console.log("the list number is: " + data.listNumber);
							   }
							}); 
						});
						
						
						altBackground();
						
						
						
						
						function altBackground(){
							if($("#fromHere").is(".filteredList")){
								$("#dropHere li, #fromHere li").removeClass("altBG");
								$("#dropHere li.setDrag:nth-child(2n-1)").not(".placeholder").addClass("altBG");
								$("#fromHere li.filtered:odd").addClass("altBG");
							}else{
								$("#dropHere li, #fromHere li").removeClass("altBG");
								$("#dropHere li.setDrag:odd, #fromHere li.setDrag:nth-child(2n)").addClass("altBG");
							}
						}
						
						$(document).on("click", "p.itemDimCheck", function(){
							if($(this).hasClass("dimSelection")){
								$(this).removeClass("dimSelection");
								$("input", this).prop("checked", false);
							}else{
								$(this).addClass("dimSelection");
								$("input", this).prop('checked', true);
							}
						});
						
						$( "#dropHere, #fromHere" ).sortable({
							connectWith: ".connectList",
							delay: 300,
							stop: function(event, ui){
								//console.log(ui);
								if($(this).attr("id") == "fromHere"){ //if it comes from #fromHere
									var myCount = $("#dropHere").children().length;
									//$(".clickable", ui.item).insertBefore($(".draggable", ui.item));
									if(myCount > 1){
										$("#dropHere .placeholder").addClass("hideObject");
										$("#mapButton, #saveBtn1").removeClass("hideObject");
									}
									$(".clickable", ui.item).removeClass("toDropHere icon-plus-sign").addClass("toFromHere icon-minus-sign");
								}else{//if it comes from #dropHere
									var myCount = $("#dropHere").children().length;
									$(".clickable", ui.item).insertAfter($(".draggable", ui.item));
									if(myCount == 1){
										$("#dropHere .placeholder").removeClass("hideObject");
										$("#mapButton, #saveBtn1").addClass("hideObject");
									}
									$(".clickable", ui.item).removeClass("toFromHere icon-minus-sign").addClass("toDropHere icon-plus-sign");
								}
								var targetListID = ui.item.parent().attr("id");
								var theList = $("#" + targetListID + " li").sort(compare_name);
								$("#" + targetListID).append(theList);
								altBackground();
								checkSourceList();
								var countHTML = "(" + (myCount - 1) + " item" + ((myCount - 1) != 1 ? "s" : "") + ")";
								$("#itemCount").html(countHTML);
							}
						}).disableSelection().on("mouseup", ".clickable, .draggable", function(){
							if($(this).is(".clickable")){
								var	theClickedClass = "clickable"; 
							}else if($(this).is(".draggable")){
								var	theClickedClass = "draggable";
							}
							
							var targetList = $("#dropHere, #fromHere").not($(this).closest("ul"));
							var targetListID = targetList.attr("id");
							var myLi = $(this).closest("li");
							
							
							myLi.detach().appendTo(targetList);
							
							
							var theTarget = $(this).children("i.directionIcon");
							//console.log(theTarget);
							if(targetListID == "dropHere"){
								var myCount = $("#dropHere").children().length;
								//$(theTarget).insertBefore($(".sortName", myLi));
								if(myCount > 1){
									$("#dropHere .placeholder").addClass("hideObject");
									$("#mapButton, #saveBtn1").removeClass("hideObject");
								}
								$(theTarget).removeClass("toDropHere icon-plus-sign").addClass("toFromHere icon-minus-sign");
							}else{
								var myCount = $("#dropHere").children().length;
								$(theTarget).insertAfter($(".sortName", myLi));
								if(myCount == 1){
									$("#dropHere .placeholder").removeClass("hideObject");
									$("#mapButton, #saveBtn1").addClass("hideObject");
								}
								$(theTarget).removeClass("toFromHere icon-minus-sign").addClass("toDropHere icon-plus-sign");
								if(myLi.parent("ul").is(".filteredList") && myLi.not(".filtered")){
									myLi.addClass("hideObject");
								}
							}
							
							var theList = $("#" + targetListID + " li").sort(compare_name);
							$("#" + targetListID).append(theList);
							altBackground();
							checkSourceList();
							var countHTML = "(" + (myCount - 1) + " item" + ((myCount - 1) != 1 ? "s" : "") + ")";
							$("#itemCount").html(countHTML);
						});
						
						function checkSourceList(){
						  var numVisible = $("#draggable #fromHere li").not(".hideObject");
						  //console.log(numVisible);
						  if(numVisible.length == 0){
							$("#autocomplete").val("");
							$("#draggable #fromHere li").removeClass("hideObject");
						  }
						}
						
						var compare_name = function (a,b){
						  aText = $(a).text();
						  bText = $(b).text();
						  if (aText < bText) {
							  return -1;
						  } else if (aText > bText) {
							  return 1;
						  }
						  return 0;
						};
						
						/*$( "#dropHere" ).droppable({
							drop: function( event, ui ) {
								$( this )
									.find( "p" )
									.html( "Dropped!" );
								$( "<li></li>" ).text( ui.draggable.text() ).appendTo( this );
							}
						});*/
					});
				  </script>
				  
				<?php
				  }//else if($action == "list")
				  else if($action == "view" || $action == "print"){
					//$users = new users();
					//$theUser = $users->getUserInfo($_SESSION['UserID']);
					//$storeObj = new stores();
					//$theItems = $storeObj->getUsedDirectoryItems($theUser['pref_store']);
					
					$allItems = array();
				?>
				  <h1>Your shopping list: <?php echo $theListName; ?></h1>
				  <div class="functionBtns">
					<p class="hideObject"><a href="#" id="mapButtonView">Map</a></p>
					<p>
					  Map your route through:
					  <select id="storeLocationSelect">
						<option value="none">Select a location</option>
					  <?php
						  $allStores = $users->getAllStoreLocations();
						  foreach($allStores as $oneStore){
					  ?>
							  <option value="<?php echo $oneStore['store_id']; ?>"><?php echo $oneStore['store_name']; ?></option>
					  <?php	
						  }
					  ?>
					  </select>
					</p>
				  </div>
				  <script>
					var theListItems = <?php echo json_encode($theList['items']); ?>;
					var theIDfromStore = "0";
					var theStoreAisle = "0";

					//console.log(theListItems);
					
					$("#storeLocationSelect").bind("change", function(){
					  var theLocation = $(":selected", this).val();
					  //console.log(theLocation);
					  if(theLocation != "none"){
						$.ajax({        
						  type: "POST",
						  url: "/admin/lookUp.php",
						  data: { action : "itemsByStore", location : theLocation },
						  success: function(data) {
							//console.log(theListItems);
							$.each(data, function(){
							  //console.log(this);
							  theIDfromStore = this.item_id;
							  theStoreAisle = this.aisle;
							  
							  $.each(theListItems, function(){
								var theIDfromList = this.item_id;
								if(theIDfromList == theIDfromStore){
								  $("#item_" + theIDfromList).removeClass().addClass("itemDimCheck " + theStoreAisle);
								  //console.log("fromStore: " + theIDfromStore + "\nfromList: " + theIDfromList);
								}
							  });
							});
						  }
						});
						setTimeout(function(){
						  $("#mapButtonView").click();
						}, 500);
					  }
					});
				  </script>
				  <div class="offsetPadLeft" id="shopListContainView">
					<?php
						//echo "<pre>";
						//var_dump($theList);
						//echo "</pre>";
						foreach($theList['items'] as $anItem){
					?>
						  <p class="itemDimCheck" id="item_<?php echo $anItem['item_id']; ?>"><input type="checkbox" name="item[]"/> &nbsp;<span class="itemNameHolder"><?php echo $anItem['item_name']; ?></span></p>
					<?php
						}
					?>
				  </div>
					
				  <?php
					}//end else if($action == "view")
				  ?>
			  </div>
			  <?php
				if($action == "view"){
			  ?>
				<p><a class="btn" href="/shoppingList/print/<?php echo $wantedList; ?>">Print List</a></p>
			  <?php
				}
			  ?>
		  </div>
		  <!--</form>-->
	    </div>
	    
	    
      </section>
      
    </section>
      
    
    
    
    
    
    

  
  
  
  
  
  <script>
   //var theAction = "<?php echo $action; ?>";
   
   
   ks.ready(function() {
      // JavaScript placed here will run only once Kickstrap has loaded successfully.
      
   });
  </script>
  
<?php require($_SERVER['DOCUMENT_ROOT'] . '/common/footer.php'); ?>
<?php 
  if($action == "print"){
?>
	<script>
	  var theContent = $("#shoppingOffset");
	  $("body").css("background", "none").children().not("script").remove();
	  $("body").prepend(theContent);
	  
	</script>
<?php
	}//end if($action == "print")
?>
<script>
	  
	  
	  
	  $(document).ready(function(e) {
		  $("#accountContain h3:first").addClass("lessMargTop");   
		  
		  var userName = "<?php echo $_SESSION['Username'] ?>";
		  //$("#senderEmail").val(userName); 
		  
		  var sharedList = "<?php echo $listShared; ?>";
		  if(sharedList == true){
			  $("#sharedMessage").removeClass("hideObject");
			  
			  setTimeout(function () {
				  $("#sharedMessage").addClass("hideObject");
			  }, 3000);
		  }
		  
		  var addListResult = "<?php echo $addListFailed; ?>";
		  if(addListResult == true){
			  $("#addFailed").removeClass("hideObject");
			  
			  setTimeout(function () {
				  $("#addFailed").addClass("hideObject");
			  }, 5000);
		  }
	  });
	  
	  
	  $(".edit").bind("click", function(e){
		  e.preventDefault();
		  var $this = $(this);
		  
		  $this.parents("div.listContents").children(".nameChange").removeClass("hideObject");
	  });
	  
	  $(".save").bind("click", function(e){
		  e.preventDefault();
		  var $this = $(this);	
		  var $nameInputParent = $this.parents("div.listContents").children(".nameChange");
		  var newName = $nameInputParent.children("input").val();
		  var adam = $this.parents("#editBtns").children(".editContain");
		  var listNum = $this.parents("div.listContents").children("p#editBtns").children("span.editContain").attr("id").replace("edit", "");
		  
		  $.ajax({        
			 type: "POST",
			 url: "/admin/lookUp.php",
			 data: { action : "saveListName", listName : newName, listNum : listNum },
			 success: function(data) {
				  //alert(data.theList);
				  $this.parents("div.listContents").children(".nameChange").addClass("hideObject");
				  if(data = true){
					var theMessage = "Your changes have been saved!";
					var messageClass = "text-success";
					$this.parents("div.listContents").children(".listName").children("a").html(newName.replace(/\\/g, ''));
				  }else{
					var theMessage = "There was an error. Please try again.";
					var messageClass = "text-important";
				  }
				  $this.parents("div.listContents").children(".saveMsg").html(theMessage).addClass(messageClass).removeClass("hideObject");
				  $this.addClass("hideObject");
				  
				  setTimeout(function () {
					  $this.parents("div.listContents").children(".saveMsg").addClass("hideObject");
				  }, 3000);
				  //console.log(data.added);
				  //console.log("the list number is: " + data.listNumber);
			 }
		  });
		  
	  });
	  
	  $(".cancelName").bind("click", function(e){
		  e.preventDefault();
		  //maybe do some preprocessing here
		  $("#newName").val("");
		  $(".nameChange").addClass("hideObject");
	  });
	  
	  $(".delete").bind("click", function(e){
		  e.preventDefault();
		  var $this = $(this);
		  //console.log($this.parents("div.listContents").children(".deleteMessage").is(".hideObject"));
		  if($this.parents("div.listContents").children(".deleteMessage").is(".hideObject")){
			  $this.parents("div.listContents").children(".deleteMessage").removeClass("hideObject");	
		  }else{
			  $this.parents("div.listContents").children(".deleteMessage").addClass("hideObject");
		  }
	  });
	  
	  $(".deleteYes").bind("click", function(e){
		  var $this = $(this); 
		  var listNum = $this.parents(".deleteMessage").attr("id").replace("delete", "");
		  
		  $.ajax({        
			 type: "POST",
			 url: "/admin/lookUp.php",
			 data: { action : "deleteList", listNum : listNum },
			 success: function(data) {
				  //alert(data.theList);
				  var $myLi = $this.parents("li");
				  $myLi.addClass("text-success").html("You have deleted the list");
				  
				  setTimeout(function () {
					  $myLi.remove();
				  }, 3000);
				  //console.log(data.added);
				  //console.log("the list number is: " + data.listNumber);
			 }
		  });	
	  });
	  
	  $(".deleteNo").bind("click", function(e){
		  $(this).parents("div.listContents").children(".deleteMessage").addClass("hideObject");
	  });
	  
	  $("#addList").bind("click", function(e){
		  var userName = "<?php echo $_SESSION['Username'];?>";
		  
		  $.ajax({        
			type: "POST",
			url: "/admin/lookUp.php",
			data: { action: "newList", userID : userID },
			success: function(data) {
			  //alert(data.theList);
			  window.location.href = docRoot + "shoppingList/account";
			}
		  });
	  });
	  
	  $("#chooseLocations").bind("change", function(e){
		  e.preventDefault();
		  //var userID = "<?php echo $_SESSION['UserID'];?>";
		  var $this = $(this);
		  var theValue = $this.val();
		  var theText = $(":selected", $this).text();
					  
		  if(theValue != "none"){
			  $.ajax({        
				 type: "POST",
				 url: "/admin/lookUp.php",
				 data: { action : "changeLocation", newLocation: theValue, userName : userID },
				 success: function(data) {
					  //alert(data.theList);
					  //console.log(theText);
					  $("#locationMsg").removeClass("hideObject");
					  $("#allLocations").addClass("hideObject");
					  $(".storeName").text(theText);
					  
					  //$(".changeLoc").text("change");
					  setTimeout(function () {
						  $("#locationMsg").addClass("hideObject");
					  }, 3000);
					  //console.log(data.added);
					  //console.log("the list number is: " + data.listNumber);
				 }
			  });
		  }
	  });
	  
	  $(".changeLoc").bind("click", function(e){
		  e.preventDefault();
		  $("#allLocations").toggleClass("hideObject");
		  //var newText = $(this).text() == "change" ? "hide" : "change";
		  //$(this).text(newText);
	  });
	  
	  $(".share").bind("click", function(e){
		  e.preventDefault();
		  var $this = $(this);
		  var listURL = $this.attr("id");
		  $("#listURL").val(listURL);
		  $("#mailContain").removeClass("hideObject");
		  var store = $this.parents(".listContents").children(".listName").children().text();
		  $("#formListName").text("Fill out the form to share: " + store);
	  });
	  
	  
	  
	  $("#cancel").bind("click", function(e){
		  e.preventDefault();
		  var val = $(this).val();
		  $("#receiveEmail, #message").val("");
		  $("#mailContain").addClass("hideObject");
	  });
	  
	  $("#send").bind("click", function(e){
		  e.preventDefault();
		  //maybe do some preprocessing here
		  $("form#shareform").submit();
	  });
	  
	  $("#mapButton").bind("click", function(e){
		  e.preventDefault();
		  var aisleNames = ["Pharmacy", "Back Aisle", "Dairy", "Front End", "Produce", "Treasure Aisle"];
		  var theList = $("#dropHere").children("li").not(".placeholder");
		  
		  var myHTML = mapTheList(theList, aisleNames, "div.sortName");
		  
		  $("#theMap").html(myHTML);
		  $("#pickItems").addClass("hideObject");
		  $("#chosenItems").removeClass("hideObject");
	  });
	  
	  $("#mapButtonView").bind("click", function(e){
		  e.preventDefault();
		  var aisleNames = ["Pharmacy", "Back Aisle", "Dairy", "Front End", "Produce", "Treasure Aisle"];
		  //var theList = $("#shopListContainView").children("p");
		  var theList = $("#shopListContainView .itemDimCheck");
		  //console.log(theList);
		  
		  var myHTML = mapTheList(theList, aisleNames, ".itemNameHolder");
  		  
		  $("#shopListContainView").html(myHTML);
		  //$("#pickItems").addClass("hideObject");
		  //$("#chosenItems").removeClass("hideObject");
	  });
	  
	  function mapTheList(theList, aisleNames, itemNameHolder){
		var listWithAisle = [];
  
		$.each(theList, function(){
			var theClasses = $(this).attr("class").split(/\s+/);
			//console.log(theClasses);
			for(i=0; i < theClasses.length; i++){
				if(theClasses[i] != "altBG" && theClasses[i] != "setDrag" && theClasses[i] != "clearfix" && theClasses[i] != "itemDimCheck" && theClasses[i] != "clickable"){
					var aisleName = theClasses[i] == "null" ? " Information not Found" : theClasses[i];
					//console.log(aisleName);
				}
				
			}
			var itemName = $(itemNameHolder, this).html();
			var itemNum = $(this).attr("id").replace("item_", "");
			var pushThis = [itemName, aisleName, itemNum];
			listWithAisle.push(pushThis);
		});
		
		var myHTML = "";
		
		listWithAisle.sort(compare_rows_aisle);
		
		//console.log(listWithAisle);
		var oldAisle = "z";
		for(j = 0; j < listWithAisle.length; j++){
			//console.log(listWithAisle[j]);
			if(listWithAisle[j][1] != oldAisle && oldAisle != "z"){
				myHTML += "</div>";
			}
			
			if(listWithAisle[j][1] != oldAisle){
				var aisleCheck = listWithAisle[j][1].replace("_", " ");
				var theCheck = $.inArray(aisleCheck, aisleNames);

				if(theCheck > -1){
					var finalAisle = aisleCheck;
				}else{
					var finalAisle = "Aisle " + aisleCheck;	
				}
				myHTML += "<div class='mapAisles'><h2>" + finalAisle + "</h2>";
				
			}
			myHTML += "<p id='item_" + listWithAisle[j][2] + "' class='itemDimCheck'><input type='checkbox' name='item[]'/> &nbsp;<span class='itemNameHolder'>" + listWithAisle[j][0] + "</span></p>";
			
			oldAisle = listWithAisle[j][1];
		}
		myHTML += "</div>";
		
		return myHTML;
	  }
	  
	  var compare_rows_aisle = function (a,b){
		if(a[1].length == 1){
			var newA = "0" + a[1];
		}else{
			var newA = a[1];
		}
		
		if(b[1].length == 1){
			var newB = "0" + b[1];
		}else{
			var newB = b[1];
		}
		
		
		if (newA < newB) {
			return -1;
		} else if (newA > newB) {
			return 1;
		}
		return 0;
	  };
	  
	  
  </script>