<?php
include "../includes/session.php";
include "../includes/config.php";
include "../includes/function.php";
$temperory_location="http://192.168.0.11/sitebuilder/workarea/tempsites";
$real_location="http://192.168.0.11/sitebuilder/workarea/sites";
$script_string="<script> ";
	//Functions used in various sections

		//function createPage($pageName,$templateId,$pageType,$editing) {} used to create a page in work area
		//$pageName 	==> name of the page created
		//$templateId 	==>	Id of the template 
		//$tmpSiteId	==>	Id of the temperory site the file has to be copied to
		//$pageType		==>	'1' indicates index.htm, '2' indicates a sub.htm.
		//$editing		==>	'true' indicates we are editing a published site(workarea/sites/siteid), 
		//					'false' indicates this site has not yet published (workarea/tempsites/tempsiteid)
		//$firstTime 	==>	'true' indicates page is being created for the first time so copy images
		//					'false' indicates page is being created for the nth time so do not copy images
		function createPage($pageName,$templateid,$tmpsiteid,$pageType,$editing,$firstTime=false) {
			//physical location of the template will be /templates/template_id/
			//2 pages will be present 'index.htm' and 'sub.htm'
			//a folder called 'images' and 'watermarkimages' will be present in this folder.
			$workLocation = "";
			$pageToCopy = "";
			if($pageType == 1) {
				$pageToCopy = "index.htm";
			}
			else {
				$pageToCopy = "sub.htm";
			}
			if($editing == true) {
				$workLocation = "../workarea/sites/$tmpsiteid";
			   @copy("../templates/$templateid/$pageToCopy","../sites/$tmpsiteid/$pageName");
			   @chmod("../sites/$tmpsiteid/$pageName",0777);
			}
			else {
				$workLocation = "../workarea/tempsites/$tmpsiteid";
			}
			if($firstTime == true)	{
				copydirr("../templates/".$templateid."/watermarkimages",$workLocation . "/images",0777,false);
 			    copy("../templates/$templateid/style.css",$workLocation . "/style.css");
			    chmod($workLocation . "/style.css",0755);
		    }
		    copy("../templates/$templateid/$pageToCopy",$workLocation . "/$pageName");
   		    chmod($workLocation . "/$pageName",0777);
		    return $workLocation . "/$pageName";
		}
	
		
		//function SaveFile($fileToSave)
		//$fileToSave ==>	the full path of the file to be saved
		//It saves the data that comes in the form Post EditorHTM,EditorHTM2,EditorHTM3,EditorHTM4,
		//EditorHTM5 variables to the location specified in $fileToSave.   
		function SaveFile($fileToSave,$search_string) {
			$fp = fopen($fileToSave,"w");
			fwrite($fp,$_POST["EditorHTM"]);	
			fwrite($fp,$_POST["EditorHTM2"]);	
			fwrite($fp,$_POST["EditorHTM3"]);	
			fwrite($fp,$_POST["EditorHTM4"]);	
			fwrite($fp,$_POST["EditorHTM5"]);	
			fclose($fp);
			file_replace ($search_string, ".", $fileToSave);
		}
		
		function file_replace ($search, $replace, $filename) {
		   if (file_exists($filename)) {
			   $cnt = file_get_contents($filename);
				   $cnt = preg_replace($search,$replace,$cnt);
				   fwrite(fopen($filename,"w"),$cnt);  //here file_put_contents() cannot be used since it is available only on php5 
			   		return true;
		   }
		   return false;
	   }
		
		//function to save changes to resource file
		//function SaveResource($resource_location,$var_deletedimages,$var_newimages)
		//$resource_location ==>	the location of the resource.txt file that has to be modified
		//$var_deletedimages ==>	'|' character seperated image file names that has to be deleted from the resource file
		//$var_newimages 	 ==>	'|' character seperated image file names that has to be added to the resource file	
		//the resource file is read into an array using file($resourcelocation)
		//for each name in $deletedimages we delete a name from the populated array and then finally overwrite the new array into resource.txt
		//Also the contents in the $newimages is written to resourcelocation 
		$resource_save_flag = false;
		function SaveResource($resource_location,$var_deletedimages,$var_newimages,$userid) {
			//
			global $resource_save_flag;
			if($resource_save_flag == false) {
				if($_SESSION["session_checkid"] >= $_POST["checkid"]) {
					return;
				}
				else {
					$_SESSION["session_checkid"]=$_POST["checkid"];
					$resource_save_flag = true;
				}
			}
			
			if(is_file($resource_location)) {
			$content_arr = file($resource_location);
			if(strlen($var_deletedimages) > 0) {	// IF Delete images > 0
				$deleted_arr = explode('|',$var_deletedimages);
				$deleted_count = count($deleted_arr);
				for($i=0;$i < $deleted_count;$i++) {	// FOR LOOP - I
						$temp_string=$deleted_arr[$i];
						switch(substr($temp_string,0,2)) {
							case "ug":
									$temp_string = "../usergallery/$userid/images/" . $temp_string;
									break;
							case "sg":
									$temp_string = "../systemgallery/" . $temp_string;
									break;
							case "sl":
									$temp_string = "../samplelogos/" . $temp_string;
									break;
							default:
									continue;											
						}
					$temp_count = 0;	
					foreach($content_arr as $lines) {	// FOR LOOP - II
						if(strcmp($temp_string,rtrim($lines,"\n")) == 0) {
							$content_arr[$temp_count] = "";
							break;
						}
						$temp_count++;
					}		// END FOR LOOP - II	
				}			// END FOR LOOP - I
			}		// END IF Delete images > 0
			}
			$fwriter=fopen($resource_location,"w");
			if(count($content_arr) > 0) {
				foreach($content_arr as $lines) {	// FOR LOOP 
					if($lines != "") {
						fputs($fwriter,$lines);
					}
				}
			}
			if(strlen($var_newimages) > 0) {	// IF New images > 0
				$new_arr = explode('|',$var_newimages);
				$new_count = count($new_arr);
				for($i=0;$i < $new_count;$i++) {	// FOR LOOP - I
					$temp_string=$new_arr[$i];
					switch(substr($temp_string,0,2)) {
						case "ug":
								$temp_string = "../usergallery/$userid/images/" . $temp_string . "\n";
								break;
						case "sg":
								$temp_string = "../systemgallery/" . $temp_string . "\n";
								break;
						case "sl":
								$temp_string = "../samplelogos/" . $temp_string . "\n";
								break;
						default:
								continue;											
					}
					fputs($fwriter,$temp_string);
				}
			}	// END IF New images > 0
			fclose($fwriter);
		}
		
		
		//function removePage($pageName,$templateid,$tmpsiteid,$pageType,$editing) {
		//$pageName		==>	name of the page to be deleted
		//$tmpsiteid	==>	temp site id
		//$editing		==>	'true' indicates we are removing a page while editing a published site, hence use 'sites' folder
		//					'false' indicates  we are removing a page while creating a new site, hence use 'tempsites' folder
		function removePage($pageName,$tmpsiteid,$editing) {
			$workLocation = "";
			if($editing == true) {
				$workLocation = "../workarea/sites/$tmpsiteid/$pageName";
				if(is_file("../sites/$tmpsiteid/$pageName")) {
	    	       unlink("../sites/$tmpsiteid/$pageName");
				}
			}
			else {
				$workLocation = "../workarea/tempsites/$tmpsiteid/$pageName";
			}
			if (is_file($workLocation)) {
    	       unlink($workLocation);
	       }
		}		
		
		//function setupEditSite($tmpsiteid,$templateid)
		function setupEditSite($tmpsiteid,$templateid) {
			$pageToCopy = "";
			$workLocation = "../workarea/sites/$tmpsiteid";
			if(!is_dir($workLocation)){
				mkdir($workLocation,0777);
				
			}				
			if(!is_dir($workLocation . "/images")){
				mkdir($workLocation . "/images",0777);
				
			}				

			copydirr("../templates/".$templateid."/images",$workLocation . "/images",0777,false);
			copydirr("../sites/".$tmpsiteid,$workLocation,0777,false);
			if(is_file($workLocation . "/resource.txt")) {
				$content_arr = file($workLocation . "/resource.txt");
				foreach($content_arr as $lines) {
					$file_name=rtrim($lines,"\n");
					@copy($file_name, $workLocation . "/images/" . basename($file_name));
					//echo($file_name . "<br>" . $workLocation . "/images/" . basename($file_name));
				}
			}
			$var_presentpage="";
			$sql = "Select * from tbl_site_pages where nsite_id='" . $tmpsiteid . "'";
			$result = mysql_query($sql) or die(mysql_error());
			if(mysql_num_rows($result) > 0)  {
				$row = mysql_fetch_array($result);
				$var_presentpage=$row["vpage_name"];	
			}
			return $var_presentpage;
		}
		
		//function isValidRequest($tmpsiteid,$templateid,$userid,$var_type)
		function isValidRequest($tmpsiteid,$templateid,$userid,$var_type,$init_flag=false) {
			if($init_flag == true) {
				$var_insert_field="";
			}
			else {
				$var_insert_field=" AND ntemplate_id='" . addslashes($templateid) . "' ";
			}
			if($var_type == "new") {
				$sql = "Select ntempsite_id from tbl_tempsite_mast where ntempsite_id='" . addslashes($tmpsiteid) . "' 
				" . $var_insert_field . " AND nuser_id='" . addslashes($userid) . "'";
			}	
			else {
				$sql = "Select nsite_id from tbl_site_mast where nsite_id='" . addslashes($tmpsiteid) . "' 
				" . $var_insert_field . " AND nuser_id='" . addslashes($userid) . "'";
			}
			$result = mysql_query($sql) or die(mysql_error());
			if(mysql_num_rows($result) > 0) {
				return true;
			}
			else {
				return false;
			}
		}
	//End functions
	
	
	//When this page gets loaded for the first time as request comes from template selection for a non-published site
/*		if($_SESSION["session_checkid"] == "") {
			$_SESSION["session_checkid"] = 1;
		}*/
		
		if($_GET["actiontype"] == "editsite") {	//edit the site previously created 
			if($_GET["type"] == "new") {		// edit a non published site
				$var_type=$_GET["type"];
				$var_actionin = $_GET["actiontype"];			//assigned to a hidden variable(actionin) 	
				$templateid=addslashes($_GET['templateid']);
				$_SESSION['session_currenttempsiteid'] = $_GET["tempsiteid"];

				$tmpsiteid=$_SESSION['session_currenttempsiteid'];
				$userid=$_SESSION["session_userid"];
 			    $_SESSION['session_currenttemplateid']=$templateid;
				
				if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
				}

				$sql = "Select * from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "'";	
				$result = mysql_query($sql) or die(mysql_error());
				if(mysql_num_rows($result) <= 0) {
					$sql = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
							Values('','" . $_SESSION['session_currenttempsiteid']  . "',
							'index.htm','','htm','advanced')";
					mysql_query($sql) or die(mysql_error());		
					$var_presentpage="index.htm";
					$var_pageurl=createPage("index.htm",$templateid,$tmpsiteid,1,false);
				}
				else {
					$row = mysql_fetch_array($result);
					$var_presentpage=$row["vpage_name"];
					$var_pageurl="../workarea/tempsites/$tmpsiteid/$var_presentpage";
				}
			}	//end if $_GET["type"] == "new"			
			elseif($_GET["type"] == "edit") {	//edit a published site
				$var_type=$_GET["type"];
				$var_actionin = $_GET["actiontype"];			//assigned to a hidden variable(actionin) 	
				$templateid=addslashes($_GET['templateid']);
				$_SESSION['session_currenttempsiteid'] = $_GET["tempsiteid"];
				$tmpsiteid=$_SESSION['session_currenttempsiteid'];
				$userid=$_SESSION["session_userid"];
 			    $_SESSION['session_currenttemplateid']=$templateid;
				
				if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
				}
				$var_presentpage=setupEditSite($tmpsiteid,$templateid);
				$var_pageurl="../workarea/sites/$tmpsiteid/$var_presentpage";
			}// end if $_GET["type"] == edit
		}
		elseif($_GET["actiontype"] == "init") {
			if($_GET["type"] == "new") {  //this page is called for a new site not yet published
				$var_type=$_GET["type"];
				$var_actionin = $_GET["actiontype"];			//assigned to a hidden variable(actionin) 	
				$templateid=addslashes($_GET['templateid']);

				$tmpsiteid=$_SESSION['session_currenttempsiteid'];
				$userid=$_SESSION["session_userid"];

				if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type,true)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
				}
					  $_SESSION['session_currenttemplateid']=$templateid;
					  $qry="update tbl_tempsite_mast set ntemplate_id='".$_SESSION['session_currenttemplateid']."',vtype='advanced' where ntempsite_id='".$_SESSION['session_currenttempsiteid']."'";
					  mysql_query($qry);
					  //fetch template logo,caption,company
					  /*$qry= "select * from tbl_template_mast where ntemplate_mast='".$_SESSION['session_currenttemplateid']."'";
					  $exc=mysql_query($qry);
					  $row=mysql_fetch_array($exc);
					  $_SESSION['session_templatelogoband']=$row['vlogo'];
					  $_SESSION['session_templatecompanyband']=$row['vcompany'];
					  $_SESSION['session_templatecaptionband']=$row['vcaption'];
					  $_SESSION['session_templatecolor']=$row['vcolor'];*/

					$sql = "Select * from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='index.htm'";	
					$result = mysql_query($sql) or die(mysql_error());
					if(mysql_num_rows($result) <= 0) {
						$sql = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'index.htm','','htm','advanced')";
						mysql_query($sql) or die(mysql_error());		
					}
	  				$var_presentpage="index.htm";
					$var_pageurl=createPage("index.htm",$templateid,$tmpsiteid,1,false,true);
			}  //End If $_GET["type"] == "new"
		}		//End If $_GET["actiontype"] == "init"
		elseif($_POST["actiontype"] == "save" || $_POST["actiontype"] == "saveandcreate" || $_POST["actiontype"] == "saveandexit") {
	
			$bool_type = false;
			$var_actionin = $_POST["actiontype"];	
			$var_presentpage = $_POST["presentpage"];
			$var_pageurl=$_POST["pageurl"];
			$var_type = $_POST["type"];
			$var_deletedimages=$_POST["deletedimages"];
			$var_newimages=$_POST["newimages"];

			$tmpsiteid=$_SESSION['session_currenttempsiteid']; // reconsider this statement since the session will be different in case of sites
			$userid=$_SESSION["session_userid"];
			
			//these 3 parameters will be passed only if "actiontype" = "saveandcreate" 
			$templateid=$_SESSION['session_currenttemplateid'];
			$var_pagetype=($_POST["pagetype"] == "index")?1:2;
			$var_editpage = $_POST["editpage"];
	
			if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
			}	
				 
			if($var_type == "new") {
				$search_string=$temperory_location . "/$tmpsiteid";
				$fileToSave = "../workarea/tempsites/$tmpsiteid/$var_presentpage";
				$resource_location="../workarea/tempsites/$tmpsiteid/resource.txt";
				$sql_check = "Select * from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";
				$sql_insert = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'" . addslashes($var_editpage) . "','','htm','advanced')";
			}
			elseif($var_type == "edit") {
				$bool_type = true;
				$search_string=$real_location . "/$tmpsiteid";
				$fileToSave = "../workarea/sites/$tmpsiteid/$var_presentpage";
				$resource_location="../workarea/sites/$tmpsiteid/resource.txt";
				$sql_check = "Select * from tbl_site_pages where nsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";
				$sql_insert = "Insert into tbl_site_pages(nsp_id,nsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'" . addslashes($var_editpage) . "','','htm','advanced')";
				//save to original site location
				SaveFile("../sites/$tmpsiteid/$var_presentpage",$search_string);
				SaveResource("../sites/$tmpsiteid/resource.txt",$var_deletedimages,$var_newimages,$userid);
			}
			SaveFile($fileToSave,$search_string);
			SaveResource($resource_location,$var_deletedimages,$var_newimages,$userid);
			if($_POST["actiontype"] == "saveandexit") {
				echo("<script>alert('Page Saved!'); location.href='../usermain.php'; </script>");
				exit();
			}
			$script_string .= " alert(\"Page Saved!\"); 
								global_saved = true; 
								 global_reload = true; ";
			
			// If user selected to create a new page
			if($_POST["actiontype"] == "saveandcreate") {	
				if($templateid !=""){
					$result = mysql_query($sql_check) or die(mysql_error());
					if(mysql_num_rows($result) <= 0) {
						mysql_query($sql_insert) or die(mysql_error());		
					}
	  				$var_presentpage=$var_editpage;
					
					$var_pageurl=createPage($var_editpage,$templateid,$tmpsiteid,$var_pagetype,$bool_type);
				}	
			}	
			//End If user selected to create a new page					 
		}
		elseif($_POST["actiontype"] == "edit" || $_POST["actiontype"] == "saveandedit") {
			$bool_type = false;
			$var_actionin = $_POST["actiontype"];	
			$var_presentpage = $_POST["presentpage"];
			$var_pageurl=$_POST["pageurl"];
			$var_type = $_POST["type"];
			$var_deletedimages=$_POST["deletedimages"];
			$var_newimages=$_POST["newimages"];

			$tmpsiteid=$_SESSION['session_currenttempsiteid']; // reconsider this statement since the session will be different in case of sites
			$userid=$_SESSION["session_userid"];
			$templateid=$_SESSION['session_currenttemplateid'];
		
			$var_editpage=$_POST["editpage"];		// here editpage will contain the id of the page
			
			if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
			}

			if($var_type == "new") {
				//for save
				$search_string=$temperory_location . "/$tmpsiteid";
				$fileToSave = "../workarea/tempsites/$tmpsiteid/$var_presentpage";
				$resource_location="../workarea/tempsites/$tmpsiteid/resource.txt";

				$sql = "Select * from tbl_tempsite_pages where ntempsp_id='" . addslashes($var_editpage) . "'";
				$result = mysql_query($sql) or die(mysql_error());
				if(mysql_num_rows($result)) {
					$row = mysql_fetch_array($result);
					$var_presentpage = $row["vpage_name"];
					$var_pageurl = "../workarea/tempsites/" . $row["ntempsite_id"] . "/$var_presentpage";	
				}
			}
			else {
				//for save
				$bool_type = true;
				$search_string=$real_location . "/$tmpsiteid";
				$fileToSave = "../workarea/sites/$tmpsiteid/$var_presentpage";
				$resource_location="../workarea/sites/$tmpsiteid/resource.txt"; 
				$fileRealLocation = "../sites/$tmpsiteid/$var_presentpage";
				
				$sql = "Select * from tbl_site_pages where nsp_id='" . addslashes($var_editpage) . "'";
				$result = mysql_query($sql) or die(mysql_error());
				if(mysql_num_rows($result)) {
					$row = mysql_fetch_array($result);
					$var_presentpage = $row["vpage_name"];
					$var_pageurl = "../workarea/sites/" . $row["nsite_id"] . "/$var_presentpage";	
				}
			}
			if($_POST["actiontype"] == "saveandedit") {
				//for save
				if($var_type == "edit") {
					SaveFile($fileRealLocation,$search_string);
					SaveResource("../sites/$tmpsiteid/resource.txt",$var_deletedimages,$var_newimages,$userid);
				}
				SaveFile($fileToSave,$search_string);
				SaveResource($resource_location,$var_deletedimages,$var_newimages,$userid);
				$script_string .= " alert(\"Page Saved!\"); 
									global_saved = true; 
									 global_reload = true; ";
	
			}
		}
		elseif($_POST["actiontype"] == "newpage") {
			$bool_type = false;
			$var_type=$_POST["type"];
			$var_actionin = $_POST["actiontype"];			//assigned to a hidden variable(actionin) 	
			$templateid=$_SESSION['session_currenttemplateid'];
			$var_pagetype=($_POST["pagetype"] == "index")?1:2;
			$tmpsiteid=$_SESSION['session_currenttempsiteid'];
			$userid=$_SESSION["session_userid"];
			$var_editpage = $_POST["editpage"];			// here editpage will contain the name of the page

			if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
			}

			if($var_type == "new") {  //this page is called for a new site not yet published
					$sql_check = "Select * from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";	
					$sql_insert = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'" . addslashes($var_editpage) . "','','htm','advanced')";
			}
			else {
					$bool_type = true;
					$sql_check = "Select * from tbl_site_pages where nsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";	
					$sql_insert = "Insert into tbl_site_pages(nsp_id,nsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'" . addslashes($var_editpage) . "','','htm','advanced')";
			}
			$result = mysql_query($sql_check) or die(mysql_error());
			if(mysql_num_rows($result) <= 0) {
				mysql_query($sql_insert) or die(mysql_error());		
			}
			$var_presentpage=$var_editpage;
			
			$var_pageurl=createPage($var_editpage,$templateid,$tmpsiteid,$var_pagetype,$bool_type);
		}
		elseif($_POST["actiontype"] == "delete") { 
				$bool_type = false;
				$var_type=$_POST["type"];
				$var_editpage=$_POST["editpage"];		// here editpage will contain the id of the page you are trying to delete 
				$var_actionin = $_POST["actiontype"];				//assigned to a hidden variable(actionin) 	
				$var_presentpage = $_POST["presentpage"];
				$var_deletedimages=$_POST["deletedimages"];

				$templateid=$_SESSION['session_currenttemplateid'];
				$tmpsiteid=$_SESSION['session_currenttempsiteid'];
				$userid=$_SESSION["session_userid"];

				if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
				}
				
				if($var_type == "new") {
					$resource_location="../workarea/tempsites/$tmpsiteid/";
					$sql_delete = "Delete from tbl_tempsite_pages where ntempsp_id='" . addslashes($var_editpage) . "'";
					$sql_check = "Select * from tbl_tempsite_pages where ntempsite_id='" . addslashes($tmpsiteid) . "'";
					$sql_insert = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'index.htm','','htm','advanced')";
					removePage($var_presentpage,$tmpsiteid,false);
				}
				elseif($var_type == "edit") {
					$bool_type = true;
					$sql_delete = "Delete from tbl_site_pages where nsp_id='" . addslashes($var_editpage) . "'";
					$sql_check = "Select * from tbl_site_pages where nsite_id='" . addslashes($tmpsiteid) . "'";
					$sql_insert = "Insert into tbl_site_pages(nsp_id,nsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'index.htm','','htm','advanced')";
					$resource_location="../workarea/sites/$tmpsiteid/";
					removePage($var_presentpage,$tmpsiteid,true);
					SaveResource("../sites/$tmpsiteid/resource.txt",$var_deletedimages,"",$userid); 
				}
				
				//This call to SaveResource deletes the images that was there in the page from resource.txt
				SaveResource(($resource_location . "resource.txt"),$var_deletedimages,"",$userid); 

				mysql_query($sql_delete) or die(mysql_error());	
				
				$result=mysql_query($sql_check) or die(mysql_error());	
				if(mysql_num_rows($result) > 0) {
					$row = mysql_fetch_array($result);
					$var_presentpage = $row["vpage_name"];
					$var_pageurl= $resource_location . $var_presentpage;
				}
				else {
						mysql_query($sql_insert) or die(mysql_error());		
						$var_presentpage="index.htm";
						$var_pageurl=createPage("index.htm",$templateid,$tmpsiteid,1,$bool_type);
				}
				$script_string .= " alert(\"Page Deleted!\");"; 
				
		}
		else if($_POST["actiontype"] == "saveas") {

			$bool_type = false;
			$var_actionin = $_POST["actiontype"];	
			$var_presentpage = $_POST["presentpage"];
			$var_pageurl=$_POST["pageurl"];
			$var_type = $_POST["type"];
			$var_deletedimages=$_POST["deletedimages"];
			$var_newimages=$_POST["newimages"];

			$tmpsiteid=$_SESSION['session_currenttempsiteid']; // reconsider this statement since the session will be different in case of sites
			$userid=$_SESSION["session_userid"];
			
			//these 3 parameters will be passed only if "actiontype" = "saveandcreate" 
			$templateid=$_SESSION['session_currenttemplateid'];
			//$var_pagetype=($_POST["pagetype"] == "index")?1:2;
			$var_editpage = $_POST["editpage"];
				 
			if(!isValidRequest($tmpsiteid,$templateid,$userid,$var_type)) {
					echo("<script>alert('Invalid request! Please try again.'); location.href='../usermain.php';</script>");
					exit();
			}	 
			if($var_type == "new") {
				$search_string=$temperory_location . "/$tmpsiteid";
				$fileToSave = "../workarea/tempsites/$tmpsiteid/$var_editpage";
				$resource_location="../workarea/tempsites/$tmpsiteid/resource.txt";
				$sql_check = "Select * from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";
				$sql_insert = "Insert into tbl_tempsite_pages(ntempsp_id,ntempsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'" . addslashes($var_editpage) . "','','htm','advanced')";
			}
			elseif($var_type == "edit") {
			
				$bool_type = true;
				$search_string=$real_location . "/$tmpsiteid";
				$fileToSave = "../workarea/sites/$tmpsiteid/$var_editpage";
				$resource_location="../workarea/sites/$tmpsiteid/resource.txt";
				$sql_check = "Select * from tbl_site_pages where nsite_id='" . $_SESSION['session_currenttempsiteid'] . "' AND vpage_name='" . addslashes($var_editpage) . "'";
				$sql_insert = "Insert into tbl_site_pages(nsp_id,nsite_id,vpage_name,vpage_title,vpage_type,vtype) 
								Values('','" . $_SESSION['session_currenttempsiteid']  . "',
								'" . addslashes($var_editpage) . "','','htm','advanced')";
				//save to original site location
				SaveFile("../sites/$tmpsiteid/$var_editpage",$search_string);
				SaveResource("../sites/$tmpsiteid/resource.txt",$var_deletedimages,$var_newimages,$userid);
			}
			$var_presentpage=$var_editpage;
			SaveFile($fileToSave,$search_string);
			SaveResource($resource_location,$var_deletedimages,$var_newimages,$userid);
			$var_pageurl=$fileToSave;
			$result = mysql_query($sql_check) or die(mysql_error());
			if(mysql_num_rows($result) <= 0) {
				mysql_query($sql_insert) or die(mysql_error());
			}
		}
		$script_string .= "</script>";
	

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML><HEAD><TITLE>::Site Builder-Advanced Editor::</TITLE>
<META http-equiv=Content-Type content="text/html; charset=iso-8859-1">
<LINK href="style/editor.css" type=text/css rel=stylesheet>
<META content="MSHTML 6.00.2900.2722" name=GENERATOR>
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CHACHE"> 
<SCRIPT language=JavaScript src="js/formatbar.js"></script>
<?php
	echo($script_string);
?>
</HEAD>

<BODY onLoad="loading();">

<table width="100%" cellpadding="0" cellspacing="0">
	
	<tr>
	  <td width="79%">&nbsp;&nbsp;&nbsp;
		</td>
	    <td width="21%">&nbsp;
		<form name="PageDetails" method="post" action="editor.php">
			<input type="hidden" name="checkid" id="checkid" value="<?php echo($_SESSION["session_checkid"]); ?>">
			<input type="hidden" name="actiontype" id="actiontype" value="">
			<input type="hidden" name="presentpage" id="presentpage" value="<?php echo($var_presentpage); ?>"> 
			<input type="hidden" name="editpage" id="editpage" value="">
			<input type="hidden" name="pagetype" id="pagetype" value="">
			<input type="hidden" name="pageurl" id="pageurl" value="<?php echo($var_pageurl); ?>">
			<input type="hidden" name="actionIn" id="actionIn" value="<?php echo($var_actionin); ?>">
			<input type="hidden" name="type" id="type" value="<?php echo($var_type); ?>">
			<INPUT type=hidden name="EditorHTM" id="EditorHTM" value=""> 
			<INPUT type=hidden name="EditorHTM2"  value="">
			 <INPUT type=hidden name="EditorHTM3"  value=""> 
			 <INPUT type=hidden name="EditorHTM4"  value=""> 
			 <INPUT type=hidden name="EditorHTM5"  value="">
			 <input type="hidden" name="deletedimages" id="deletedimages" value="">
			 <input type="hidden" name="newimages" id="newimages" value="">
		</form>
		<form name="publishPage" method="post" action="">
			
		</form>
		</td>
    </tr>
	<tr>
	  <td>Pages &nbsp;
        <select name="cmbPages" onChange="javascript:editPage();">
          <?php
			if($var_type == "new") {
			$sql = "Select ntempsp_id as 'nsp_id',vpage_name from tbl_tempsite_pages where ntempsite_id='" . $_SESSION['session_currenttempsiteid'] . "'";
			}
			else {
			$sql = "Select nsp_id,vpage_name from tbl_site_pages where nsite_id='" . $_SESSION['session_currenttempsiteid'] . "'";
			}
			$result = mysql_query($sql) or die(mysql_error());
			if(mysql_num_rows($result) > 0)	{
				while($row= mysql_fetch_array($result)) {
					echo("<OPTION VALUE=\"" . $row["nsp_id"] . "\"" . (($var_presentpage == $row["vpage_name"])?"Selected":"") . " >" . $row["vpage_name"] . "</OPTION>");
				}
			} 
			mysql_free_result($result);
		?>
        </select>
        &nbsp;
        <input type="button" name="EditButton"  value="View"  onClick="javascript:editPage();" style="display:none; ">
        Current Page :<?php echo($var_presentpage); ?> 
      <input type="button" name="SavePage"  value="Save"  onClick="javascript:savePage(1);">
      <input type="button" name="RemovePage"  value="Delete"  onClick="javascript:removePage();">
      <input type="button" name="AddPage"  value="Add a new page"  onClick="javascript:addPage();">
      <input name="Preview" type="button" id="Preview" value="Preview" onClick="javascript:previewSite(<?php echo("'" . (($var_type == "new")?"tempsites":"sites") . "','" . $_SESSION['session_currenttempsiteid'] . "','" . $var_presentpage . "'"); ?>);">
      <?php
	  	if($var_type == "new") { 
	  ?>
	  <input name="Publish" type="button" id="Publish" value="Publish" onClick="javascript:publishSite();">
	  <?php
	  	}
	  ?>	
	  </td>
	  <td>&nbsp;</td>
  </tr>
</table>
<br>&nbsp;<br>&nbsp;<br>&nbsp;
<DIV class=MainBody style="WIDTH: 100%; HEIGHT: 100%">
<!-- Insert top menu  -->
<SCRIPT language=JavaScript src="js/makemenu.js"></SCRIPT>
<SCRIPT language=JavaScript src="js/menu.js"></script>
<!-- Insert format bar  -->
 <TABLE cellSpacing=0 cellPadding=0 width="100%" border=0>
  <TBODY>
  <TR>
  <TD class=body height=22>
      <TABLE class=toolbar id=toolbar_full cellSpacing=0 cellPadding=0
      width="100%" align=center border=0>
      <TBODY>
      <TR>
      <TD class=body height=22>
       <?php
	    include("includes/formatbar.inc");
       ?>
        </TD></TR>
        </TBODY>
        </TABLE>
   </TD></TR>
</TBODY></TABLE>
<DIV id=charMenu style="DISPLAY: none">
<TABLE 
style="BORDER-RIGHT: buttonshadow 2px solid; BORDER-TOP: buttonhighlight 1px solid; FONT-WEIGHT: bold; FONT-SIZE: 14px; BORDER-LEFT: buttonhighlight 1px solid; CURSOR: hand; BORDER-BOTTOM: buttonshadow 1px solid; FONT-FAMILY: Verdana" 
borderColor=#666666 cellSpacing=5 cellPadding=1 bgColor=buttonface border=1>
  <TBODY>
  <TR>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD></TR>
  <TR>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD></TR>
  <TR>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD></TR>
  <TR>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD></TR>
  <TR>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD>
    <TD onclick=parent.insertChar(this) width=15>�</TD></TR></TBODY></TABLE>
</DIV>
<SELECT id=sPageSwitch style="DISPLAY: none" unselectable="on"
            onchange=sGoTo(this.options[this.selectedIndex].value); ></SELECT>
<IFRAME id=foo contentEditable=true
style="BORDER-RIGHT: #000000 0px solid; PADDING-RIGHT: 0px; BORDER-TOP: #000000 0px solid; PADDING-LEFT: 0px; PADDING-BOTTOM: 0px; OVERFLOW: auto; BORDER-LEFT: #000000 0px solid; WIDTH: 100%; PADDING-TOP: 0px; BORDER-BOTTOM: #000000 0px solid; SCROLLBAR-BASE-COLOR: #dddddd; ; HEIGHT: expression(setHeight()); BACKGROUND-COLOR: white"
src="javascript:false;" onload="fooLoad();" onfocus="fooFocus();"></IFRAME>
</DIV>
</BODY>


</HTML>
<script>
function fooFocus() {
}	
 

</script>