<?php
if ($_SESSION['FirstName'] == "") {
	//echo 'You are not authorized to view this page. <br><br>You may <a href="index.php">log in here.</a>';
	//exit;
} else {
	 //require_once ('mysql_connect.php');
	$action            = $_GET["a"];
	$pagename          = $_GET["pagename"];
	$editpage          = $_REQUEST["page"];
	if(empty($editpage)){
		$editpage      = $_GET["key"];
	}
	
//print_r($_POST);
	
	function update_nav_tables($button_text="", $button_url, $pageid){
		$nav_tables = array("nav_menu", "nav_menu_mobile", "nav_slider_mobile");
		foreach ($nav_tables as $table){
			$sql = "update $table set ";
			$sql.= " button_url='$button_url' ";
			if($button_text<>''){
				$sql.= ",  button_text='$button_text'";
			}
			$sql.= " where pageid='$pageid'";
			//echo "$sql<br>";
			mysql_query($sql);
		}
	}
				
	//add function to update wysiwyg image URL's, based on live domain or dev url in sub folder
	function updateImagePaths($block){
		$url = $_SERVER['REQUEST_URI'];	
		$root = $_SESSION['root_folder'];
		if(stristr($url, $root)){
			//add root folder to image paths - first strip it off if it exists since it may or may not exist
			$newstring = $root."/custom/images";
			$newstring = $root;
			$block = str_replace("/custom/images", "/$newstring/custom/images", $block);
		} else {
			//remove root folder from image paths		
			$block = str_replace($root, "", $block);
			$oldstring = $root."/custom/images";
		}
		return $block;
	}
	
	//Code to save time setting for menu
	$globalMenuId = 0;
	$globalPageId = 0;
	$globalPageRecordKey=$editpage;
	if(isset($_POST['save-menu-time']))
	{
		//delete existing page setting		
		$delQuery = "DELETE from menu_time_setting where 
					 menu_page_id='".$_POST['menu_id']."' ";
		$delResult = mysql_query($delQuery);

		//insert code here
		$i=0;
		foreach ($_POST['menu'] as $key => $value)
		{
			$menuId = $_POST['menu_id'];
			$pageID = $_POST['page_id'];
			$menuName =  $value;
			$userId = $_SESSION['UserID'];
		 	$starttime = $_POST['start_time'][$i];
			$query = "INSERT INTO menu_time_setting (pageId,menu_page_id,menu_name,start_time,user_id)
					  values('".$pageID."' , '".$menuId."' ,'".$menuName."', '".$starttime."' , '".$userId."')";
			mysql_query($query);
			$i++; 
		}
	}


	//$cwd = getcwd(); 
	//$url = $_SERVER['REQUEST_URI'];
	//echo $cwd . "<br>";
	//echo $url . "<br>";
	//for testing:
	//echo "post page = " . $_POST["page"];
	//echo "<br>get key = " . $_GET["key"];
	//echo "<br>page name = " . $pagename;
	
	//get number of widgets allowed in each area
	$widget_qry="Select bottom_widgets, top_widgets from admin_options";
	$rt=mysql_query($widget_qry);
	 while($nt=mysql_fetch_array($rt)){
		$bottom_widgets=$nt[bottom_widgets];	
		$top_widgets=$nt[top_widgets];	
	}
	
	
	if(!empty($pagename)){
		$query = "Select pageID from content where pageTitle='$pagename'";
		$rt=mysql_query($query);
	    while($nt=mysql_fetch_array($rt)){
			$editpage=$nt[pageID];	
		}
	}
	//if page id still empty, use 1 for home page
	if(empty($editpage)){$editpage='1';}
	
	
	//echo "<br>editpage = " . $editpage;
	
	$current_dir = str_replace("/rooadmin", "", dirname($_SERVER['PHP_SELF']));
	//$current_dir = dirname($_SERVER['PHP_SELF']);
	//echo "current dir:" . $current_dir;
	
	//function to build seo-friendly url link
	setlocale(LC_ALL, 'en_US.UTF8');
	function toAscii($str, $replace=array(), $delimiter='-') {
		if( !empty($replace) ) {
			$str = str_replace((array)$replace, ' ', $str);
		}
	
		$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
		$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
		$clean = strtolower(trim($clean, '-'));
		$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
	
		return $clean;
	}
	
	
	if (!empty($_POST["chkDelete"])) {
	     $query = "delete from content WHERE recordKey = '" . $_GET['key'] ."'";
	     mysql_query($query);
	     echo "<font color=red>Page deleted successfully.</font>";
	     unset($action);
	}
		//echo 'Action = ' . $action; (for testing)
	/*
	if ($action == "addwidget") {
		$widgetid=$_GET['wid'];
		$pagearea=$_GET['area'];
		echo "editpage=". $editpage;
		echo "<br>widgetid=". $widgetid;
		echo "<br>pagearea=". $pagearea;
		if((!empty($editpage)) && (!empty($widgetid)) && (!empty($pagearea))){
			if($pagearea=="1"){$area="sidebar";} elseif($pagearea=="2"){$area="top";}elseif($pagearea=="3"){$area="bottom";}
			$sql_update = "insert into pageWidgets (pageid, widgetid, $area) values ('$editpage', '$widgetid', '1') ";
			echo "qry=". $sql_update;
			mysql_query($sql_update);
		}
	}
	*/
	if ($action == "remwidget") {
		$widgetid=$_GET['wid'];
		$pagearea=$_GET['area'];
		//echo "editpage=". $editpage;
		//echo "<br>widgetid=". $widgetid;
		//echo "<br>pagearea=". $pagearea;
		if((!empty($editpage)) && (!empty($widgetid)) && (!empty($pagearea))){
			if($pagearea=="1"){$area="sidebar";} elseif($pagearea=="2"){$area="top";}elseif($pagearea=="3"){$area="bottom";}
			$sql_update = "delete from pageWidgets where pageid='$editpage' AND widgetid='$widgetid' and $area='1'";
			//echo "qry=". $sql_update;
			mysql_query($sql_update);
		}
	}	
		
	if ($action == "add") {
	         $query = "Select max(pageID) as pageID from content";
	         	$rt=mysql_query($query);
	         	while($nt=mysql_fetch_array($rt)){
	              $pageid = $nt[pageID] +1;
	            }
	            mysql_close;
	        if((strtoupper($_POST["newpage"])!=="HOME")&&(strtoupper($_POST["newpage"])!=="COUPONS")){
				 //create permalink before adding new page	
				 $dirty=mysql_real_escape_string($_POST['newpage']);
				 $permalink = toAscii($dirty);
				 
				 //if selecting to add to nav menu, set page to active right away
				 if(!empty($_POST[show_on_menu])){
				 	$active = "1";		
				 } else {
				 	$active = "0";
				 }
				 
				 $query = "Insert into content (pageTitle, enableUpdates, addon, pageID, permalink, active) values('" . mysql_real_escape_string(strtoupper($_POST["newpage"])) . "', '1', '1', " . $pageid . ",'$permalink', '$active')";
				 mysql_query($query);
				 $query = "Select max(recordKey) as recordKey from content where enableUpdates=1";
				 $rt=mysql_query($query);
				 while($nt=mysql_fetch_array($rt)){
				 	  $editpage = $nt[recordKey];
				 }
				 mysql_close;
					
				//add to nav menu if selected	
				if(!empty($_POST[show_on_menu])){
					//selected to display on navigation menu. add record now.
					$sql="INSERT INTO nav_menu ( button_text, button_url, nav_order, pageid, active) VALUES ('" . mysql_real_escape_string(strtoupper($_POST["newpage"])) . "', '".$permalink."', '999', '".$pageid."', '1')";
					mysql_query($sql);
				}
			}
	}
	
	                      //******************make any updates if any
	if ($action == "update") {
		//get pageID first
		$sql="SELECT * from content where recordKey='$editpage'";
		$rt=mysql_query($sql); 
		while($nt=mysql_fetch_array($rt)){
			$pageid=$nt[pageID];
			$permalink = $nt[permalink];
		}
		
		if($_POST['alias']){
			$button_text=mysql_real_escape_string($_POST['alias']);
		} else {
			$button_text=mysql_real_escape_string($_POST['pagename']);
		}
						
		if($pageid=='1'){
			$button_url="index.php";
		} else {
			$button_url=$_POST['permalink'];
		}
				
		$query = "UPDATE content SET ";
		
		if($_GET[section]=="general"){
			$alias = strtoupper(mysql_real_escape_string($_POST['alias']));
			$pagetitle = strtoupper(mysql_real_escape_string($_POST['pagename']));
			//$parentpage = mysql_real_escape_string($_POST['parentpage']);
			$query .="tagline = '" . mysql_real_escape_string($_POST['tagline']) . "', marquee = '" . mysql_real_escape_string($_POST['marquee']) . "', slideshow_gallery = '" . $_POST['gallery'] . "', block1 = '" . mysql_real_escape_string($_POST['block1']) . "',  pageTitle = '"
			. strtoupper(mysql_real_escape_string($_POST['pagename'])) . "', alias = '". strtoupper(mysql_real_escape_string($_POST['alias'])) . "',   block3 = '" . mysql_real_escape_string($_POST['block3']) . "', active =";
			if(!empty($_POST['chkActive'])){
				$query .= "1";
			}else{
				$query .= "0";
			}
			$query .= ", full_width =";
			if(!empty($_POST['chkFullWidth'])){
				$query .= "1";
			}else{
				$query .= "0";
			}
			
			
			if($_POST['page_type']!=''){
				$query .=", page_type='".$_POST['page_type']."'";
			}
			if($_POST['prod_cat']){
				$query .=", product_category='".$_POST['prod_cat']."'";
			}
			if($_POST['menu_name']){
				$query .=", menu_id='".$_POST['menu_name']."'";
			}
			if(!empty($_POST['blog_cat'])){
				$query .=",blog_category='".$_POST['blog_cat']."'";
			}
			if(!empty($_POST['formnumber'])){
				$query .= ", formNumber ='".$_POST['formnumber'] ."'";
			}else{
				$query .= ", formNumber ='0'";
			}

			//set page format - desktop, mobile or blank = both
			$query .=", availability='".$_POST['page_format']."'";
				

			update_nav_tables($button_text, $permalink, $pageid);	
				
				
				
							
		}
		
		if($_GET[section]=="html"){
			$query .="block2 = '" . addslashes($_POST['block2']) . "'";
		}
		if($_GET[section]=="lennox"){
			$query .="lennox_api = '" . mysql_real_escape_string($_POST['lennox_api']) . "'";
		}
		if($_GET[section]=="style"){
			$query .="custom_css = '" . mysql_real_escape_string($_POST['custom_css']) . "'";
			$query .=", page_layout = '" . $_POST[page_layout] . "'";
		}
		
		if($_GET[section]=="widgets"){
			$query .="widgets_pageid = '" . mysql_real_escape_string($_POST['use_widgets_from']) . "'";
		}
		
		if($_GET[section]=="popup" || isset($_POST[save_popup])){
			$query = "UPDATE content SET ";
			$query .=" use_popup = '" . mysql_real_escape_string($_POST['use_popup']) . "'";
			$query .=", popup_includes_file = '" . mysql_real_escape_string($_POST['popup_type']) . "'";
			$query .=", popup_content = '" . mysql_real_escape_string($_POST['popup_content']) . "'";
			$query .=", popup_button_text = '" . mysql_real_escape_string($_POST['popup_button_text']) . "'";
			$query .=", popup_title = '" . mysql_real_escape_string($_POST['popup_title']) . "'";
			
			//echo $query;
			
		}
		
		if($_GET[section]=="seo"){
			$query.=" seo_title='".mysql_real_escape_string($_POST[seo_title])."', seo_description='".mysql_real_escape_string($_POST[seo_description])."', seo_keywords='".mysql_real_escape_string($_POST[seo_keywords])."'";
		
			//add/update user friendly URL to point to this page
				if(empty($_POST['seo_permalink'])){
					$dirty=$_POST['pagename'];
					$permalink = toAscii($dirty);				
				} else {
					$dirty=$_POST['seo_permalink'];
					$permalink = toAscii($dirty);				
				}
			$query.=", permalink='$permalink'";
			
			$button_text = ""; //do not pass in a value here - it will not update
			update_nav_tables($button_text, $permalink, $pageid);
			
			
		}
		$query .= " WHERE recordKey = '" . $_GET['key'] ."'" ;	
			
			
			//echo $query;
			mysql_query($query) or die(mysql_error());   //execute query
	
			//confirmation message that update worked...
			echo "<font color=red>Page content updated successfully.</font>";
			
			//************************** SAVE A COPY IN BACKUP TABLE ***************************
			$query = "SELECT * FROM content where recordKey = '" . $_GET['key'] ."'" ;	
			$result = mysql_query($query);
			$save_copy = "insert into content_backup (alias, tagline, marquee, pageTitle, include_file, slideshow_gallery, seo_title, seo_description, seo_keywords, permalink, 
			use_popup, popup_title, popup_content, popup_includes_file, popup_button_text, parent_page_id, custom_css, page_type, product_category, use_home_widgets, formNumber, 
			widgets_pageid, blog_category, block1, block2, block3) values (";	
			while ($data = mysql_fetch_array($result)) {
					 $save_copy .= "'".mysql_real_escape_string($data[alias])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[tagline])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[marquee])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[pageTitle])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[include_file])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[slideshow_gallery])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[seo_title])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[seo_description])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[seo_keywords])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[permalink])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[use_popup])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[popup_title])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[popup_content])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[popup_includes_file])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[popup_button_text])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[parent_page_id])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[custom_css])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[page_type])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[product_category])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[use_home_widgets])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[formNumber])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[widgets_pageid])."',";
					 $save_copy .= "'".mysql_real_escape_string($data[blog_category])."',";
					 $save_copy .= "'".mysql_real_escape_string($data['block1'])."',";
					 $save_copy .= "'".mysql_real_escape_string($data['block2'])."',";
					 $save_copy .= "'".mysql_real_escape_string($data['block3'])."'";
			}
			$save_copy .= ")";
			//mysql_query($save_copy);
			mysql_query($save_copy) or die(mysql_error());
	
			//write to log for testing
			//$update = "Insert into test_log (field1) values('".mysql_real_escape_string($save_copy)."')";	
			//mysql_query($update) or die(mysql_error());
			
			//echo "$save_copy";
			//confirmation message that backup copy saved...
			//echo "<br><font color=red>Backup copy created successfully.</font>";
			
		}	                  //*******************end of update section
		
		if(!empty($editpage)){
	    $query = "SELECT * from content where recordKey =" . $editpage ;
	    } else{
	    $query = "SELECT * from content where pageTitle ='HOME'" ;
	    }
			//$query = "SELECT * from content where enableUpdates='1' and addon='0'";
			$rt=mysql_query($query);          // query executed 
			echo mysql_error();                    // if any error is there that will be printed to the screen
	
	echo '<div id="single-admin-button">
	<ul>
	<a href="index.php"><li>BACK TO HOME ADMIN</li></a>
	</ul>
	</div>';
	
		 //create selector to choose page to edit
		 echo '<form style="margin-left:4px;" action="' . $_SERVER['PHP_SELF'] . '?a=select" method="post">';
		 echo'Choose a page to edit: <br /><select name="page" style="width:213px;">';
		 $pages="Select recordKey, pageTitle from content where enableUpdates='1'";
		 
		 //hide these two pages from being edited here, unless page selected from another page
		 if($pagename!=="COUPONS"){
			$pages .= " AND pageTitle <> 'COUPONS'";
		 }
		 //if($pagename!=="SPECIALS"){
		 //$pages .= " AND pageTitle <> 'SPECIALS'";
		 //}
		 //if($restaurant_pkg!='1'){
		//	$pages .= " AND pageTitle <> 'MENU'";
		 //}
		 
		 $pages.=" order by pageTitle ";	 
		 
		 $pg=mysql_query($pages);
		 while($pnt=mysql_fetch_array($pg)){
			echo '<option value='. $pnt[recordKey];
			if($pnt[recordKey]==$editpage){echo ' selected="selected"';}
			echo'>' .$pnt[pageTitle] . ' </option>';
		}
		echo '</select> <input id="save-button" type="submit" name="select" value="Edit"> &nbsp; &nbsp; &nbsp;- OR - </form>';	
		
		
		echo '<div id="new-page-wrapper"><form action="' . $_SERVER['PHP_SELF'] . '?a=add" method="post">Add a new page: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="checkbox" name="show_on_menu" checked="checked"> 
		<a href="#" data-tooltip="Check this box if you want this page to show in your main navigation. You can also change this in the Navigation Menu area">Display on Navigation Menu</a><br />
		<input type="text" name="newpage" style="width:250px;">
		<input id="save-button" type="submit" name="save" value="Create Page">
		</form></div>';
	       
	
			
	echo '<table id="manage-page-content" border=0 cellpadding=0 cellspacing=4>';
	
	while($nt=mysql_fetch_array($rt)){
	  $addon = $nt[addon];
	  
		$form_body = '<td><table id="page-info-box"><tr><td><input type="hidden" name="recordKey" value="' . $nt[recordKey] . '"><form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $nt[recordKey] . '&section=general" method="post">';
		$form_body .= '<tr><td><div align=left>Page name: <span class="hide-field"><input class="move-right" type="text" name="pagename" size="32" value="' .  $nt[pageTitle] . '"';
		if($addon=='0'){$form_body .= 'readonly="readonly"';}
		$form_body .='></span>';
		
		//if($nt[page_type]=='5'){$form_body .='<tr><td><span style="float:right;"><a id="save-button" href="edit_list_items.php?listid='.$nt[pageID].'">Manage list items</a></span>';}
		
		  //*************** build page_type selector *******************
			$type_selector ='<div class="page-type" align=left>Page type:';
			//add list item button in page type section, if this is a list type of page
			if($nt[page_type]=='5' || $nt[page_type]=='7' || $nt[page_type]=='8'){$type_selector .='<span style="float:right;margin-bottom:8px;margin-top:3px;"><a id="save-button" href="edit_list_items.php?listid='.$nt[pageID].'"><font style="color:#fff;">Manage list items</font></a></span>';}
			$type_selector .='<select name="page_type">';
			
			$type_selector .='<option value="0"';
			if($nt[page_type]=='0'){$type_selector.=" selected=\'selected\'";}
			$type_selector .='>Standard</option>';
			
			$type_selector .='<option value="1"';
			if($nt[page_type]=='1'){$type_selector.=" selected=\'selected\'";}
			$type_selector .='>Blog - Standard</option>';
			
			if($nt[page_type]=='4'){
				$type_selector .='<option value="4"';
				if($nt[page_type]=='4'){$type_selector.=" selected=\'selected\'";}
				$type_selector .='>Blog - Full Width</option>';
			}
			$type_selector .='<option value="2"';
			if($nt[page_type]=='2'){$type_selector.=" selected=\'selected\'";}
			$type_selector .='>Products</option>';
			
			if($nt[page_type]=='3'){
				$type_selector .='<option value="3"';
				if($nt[page_type]=='3'){$type_selector.=" selected=\'selected\'";}
				$type_selector .='>Full Width</option>';
			}
			
			$type_selector .='<option value="5"';
			if($nt[page_type]=='5'){$type_selector.=" selected=\'selected\'";}
			$type_selector .='>List/Directory page</option>';
			
			$type_selector .='<option value="6"';
			if($nt[page_type]=='6'){$type_selector.=" selected=\'selected\'";}
			$type_selector .='>Menu page</option>';
			
			$type_selector .='<option value="7"';
			if($nt[page_type]=='7'){$type_selector.=" selected=\'selected\'";}
			$type_selector .='>Event page</option>';
			
			$type_selector .='<option value="8"';
			if($nt[page_type]=='8'){$type_selector.=" selected=\'selected\'";}
			$type_selector .='>Specials page</option>';
			
			$type_selector .='<option value="9"';
			if($nt[page_type]=='9'){$type_selector.=" selected=\'selected\'";}
			$type_selector .='>Account/Login page</option>';
			
			$type_selector .='</select>';
			
			//*************** end of page_type selector *******************
		
			if($nt[page_type]=='2'){
				//this is a product page, select the category you want on this page
				$form_body .='<tr><td style="width:340px;"><div align=left>Category to display: &nbsp;<span class="hide-field"><select style="max-width:63%;min-width:63%;" name="prod_cat"><option value="">All</option>';
				$category_query = "select CategoryName, RecordKey from productCategory where active='1' order by CategoryName";
				$rtcat=mysql_query($category_query);
				while($ntcat=mysql_fetch_array($rtcat)){
					$form_body .="<option value='".$ntcat[RecordKey]."'";
					if($ntcat[RecordKey]==$nt[product_category]){$form_body .=" selected='selected'";}
					$form_body .=">".$ntcat[CategoryName]."</option>";
				}				
				$form_body .='</select>';
			}
			if($nt[page_type]=='6'){
				echo "<input type='hidden' value='".$nt[pageID]."' id='pageIdBox'>";
				$globalPageId = $nt[pageID];
				$globalPageRecordKey = $nt[recordKey];
				//this is a menu page, select the menu category you want on this page
				$form_body .='<tr><td style="width:340px;"><div align=left>Menu to display: &nbsp;<span class="hide-field"><div class="menu-select-div"><select style="max-width:63%;min-width:63%;" id="menu_name" name="menu_name" onChange=saveMenuId()><option value="999">All (Auto)</option>';
				$category_query = "select recordkey, menu_name from menu_master where disabled='0' order by menu_name";
				$rtcat=mysql_query($category_query);
				while($ntcat=mysql_fetch_array($rtcat)){
					$form_body .="<option class='".$ntcat[menu_name]."' value='".$ntcat[recordkey]."'";
					if($ntcat[recordkey]==$nt[menu_id]){$form_body .=" selected='selected'"; $globalMenuId = $nt[menu_id]; }
					$form_body .=">".$ntcat[menu_name]."</option>";
				}				
				$form_body .='</select></div></div></td><td><div class=time-setting style="display:none;"><img src="images/gear-icon.png" title="Set Time Duration"></div></td>
				</tr>';
			}
			
			if($nt[page_type]=='1' || $nt[page_type]=='4'){
				//this is a blog page, select the blog category you want on this page
				$form_body .='<tr><td style="width:340px;"><div align=left>Category to display: &nbsp;<span class="hide-field"><select style="max-width:63%;min-width:63%;" name="blog_cat"><option value="999">All</option>';
				$category_query = "select * from blog_categories order by category_name";
				$rtcat=mysql_query($category_query);
				while($ntcat=mysql_fetch_array($rtcat)){
					$form_body .="<option value='".$ntcat[recordkey]."'";
					if($ntcat[recordkey]==$nt[blog_category]){$form_body .=" selected='selected'";}
					$form_body .=">".$ntcat[category_name]."</option>";
				}				
				$form_body .='</select>';
			}
		$form_body .= '<tr><td style="padding-bottom:7px;"><div align=left style="float:left;">Active: <!--<td valign="top"><div align=left>-->
		&nbsp; <input type="checkbox" name="chkActive"';
		if(!empty($nt[active])) {
	      $form_body .= ' checked=checked';
	    }
		$form_body .='">';
		if ($addon==0){	//show alias field if page is built in and pre-named
			$form_body .='<tr><td><div align=left><a href="#" data-tooltip="If you want to replace your Home page navigation title, type that in here">Alias:</a> <!--<td valign="top"><div align=left>--><input class="move-right" type="text" name="alias" size="32" maxlength="30" value="' .  $nt[alias] . '">';
		}
		if($addon==1){
			$form_body .='<tr><td><div align=left><a href="#" data-tooltip="This will add scrolling copy to the top of your page">Marquee:</a> <!--<td valign="top"><div align=left>--><input class="move-right" type="text" name="marquee" size="32" value="' . $nt[marquee] . '">';
		}
		if($nt[pageTitle]=="CONTACT"){
		
		}
		//if($nt[pageTitle]=="MENU"){
		//	$form_body .= '<tr><td colspan=2><br><br><div align="center"> <font color="red">You can edit the page alias here. Any other menu info must be edited through the menu admin area.</font></div><div align=right><input class="move-right" type="hidden" name="tagline" size="32" value="' . $nt[tagline] . '"><input id="save-button" type="submit" name="save_seo" value="Save"></div></form></div></div></li></ul></div>';
	
		//} else{
			$form_body .='<tr><td><div align=left><a href="#" data-tooltip="This is your headline copy for this page">Tagline:</a> <!--<td valign="top"><div align=left>--><input class="move-right" type="text" name="tagline" size="32" value="' . $nt[tagline] . '">';
				   
				   //*********************build form selector ***********************
					$form_selector ='<div align=left><a href="#" data-tooltip="To add a form to your page you need to first create one under Contact Forms">Include form:</a> <div align=left><select name="formnumber"><option value=""> - Select a form - </option>';
					$forms="Select recordKey, formName from formData where formID=0 AND formName>''";
					$frm=mysql_query($forms);
					while($fnt=mysql_fetch_array($frm)){
						$form_selector .= '<option value='. $fnt[recordKey];
						if($fnt[recordKey]==$nt[formNumber]){$form_selector .= ' selected="selected"';}
						$form_selector .='>' .$fnt[formName] . '</option>';
					}
	
					mysql_close;
					$form_selector .= '</select>';
					//*********************end form selector ***********************
				
					//*************** build page_width selector *******************
					$width_selector = "";
					$width_selector .= '<div style="margin-top:5px"><br>Full width: <input type="checkbox" name="chkFullWidth"';
					if(!empty($nt[full_width])) {
				      $width_selector .= ' checked=checked';
				    }
					$width_selector .='">';					
					//*************** end page_width selector *******************
				
				
					//*************** build page_format selector *******************
					$format_selector ='<div style="margin-top:15px;" class="format-type" align=left>Page format:';
					//add list item button in page type section, if this is a list type of page
					$format_selector .='<select name="page_format" class="move-right">
					<option value="0"';
					if($nt[availability]==''){$format_selector.=" selected=\'selected\'";}
					$format_selector .='>Standard - (mobile & desktop)</option>
					<option value="desktop"';
					if($nt[availability]=='desktop'){$format_selector.=" selected=\'selected\'";}
					$format_selector .='>Desktop only</option>
					<option value="mobile"';
					if($nt[availability]=='mobile'){$format_selector.=" selected=\'selected\'";}
					$format_selector .='>Mobile only</option>
					</select>';
					//*************** end of page_format selector *********
					$form_body .=$format_selector;
			
				  	if($addon==1){
						//*************** build slideshow gallery selector *******************
						$gallery_selector = 'Slideshow: ';
						$gallery_selector .= '<select name="gallery"><option value=""> -- None Selected --</option>';
						$galleries="Select gallerykey, gallery_name from gallery where active='1'";  
						$gal=mysql_query($galleries);
						while($galnt=mysql_fetch_array($gal)){
							$gallery_selector .= '<option value='. $galnt[gallerykey];
							if($galnt[gallerykey]==$nt[slideshow_gallery]){$gallery_selector .= ' selected="selected"';}
							$gallery_selector .='>' .$galnt[gallery_name] . ' </option>';
							//$gallery_selector .='>' .$pnt[pageTitle] . ' #'.$pnt[recordKey].' </option>';	//for testing - add page ID to list of pages
						}
						$gallery_selector .= '</select>';			
						//*************** end slideshow gallery selector *******************
						
						//********** assemble separate content box *********************
						$form_body .='<div id="manage-page-content_right">';
						$form_body .= $type_selector."<br>".$gallery_selector ."<br>".$form_selector."<br>".$width_selector;
						$form_body .='</div>';
						//********** end separate content box ********************* 
						
									
					} else {
						//********** assemble separate content box *********************
						$form_body .='<div id="manage-page-content_right">';
						$form_body .= $type_selector."<br>".$gallery_selector ."<br>".$form_selector."<br>".$width_selector;
						$form_body .='</div>';
						//********** end separate content box ********************* 
					}
			
					$form_body .='<tr><td>&nbsp;</td></tr><tr><td  colspan=2 valign=top><div align=left>Main content: ';
			
	
			
			
			$form_body .='<div id="preview-button-wrapper"><div id="preview-button-wrapper_float">
			<a id="preview-desktop-site" class="popup" href="#" data-popup-id="desktop_preview" data-tooltip="View your current saved page, or preview this web page before you save your content"'; 
			$form_body .='data-page-id="'.$nt['permalink'].'">Desktop Preview</a>
			&nbsp;';
			if ($_SESSION['enable_mobile']==1){
				$form_body .='<a id="preview-mobile-site" class="popup" href="#" data-popup-id="mobile_preview" data-tooltip="View your current saved mobile page, or preview this mobile page before you save your content" data-page-id="';
				$form_body .=$nt['permalink'].'">Mobile Preview</a>';
			}
			$form_body .='</div></div>
	
			<div class="toPopDiv" id="popup_desktop_preview"> 
				<div class="close"></div>
				<span class="ecs_tooltip">Esc to close <span class="arrow"></span></span>
				<iframe id="preview-desktop-iframe" name="desktop_preview_iframe" src="" data-href=""></iframe>
			</div> <!--toPopup end-->
	
			<div class="toPopDiv" id="popup_mobile_preview"> 
				<div class="close"></div>
				<span class="ecs_tooltip">Esc to close <span class="arrow"></span></span>
				<iframe id="preview-mobile-iframe" name="mobile_preview_iframe" src="" data-href=""></iframe>
			</div></td></tr></table></tr></td> <!--toPopup end-->';
			//update image path as needed - to work for live urls or dev urls
			//$block1 = updateImagePaths(stripslashes($nt[block1]));
			$block1 = stripslashes($nt[block1]);
			
			$form_body .='<tr><td colspan=2 valign=top><div align="left">
			<textarea name="block1" class="ckeditor" id="block1"  rows=25 style="width:540px;">' . $block1 . '</textarea></div>';

			
			
			
			$form_body .= '<tr><td valign="top"><div align=left>Delete: <input type="checkbox" name="chkDelete"><br /><font color=red> <i>Be sure you mean to delete this page if you check this box. You will not be prompted again.</i></font></div></td><td align="right" valign="top"><input id="save-button" type="submit" name="save_general" value="SAVE THIS PAGE"></td></tr>';
	
	
			
			//*************** $form_body .='<tr><td><td valign=top><div align=right><input id="save-button" type="submit" name="save_general" value="SAVE THIS PAGE"></div></form>'; ***********
			
			
			$form_body .='<tr><td colspan=3><ul class="acc" id="acc">
				<li><h3>Popup Box</h3> <div class="acc-section"><div class="acc-content">
				<form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $nt[recordKey] . '&section=popup" method="post">
				<div align="left"><font color="red"><i>Add a popup box on this page of your website.</i></font><br><br>
				Use popup: <select name="use_popup"><option value="0">Disabled</option>
				<option value="1"';
				if($nt[use_popup]=='1'){$form_body.=" selected=\'selected\'";}
				$form_body .='>Desktop only</option>
				<option value="2"';
				if($nt[use_popup]=='2'){$form_body.=" selected=\'selected\'";}
				$form_body .='>Mobile only</option>
				<option value="3"';
				if($nt[use_popup]=='3'){$form_body.=" selected=\'selected\'";}
				$form_body .='>Desktop & Mobile</option>
				</select><br>
				Popup Button Text: <input type="text" name="popup_button_text" value="'.$nt[popup_button_text].'"><br>
				Popup title bar: <input type="text" name="popup_title" value="'.$nt[popup_title].'"><br>			
				<br>Popup content: <textarea name="popup_content"  id="popup_content" rows=5 style="width:580px;">' . stripslashes($nt[popup_content]) . '</textarea>
				<br><br>
				Popup type: <select name="popup_type"><option value="">Standard</option>
				<option value="email_signup.php"';
				if($nt[popup_includes_file]=='email_signup.php'){$form_body.=" selected=\'selected\'";}
				$form_body .='>Email Signup Form</option>
				<option value="sms_subscriber_form.php"';
				if($nt[popup_includes_file]=='sms_subscriber_form.php'){$form_body.=" selected=\'selected\'";}
				$form_body .='>Text Signup Form</option>
				</select><br>
				</div>
				<div align=right><input id="save-button" type="submit" name="save_popup" value="Save Popup Settings"></div></form></div></div>
				</li>
	
				<li><h3>Widgets</h3> <div class="acc-section"><div class="acc-content"><form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $nt[recordKey] . '&section=widgets" method="post">
				<div id="accordian-note-top-box"><font style="font-size:.9em;"><strong>NOTE:</strong> Depending on your website template you may or may not have all widget options available.</font></div>
				<div align="left"><div style="float:left;width:420px;"><font color="red"><i>This section is for managing widgets on this page of your website.</i></font></div>
				';
				
				//override db variables for testing (comment these two lines out to pull database values)
				//$top_widgets =2;
				//$bottom_widgets = 3;
				
				//$form_body .= "Allowed top widgets: $top_widgets";
				//$form_body .= "<br>Allowed bottom widgets: $bottom_widgets";
				
				$widgetNumPlaces = array();
				
				//build page selector
				$page_selector = "<select name='use_widgets_from'><option value='0'>Do not copy - Let me choose</option>";
				$pages="Select recordKey, pageTitle from content";
				$pg=mysql_query($pages);
				while($pnt=mysql_fetch_array($pg)){
					$page_selector .= '<option value='. $pnt[recordKey];
					if($pnt[recordKey]==$nt[widgets_pageid]){$page_selector .= ' selected="selected"';}
					$page_selector .='>' .$pnt[pageTitle] . ' </option>';
				}	
				$page_selector .= "</select>";
	
				$form_body .="<div class='widget-copy-line'>Copy widgets from page: $page_selector <input id='save-button' type='submit' name='save_widgets' value='Save'><br /></div><div style='clear:both;'><hr /><br /></div>";
			
		//if this page is not inheriting widgets from another page, allow choosing them here		
		if($nt[widgets_pageid]=='0'){
		// BEGIN WIDGET SELECTION AREA
			//available widgets			
				$form_body .='<div class="dd available" id="widget-admin-full" data-widget-type="available"><h2>Available Widgets</h2>';
				$form_body .='<ol class="dd-list" id="widgets-available">';
					$sql = "select * from widgets";
					$rtn=mysql_query($sql);
					while($ntdata=mysql_fetch_array($rtn)){
						$form_body .= '<span id="available-widget-place'.$ntdata['recordkey'].'"></span>';
	
						if (!array_key_exists($ntdata['recordkey'], $widgetNumPlaces) || $widgetNumPlaces[$ntdata['recordkey']] < 3) {
							$widgetNumPlaces[$ntdata['recordkey']] = 0;
							$form_body .= "<li class='dd-item widget".$ntdata['recordkey']."' data-place='available' data-recordkey='".$ntdata['recordkey']."'><span class='dd-handle'>".$ntdata[title]."</span></li>";
						}
					}
				$form_body .='</ol>';
				$form_body .='</div>';
			//end of available widgets	
			
			$form_body .='<div id="mobile-sidebar-widget-wrapper">';
			//sidebar widgets
				$form_body .='<div class="dd sidebar" id="widget-admin-left" data-widget-type="sidebar"><h2>Sidebar Widgets Here</h2>';
				$sql = "SELECT 
							w.*,
							pw.widgetid
						FROM widgets w
							LEFT JOIN pageWidgets pw ON w.recordkey = pw.widgetid 
						WHERE
							pw.pageid = '".$editpage."' &&
							pw.sidebar = '1'
						ORDER BY pw.sequence";
					$rtn=mysql_query($sql) or die(mysql_error());
					//$form_body .="qry=".$sql;
					if (mysql_num_rows($rtn) > 0) {
						$form_body .= "<ol class='dd-list' id='widgets-sidebar'>";
						while($ntdata=mysql_fetch_array($rtn)){
							$form_body .= "<li class='dd-item widget".$ntdata['recordkey']."' data-place='sidebar' data-recordkey='".$ntdata['recordkey']."'><span class='dd-handle'>".$ntdata[title]."
							</span>
							<span class='remove-icon'><a href='#'><img src='images/delete.png' alt='Remove Widget' title='Remove Widget'></a></span>
							</li>";
	
							if (!array_key_exists($ntdata['recordkey'], $widgetNumPlaces)) {
								$widgetNumPlaces[$ntdata['recordkey']] = 0;
							}
							$widgetNumPlaces[$ntdata['recordkey']]++;
						}
						$form_body .= '</ol>';
					} else {
						$form_body .= '<div class="dd-empty"></div>';
					}
				$form_body .='</div>';
			//set flag to hide mobile widget section if mobile not enabled 
			if ($_SESSION['enable_mobile']!=1){$display = " style='display:none;'";} else {$display="";}
			//mobile widgets	
				$form_body .='<div class="dd mobile" id="widget-admin-left" data-widget-type="mobile" '.$display.'><h2>Mobile Widgets Here</h2>';
				$sql = "SELECT 
							w.*,
							pw.widgetid
						FROM widgets w
							LEFT JOIN pageWidgets pw ON w.recordkey = pw.widgetid 
						WHERE
							pw.pageid = '".$editpage."' &&
							pw.mobile = '1'
						ORDER BY pw.sequence";
					$rtn=mysql_query($sql) or die(mysql_error());
					//$form_body .="qry=".$sql;
					if (mysql_num_rows($rtn) > 0) {
						$form_body .= "<ol class='dd-list' id='widgets-mob'>";
						while($ntdata=mysql_fetch_array($rtn)){
							$form_body .= "<li class='dd-item widget".$ntdata['recordkey']."' data-place='mobile' data-recordkey='".$ntdata['recordkey']."'><span class='dd-handle'>".$ntdata[title]."
							</span>
							<span class='remove-icon'><a href='#'><img src='images/delete.png' alt='Remove Widget' title='Remove Widget'></a></span>
							</li>";
	
							if (!array_key_exists($ntdata['recordkey'], $widgetNumPlaces)) {
								$widgetNumPlaces[$ntdata['recordkey']] = 0;
							}
							$widgetNumPlaces[$ntdata['recordkey']]++;
						}
						$form_body .= '</ol>';
					} else {
						$form_body .= '<div class="dd-empty"></div>';
					}
				$form_body .='</div>';
				//}
			$form_body .='</div>'; //end mobile-sidebar-widget-wrapper
			
			$form_body .='<div id="top-bottom-widget-wrapper">';
			//top widgets	
				$form_body .='<div class="dd top" id="widget-admin-right_top" data-widget-type="top"><h2>Top Widgets Here</h2>';
					$sql = "SELECT 
							w.*,
							pw.widgetid
						FROM widgets w
							LEFT JOIN pageWidgets pw ON w.recordkey = pw.widgetid 
						WHERE
							pw.pageid = '".$editpage."' &&
							pw.top = '1'
						ORDER BY pw.sequence";
					$rtn=mysql_query($sql);
					//$form_body .="qry=".$sql;
					if (mysql_num_rows($rtn) > 0) {
						$form_body .= "<ol class='dd-list' id='widgets-top'>";
						while($ntdata=mysql_fetch_array($rtn)){
							$form_body .= "<li class='dd-item widget".$ntdata['recordkey']."' data-place='top' data-recordkey='".$ntdata['recordkey']."'><span class='dd-handle'>".$ntdata[title]."
							</span>
							<span class='remove-icon'><a href='#'><img src='images/delete.png' alt='Remove Widget' title='Remove Widget'></a></span>
							</li>";
	
							if (!array_key_exists($ntdata['recordkey'], $widgetNumPlaces)) {
								$widgetNumPlaces[$ntdata['recordkey']] = 0;
							}
							$widgetNumPlaces[$ntdata['recordkey']]++;
						}
						$form_body .= "</ol>";
					} else {
						$form_body .= '<div class="dd-empty"></div>';
					}
				$form_body .='</div>';
			//bottom widgets	
				$form_body .='<div class="dd bottom" id="widget-admin-right_bottom" data-widget-type="bottom"><h2>Bottom Widgets Here</h2>';
					$sql = "SELECT 
							w.*,
							pw.widgetid
						FROM widgets w
							LEFT JOIN pageWidgets pw ON w.recordkey = pw.widgetid 
						WHERE
							pw.pageid = '".$editpage."' &&
							pw.bottom = '1'
						ORDER BY pw.sequence";
					$rtn=mysql_query($sql);
					//$form_body .="qry=".$sql;
					if (mysql_num_rows($rtn) > 0) {
						$form_body .= "<ol class='dd-list' id='widgets-bottom'>";
						while($ntdata=mysql_fetch_array($rtn)){
							$form_body .= "<li class='dd-item widget".$ntdata['recordkey']."' data-place='bottom' data-recordkey='".$ntdata['recordkey']."'><span class='dd-handle'>".$ntdata[title]."
							</span>
							<span class='remove-icon'><a href='#'><img src='images/delete.png' alt='Remove Widget' title='Remove Widget'></a></span>
							</li>";
	
							if (!array_key_exists($ntdata['recordkey'], $widgetNumPlaces)) {
								$widgetNumPlaces[$ntdata['recordkey']] = 0;
							}
							$widgetNumPlaces[$ntdata['recordkey']]++;
						}
						$form_body .= "</ol>";
					} else {
						$form_body .= '<div class="dd-empty"></div>';
					}
				$form_body .='</div>';
			$form_body .='</div>'; //end top-bottom-widget-wrapper
			
		//END WIDGET SELECTION AREA
		} else {
			$form_body .="<center>To manually choose widgets for this page, select 'Do not copy - Let me choose'.</center>";
		}	
				$form_body .='<div style="clear:both;"></div></div>
				<!--<div align=right><input id="save-button" type="submit" name="save_widgets" value="Save">--></div></form></div></div>
				</li>
				<li>
				<h3>SEO Settings</h3> <div class="acc-section seo-settings-section"><div class="acc-content"><form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $nt[recordKey] . '&section=seo" method="post">
				<div>
				Page title:<br><input type="text" name="seo_title" id="seo_title" size="40" value="' .  $nt[seo_title] . '"><br>
				<span>Characters: <span class=charcount></span></span>
				</div>
				<br>Permalink:<br>';
				$query2 = "Select webURL, lennox_api_key from storePrefs";
				$rt2=mysql_query($query2);
				while($nt2=mysql_fetch_array($rt2)){
					$webaddress= $nt2[webURL];
					$lennox_api_key= $nt2[lennox_api_key];
				}
				
				$form_body .=$webaddress.'/<input type="text" name="seo_permalink" size="40" value="' .  $nt[permalink] . '"><input type="hidden" name="old_permalink" value="'.$nt[permalink].'"><br>
				<i>Copy link: <font color="blue">'.$webaddress.'/'.$nt[permalink].'</font></i><br><br>
				<div>Page keywords:<br><textarea name="seo_keywords" id="seo_keywords" rows=5 style="width:540px;">' . stripslashes($nt[seo_keywords]) . '</textarea><br /><span>Characters: <span class=charcount></span></span>&nbsp;<span>Keywords: <span class=keywordcount></span></span></div><br>
				<div>Page description:<br><textarea name="seo_description" id="seo_description" rows=5 style="width:540px;">' . stripslashes($nt[seo_description]) . '</textarea><br /><span>Characters: <span class=charcount></span></span></div>
				<div align=right><input id="save-button" type="submit" name="save_seo" value="Save"></div></form></div></div></li>
				<li><h3>Insert HTML</h3> <div class="acc-section"><div class="acc-content"><form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $nt[recordKey] . '&section=html" method="post">';
				
				$form_body .='<div id="html-main-content"><font color="red"><i>This section to be used for HTML code that doesn\'t work in the editor window above.</i></font>
				<textarea name="block2"  id="blockc" rows=10 style="width:580px;">' . stripslashes($nt[block2]) . '</textarea>
				</div>';
				$form_body .='<div align=right><input id="save-button" type="submit" name="save_html" value="Save"></div></form></div></div>
				</li>
				<li>
				<h3>CSS/Style</h3> <div class="acc-section"><div class="acc-content"><form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $nt[recordKey] . '&section=style" method="post">';
				$form_body .='Custom Page CSS:<br><textarea name="custom_css"  id="custom_css" rows=5 style="width:540px;">' . stripslashes($nt[custom_css]) . '</textarea>
				<br><br>
				Page Layout: <select name="page_layout"><option value="">Default</option>
				<option value="1"';
				if($nt[page_layout]=='1'){$form_body.=" selected=\'selected\'";}
				$form_body .='>Layout 1</option>
				<option value="2"';
				if($nt[page_layout]=='2'){$form_body.=" selected=\'selected\'";}
				$form_body .='>Layout 2</option>
				</select>';
	
				$form_body .='<br>
				<div align=right><input id="save-button" type="submit" name="save_style" value="Save"></div></form></div></div></li>';
				if($lennox_api_key>""){
					$form_body .='<li>
					<h3>Lennox API</h3> <div class="acc-section"><div class="acc-content">
					<form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $nt[recordKey] . '&section=lennox" method="post">
		             Include API for: <select name="lennox_api"><option value="">None</option>';
					//echo "API: $nt[lennox_api]<br>";
					$form_body .='<option value="1"';
					if($nt[lennox_api]=='1'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Air Conditioners</option>';
					
					$form_body .='<option value="2"';
					if($nt[lennox_api]=='2'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Furnaces</option>';
					
					$form_body .='<option value="3"';
					if($nt[lennox_api]=='3'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Indoor Air Quality Systems</option>';
					
					$form_body .='<option value="4"';
					if($nt[lennox_api]=='4'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Packaged Units</option>';
					
					$form_body .='<option value="5"';
					if($nt[lennox_api]=='5'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Comfort Controls</option>';
					
					$form_body .='<option value="6"';
					if($nt[lennox_api]=='6'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Heat Pumps</option>';
					
					$form_body .='<option value="7"';
					if($nt[lennox_api]=='7'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Boilers</option>';
					
					$form_body .='<option value="8"';
					if($nt[lennox_api]=='8'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Air Handlers</option>';
					
					$form_body .='<option value="9"';
					if($nt[lennox_api]=='9'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Garage Heaters</option>';
					
					$form_body .='<option value="11"';
					if($nt[lennox_api]=='11'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Solar Ready</option>';
					
					$form_body .='<option value="12"';
					if($nt[lennox_api]=='12'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Mini-Split Systems</option>';
					
					$form_body .='<option value="99"';
					if($nt[lennox_api]=='99'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Energy Calculator</option>';
					
					$form_body .='<option value="999"';
					if($nt[lennox_api]=='999'){$form_body.=" selected=\'selected\'";}
					$form_body .='>Special Offers</option>';
					
					$form_body .='</select>';
		
					$form_body .='<br>
					<div align=right><input id="save-button" type="submit" name="save_style" value="Save"></div></form></div></div></li>';
				}
				
				$form_body .='</ul></div>';
				
		//}
		echo $form_body;
		
	
	 echo '<tr><td colspan=2>';
	
	 
	}
	echo '</table>';
			
	
	
		echo '<br></div>';

		$menuSelect = array();
		$menuSelectquery = "SELECT * from menu_master";
		$menuSelectResult = mysql_query($menuSelectquery);
		while($menuData=mysql_fetch_array($menuSelectResult)){	
			if($menuData['menu_name']!='Timed menu rotation'){
				$menuSelect[$menuData['recordkey']] = $menuData['menu_name'];
			}
		}

		echo '<div id="timeSettingPopup" class="toPopDiv ">
					<div id="close_btn"></div>
					<div class="close close_Popup"></div>
					<div id="popup_content">
						<form action="'. $_SERVER['PHP_SELF'].'?a=select&page='.$globalPageRecordKey.'" method="POST" >
						<input type="hidden" value="'.$globalMenuId.'" name="menu_id">
						<input type="hidden" value="'.$globalPageId.'" name="page_id">
							<table border="0" id="time-table" cellpadding=15 cellspacing=0 style="text-align:center">
								';
								$query = "SELECT * FROM `menu_time_setting` WHERE menu_page_id='".$globalMenuId."' ORDER BY `id`";
								$result = mysql_query($query);
								if(mysql_num_rows($result)>0){
											echo '<tr>
													<th>Menu To Display</th>
													<th>Start Time</th>	
													<th> </th>			
												</tr>';
									 $idCount=1;
									 while($data=mysql_fetch_array($result)){
										echo '<tr>
											<td>
												<select name="menu[]">';
												foreach ($menuSelect as $key => $value) {
													$selected='';
													if($data[menu_name]==$key){ $selected='selected="selected"';}
													echo "<option ".$selected." value='".$key."'>".$value."</option>";
												}												
											echo '</select>
											</td>
											<td>
												<input  size="6" type="text" class="timepicker" value="'.$data[start_time].'" name="start_time[]" onkeypress="return false;" />
											</td>
											<td>
											 <img onclick="$(this).parents(\'tr\').remove(); return false;" class="removeField" src="../images/remove-icon.png">
											</td>
										</tr>';
										$idCount++;
									}
								}else{
								echo '<tr>
									<th>Menu To Display</th>
									<th>Start Time</th>
								</tr>
								<tr>
									<td>
										<select name="menu[]">';

										foreach ($menuSelect as $key => $value) {
											echo "<option value='".$key."'>".$value."</option>";
										}

								echo '</select>
									</td>
									<td>
										<input size="6" type="text" class="timepicker" name="start_time[]" onkeypress="return false;"/>		
									</td>
								</tr>';
							}
							echo '</table>
							<input type="submit" class="save_time_btn" value="SAVE" name="save-menu-time">
						</form>
						<button id="add_more_btn">+ ADD MORE</button>
					</div>
				  </div>';
		
	?>
	
	<form id="preview-form" action="/preview.php" method="post" target="desktop_preview_iframe">
		<input id="block1_preview" type="hidden" name="block1" value="" />
	</form>
	<!--<ul class="acc" id="acc">
			<li><h3>Add a New Page</h3> <div class="acc-section"><div class="acc-content">
			 </div></div></li>
			 </ul>-->
	<script type="text/javascript" >
	CKEDITOR.replace( 'block1',
	{	
		extraAllowedContent: '*[allowfullscreen]',
		filebrowserBrowseUrl : 'ckfinder/ckfinder.html',
		filebrowserImageBrowseUrl : 'ckfinder/ckfinder.html?type=Images',
		filebrowserFlashBrowseUrl : 'ckfinder/ckfinder.html?type=Flash',
		filebrowserUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
		filebrowserImageUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
		filebrowserFlashUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash',
		toolbarGroups: [
			{ name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
			{ name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
			{ name: 'links'},
			{ name: 'insert'},
			{ name: 'others' },
			'/',
			{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
			{ name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align'] },
			{ name: 'styles' },
			{ name: 'colors' },
			{ name: 'mode' },
			{ name: 'tools' },	
		],
	    uiColor: '#499ED7'
	});
	
	</script>
	<!-- /*extraPlugins: 'image2','audio', 'dialogui','lineutils','widget','clipboard','dialog',*/ 
		, items: [ 'audio' ] 
		-->
	
	<!-- Default toolbar config
	toolbarGroups: [
		{ name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
	    { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
	    { name: 'links' },
	    { name: 'insert' },
	    { name: 'forms' },
	    { name: 'tools' },
	    { name: 'document',    groups: [ 'mode', 'document', 'doctools' ] },
	    { name: 'others' },
	    '/',
	    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
	    { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align' ] },
	    { name: 'styles' },
	    { name: 'colors' },
	    { name: 'about' }
		]
	
	-->
	
	
	
	<script type="text/javascript" src="includes/tinyaccordion/script.js"></script>
	<script type="text/javascript" src="js/counter.js"></script>
	
	<script type="text/javascript">
	numtopwidgets = '<?php echo (isset($top_widgets)) ? $top_widgets : 100; ?>';
	numbottomwidgets = '<?php echo (isset($bottom_widgets)) ? $bottom_widgets : 100; ?>';
	numsidebarwidgets = '<?php echo (isset($sidebar_widgets)) ? $sidebar_widgets : 100; ?>';
	$(document).ready(function() {
		$('.dd').nestable({
			maxDepth: 1,
			group: 1
		}).on('done', function(e, listItem, parentItem) {
			updateWidgets(listItem, parentItem);
		});
	
		$(document).on('click', '.remove-icon', function(e) {
			listItem = $(this).parent('li');
			recordkey = listItem.data('recordkey');
	
			if (
				$('.dd.available .widget'+recordkey).length == 0
			) {
				console.log('moving: '+'#available-widget-place'+recordkey);
				listItem.data('place', 'available');
				if ($('.dd.available .dd-list').length == 0) {
					$('.dd.available').append('<ol class="dd-list"></ol>');
				}
				$('.dd.available .dd-list').append(listItem);
			} else {
				console.log('removing');
				listItem.remove();
			}
	
			checkWidgetXButtons();
			checkForEmptyAreas();
	
			saveWidgets();
	
			e.preventDefault();
		});
	
		$('#preview-desktop-site').click(function() {
			var pageID = $(this).data('page-id');
			$('#preview-form').attr('action', '/core.php?preview&page='+pageID);
			$('#preview-form').attr('target', 'desktop_preview_iframe');
			var content = CKEDITOR.instances.block1.getData();
			$('#block1_preview').val(content);
			$('#preview-form').submit();
		});
	
		$('#preview-mobile-site').click(function() {
			var pageID = $(this).data('page-id');
			$('#preview-form').attr('action', '/core-m.php?preview&page='+pageID);
			$('#preview-form').attr('target', 'mobile_preview_iframe');
			var content = CKEDITOR.instances.block1.getData();
			$('#block1_preview').val(content);
			$('#preview-form').submit();
		});
	});
	
	function checkForEmptyAreas() {
		if ($('.dd.sidebar .dd-empty').length > 0 && $('.dd.sidebar .dd-item').length > 0) {
			$('.dd.sidebar .dd-empty').remove();
		} else if ($('.dd.sidebar .dd-empty').length > 1) {
			$('.dd.sidebar .dd-empty').remove();
			$('.dd.sidebar').append('<div class="dd-empty"></div>');
		} else if ($('.dd.sidebar .dd-item').length == 0 && $('.dd.sidebar .dd-empty').length == 0) {
			$('.dd.sidebar .dd-list').remove();
			$('.dd.sidebar').append('<div class="dd-empty"></div>');
		}
		
		if ($('.dd.top .dd-empty').length > 0 && $('.dd.top .dd-item').length > 0) {
			$('.dd.top .dd-empty').remove();
		} else if ($('.dd.top .dd-empty').length > 1) {
			$('.dd.top .dd-empty').remove();
			$('.dd.top').append('<div class="dd-empty"></div>');
		} else if ($('.dd.top .dd-item').length == 0 && $('.dd.top .dd-empty').length == 0) {
			$('.dd.top .dd-list').remove();
			$('.dd.top').append('<div class="dd-empty"></div>');
		}
	
		if ($('.dd.bottom .dd-empty').length > 0 && $('.dd.bottom .dd-item').length > 0) {
			$('.dd.bottom .dd-empty').remove();
		} else if ($('.dd.bottom .dd-empty').length > 1) {
			$('.dd.bottom .dd-empty').remove();
			$('.dd.bottom').append('<div class="dd-empty"></div>');
		} else if ($('.dd.bottom .dd-item').length == 0 && $('.dd.bottom .dd-empty').length == 0) {
			$('.dd.bottom .dd-list').remove();
			$('.dd.bottom').append('<div class="dd-empty"></div>');
		}
		
		if ($('.dd.mobile .dd-empty').length > 0 && $('.dd.mobile .dd-item').length > 0) {
			$('.dd.mobile .dd-empty').remove();
		} else if ($('.dd.mobile .dd-empty').length > 1) {
			$('.dd.mobile .dd-empty').remove();
			$('.dd.mobile').append('<div class="dd-empty"></div>');
		} else if ($('.dd.mobile .dd-item').length == 0 && $('.dd.mobile .dd-empty').length == 0) {
			$('.dd.mobile .dd-list').remove();
			$('.dd.mobile').append('<div class="dd-empty"></div>');
		}
	
		if ($('.dd.available .dd-empty').length > 0 && $('.dd.available .dd-item').length > 0) {
			$('.dd.available .dd-empty').remove();
		} else if ($('.dd.available .dd-empty').length > 1) {
			$('.dd.available .dd-empty').remove();
			$('.dd.available').append('<div class="dd-empty"></div>');
		} else if ($('.dd.available .dd-item').length == 0 && $('.dd.available .dd-empty').length == 0) {
			$('.dd.available .dd-list').remove();
			$('.dd.available').append('<div class="dd-empty"></div>');
		}
	}
	
	function updateWidgets(listItem, parentItem) {
		oldParentType = listItem.data('place');
		newParentType = listItem.closest('.dd').data('widget-type');
		recordkey = listItem.data('recordkey');
		// check if a new widget should be created for the available area (only if the widget is not in all three widget areas)
		if (
			$('.dd.available .widget'+recordkey).length == 0 && 
			( $('.dd.sidebar .widget'+recordkey).length == 0 ||
			$('.dd.top .widget'+recordkey).length == 0 ||
			$('.dd.mobile .widget'+recordkey).length == 0 ||
			$('.dd.bottom .widget'+recordkey).length == 0 )
		) {
			newItem = listItem.clone();
			newItem.data('place', 'available');
			if ($('.dd.available .dd-list').length == 0) {
				$('.dd.available').append('<ol class="dd-list"></ol>');
			}
			$('.dd.available .dd-list').append(newItem);
		}
	
		if (oldParentType != 'available' && newParentType == 'available') {
			if (
				$('.dd.available .widget'+recordkey).length > 1
			) {
				listItem.remove();
			}
		}
	
		if (newParentType != 'available') {
			// check if more than allowed
			var numAllowed = window['num'+newParentType+'widgets'];
			if (parseInt($('.dd.'+newParentType+' li').length) > numAllowed) {
				listItem.remove();
			}
			// check if this widget already exists.
			else if ($('.dd.'+newParentType+' .widget'+recordkey).length > 1) {
				// move back to old parent
				// $('#widgets-'+newParentType).append(listItem);
				listItem.remove();
			}
		} else {
			listItem.data('place', newParentType);
		}
	
		checkWidgetXButtons();
		checkForEmptyAreas();
	
		saveWidgets();
	}

	//Code for menu timed option
       var menu_id = $( "#menu_name option:selected" ).val();
       if(menu_id == 16){
       	 $('.time-setting').show();
       }

		$('.Timed').click(function() {
			$('.time-setting').show();
		});
		$('.Dinner').click(function() {
			$('.time-setting').hide();
		});
		$('.Breakfast').click(function() {
			$('.time-setting').hide();
		});
		$('.Lunch').click(function() {
			$('.time-setting').hide();
		});
		
		$('.time-setting').click(function() {
			$('#timeSettingPopup').fadeIn( "slow", function() {
			});
		});

		$('input.timepicker').timepicker({ 'showDuration': true, 'step': 15, 'timeFormat': 'H:i' });

		$('#close_btn').click(function() {
			$('#timeSettingPopup').hide();
		});

		$('#add_more_btn').click(function() {

		var rowCount = $('#time-table tr').length;
		var x = rowCount-1;
		var endHour = $( "#end-h-box_"+x+" option:selected" ).val();
		var endMin = $( "#end-m-box_"+x+" option:selected" ).val();
		var endMod = $( "#end-mod option:selected" ).val();
		var i=0;
		var html = "<tr><td><select name='menu[]'>";
			<?php
				foreach ($menuSelect as $key => $value) { ?>
			html +="<option value='<?php echo $key; ?>' ><?php echo $value; ?></option>";
			<?php } ?>
			html +="</td><td><input size='6' type='text' class='timepicker' name='start_time[]' onkeypress='return false;' /></td><td><img onclick='$(this).parent().parent().remove(); return false;' class='removeField' src='../images/remove-icon.png'></td></tr>";
	$('#time-table').append(html);
		$('input.timepicker').timepicker({ 'showDuration': true, 'step': 15, 'timeFormat': 'H:i' });
	});

	function saveMenuId(){
		var pageId =$("#pageIdBox").val();
		var menuId = $( "#menu_name option:selected" ).val();
		$.ajax({
			type: 'POST',
			url: 'save_cat_order.php',
			data: {'pageId':pageId , 'menuId':menuId}
		});
	}
	
	function checkWidgetXButtons() {
		// add X button if not there
		$('.dd.sidebar li, .dd.top li, .dd.bottom li, .dd.mobile li').each(function() {
			if($(this).children('span.remove-icon').length == 0) {
				$(this).append('<span class="remove-icon"><a href="#"><img src="images/delete.png" alt="Remove Widget" title="Remove Widget"></a></span>');
			}
		});
	
		// remove X button for available widgets
		$('#widgets-available li').each(function() {
			if($(this).children('span.remove-icon').length != 0) {
				$(this).children('span.remove-icon').remove();
			}
		});
	}
	
	function saveWidgets() {
		//alert('saveWidgets triggered: ');
		sidebarWidgets = window.JSON.stringify($('.dd.sidebar').nestable('serialize'));
		topWidgets = window.JSON.stringify($('.dd.top').nestable('serialize'));
		bottomWidgets = window.JSON.stringify($('.dd.bottom').nestable('serialize'));
		mobWidgets = window.JSON.stringify($('.dd.mobile').nestable('serialize'));
		
		$.ajax({
			url: 'save_widgets.php',
			type: 'post',
			data: {sidebar: sidebarWidgets,top: topWidgets,bottom: bottomWidgets,mobile: mobWidgets,pageid:'<?php echo $editpage; ?>'}
		});
	}
	
	var expand = <?php
		$sections = array(
			'popup',
			'widgets',
			'seo',
			'html',
			'style'
		);
		if (isset($_GET['section']) && !empty($_GET['section'])) {
			if (in_array($_GET['section'], $sections)) {
				echo array_search($_GET['section'], $sections);
			} else {
				echo '-1';
			}
		} elseif (isset($_GET['a']) && ($_GET['a'] == 'remwidget' || $_GET['a'] == 'addwidget')) {
			echo array_search('widgets', $sections);
		} else {
			echo '-1';
		}


?>;

var parentAccordion=new TINY.accordion.slider("parentAccordion");
parentAccordion.init("acc","h3",1,expand);

// var nestedAccordion=new TINY.accordion.slider("nestedAccordion");
// nestedAccordion.init("nested","h3",1,-1,"acc-selected");

// var nestedAccordion2=new TINY.accordion.slider("nestedAccordion2");
// nestedAccordion2.init("nested2","h3",1,-1,"acc-selected");


//var parentAccordion=new TINY.accordion.slider("parentAccordion");
//parentAccordion.init("acc","h3",0);

//var nestedAccordion=new TINY.accordion.slider("nestedAccordion");
//nestedAccordion.init("nested","h3",1,-1,"acc-selected");
//nestedAccordion.init("nested","h3",1,-1,"acc-selected");

</script>

<?php

	}

?>
