<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 2005-2006 ARMIA INC                                    |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts EasyCreate 1.1                 |
// +----------------------------------------------------------------------+
// | Authors: sudheesh<sudheesh@armia.com>        		              	  |
// |          									                          |
// +----------------------------------------------------------------------+
include "../includes/session.php";
include "../includes/config.php";
include "../includes/function.php";
$tmpsiteid=$_SESSION['session_currenttempsiteid'];
$templateid=$_SESSION['session_currenttemplateid'];
$userid=$_SESSION["session_userid"];
if (get_magic_quotes_gpc()) {
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}


 if($_POST['btnpayment']=="Publish using FTP/ZIP/SUBFOLDER"){
    $sql="select vname,vvalue from tbl_lookup where vname ='paymentsupport'";
    $result=mysql_query($sql,$con);
    $row=mysql_fetch_array($result);
    $needpaymentsupport=$row['vvalue'];
    if($needpaymentsupport=="no"){
               header("location:../publishpage_free.php?uid=".$userid."&tid=" . $tmpsiteid . "&type=simple&style=" . $_SESSION["session_style"] . "&" );
              exit;

	}else{
	  header("location:" . $_SESSION["session_secureserver"] . "/publishpage.php?uid=".$userid."&tid=" . $tmpsiteid . "&type=simple&style=" . $_SESSION["session_style"] . "&" );
      exit;
	}

 }else  if($_POST['btnaddpage']=="Add/Remove Pages"){
   $_SESSION['session_backurl']="simpleIEeditor/editor.php";
   header("location:../addlinks.php?urltype=back&urlfrom=editor&");
   exit;
 }else if($_POST['btneditsite']=="Edit Site details"){
   $_SESSION['session_backurl']="simpleIEeditor/editor.php";
   header("location:../getsitedetail.php?urltype=back");
   exit;
 }else if($_POST['btnback']=="Back"){
   $_SESSION['session_backurl']="simpleIEeditor/editor.php";
   header("location:../addlinks.php?urltype=back");
   exit;
 }
        /*check whether the site exist in tbl_template_mast with
		* the  combination of current templateid,userid and type
		if site exist in database  check for the pages exist in workarea location
		*/
		$errormessage="";
		$qry="select * from tbl_tempsite_mast where ntempsite_id='".$tmpsiteid."' and nuser_id='".$userid."' and ntemplate_id='".$templateid."' and vtype='simple'";
		if( mysql_num_rows( mysql_query($qry))>0){
		    if(! is_dir("../workarea/tempsites/".$tmpsiteid)){
			  $errormessage="Site temporary removed.please contact administrator to resolve issue!";
			}

		}else{
		   $errormessage="You are not authorized to view this page!";
		   header("location:../sitemanager.php");
		   exit;

		}
		if($errormessage !=""){
		  echo $errormessage;
		  exit;

		}
/*
* Save html files in wrokarea/tempsites/,save editable content in sitepages/tempsite/
*/
function SaveSitepage($userid,$tmpsiteid,$templateid,$editabletext,$pagename){
       //set_magic_quotes_runtime(0);
       $basicloc=fetchBasicLocation(1);
	   $temperory_location=$basicloc."/workarea/tempsites/".$tmpsiteid;
	   $real_location=$basicloc."/workarea/sites/";

	   $qry=" select * from tbl_tempsite_mast where ntempsite_id='".$tmpsiteid."'";
       $rs=mysql_query($qry);
       $row=mysql_fetch_array($rs);
         //strip slashes and put htmlentities for title,metadesc,metakey
			 $row['vmeta_description']=htmlentities($row['vmeta_description']);
             $row['vmeta_key']=htmlentities($row['vmeta_key']);
             $row['vtitle']=htmlentities($row['vtitle']);
	   //call smarty libraries
	    require('../smarty/lib/Smarty.class.php');
		remove_dir("../smarty/templates_c");
		@mkdir("../smarty/templates_c",0777);
		@chmod("../smarty/templates_c",0777);
		if($row['vcolor'] !="NULL" and $row['vcolor'] !=""){
		  $siteclrvalue=".variable { background-color:".$row['vcolor']."; }";
		}else{
		  $siteclrvalue="";
		}
		$smarty = new Smarty();
		$smarty->template_dir = "../".$_SESSION["session_template_dir"]."/".$templateid;
		$smarty->compile_dir = '../smarty/templates_c';
		$smarty->cache_dir = '../smarty/cache';
		$smarty->config_dir = '../smarty/configs';
	    //clear the cache

		if(strcasecmp($pagename,"home.htm")==0){
                        $smarty->clear_cache('index.tpl');
				$smarty->assign('vsite_metadesc', $row['vmeta_description']);
				$smarty->assign('vsite_metakey', $row['vmeta_key']);
			    $smarty->assign('vsite_title', $row['vtitle']);
			    $smarty->assign('vsitecolor', $siteclrvalue);
			    $smarty->assign('vlogoband', $row['vlogo']);
			    $smarty->assign('vcompanyband',$row['vcompany']);
			    $smarty->assign('captionband', $row['vcaption']);
                            $smarty->assign('vsite_links', $row['vlinks']);
				$smarty->assign('vsite_editable', $editabletext);
			    $html=$smarty->fetch('index.tpl', $cache_id = null, $compile_id = null, false);
				//	echo $html."<br><br>";
				$html=str_replace("../workarea/tempsites/".$tmpsiteid,"",$html);
				//echo $html;
				$fp=fopen("../workarea/tempsites/".$tmpsiteid."/$pagename","w");
		        fwrite($fp,$html,strlen($html));
		        fclose($fp);
				file_replace ($temperory_location, ".", "../workarea/tempsites/".$tmpsiteid."/$pagename");
				$fp1=fopen("../sitepages/tempsites/$tmpsiteid/$pagename","w");
		        fputs($fp1,$editabletext);
		        fclose($fp1);
				file_replace ($temperory_location, ".", "../sitepages/tempsites/$tmpsiteid/$pagename");
		  }else{
		        $smarty->clear_cache('subpage.tpl');
				$smarty->assign('vsite_metadesc', $row['vmeta_description']);
				$smarty->assign('vsite_metakey', $row['vmeta_key']);
			    $smarty->assign('vsite_title', $row['vtitle']);
			    $smarty->assign('vsitecolor', $siteclrvalue);
			    $smarty->assign('vinnserlogoband', $row['vsub_log']);
			    $smarty->assign('vinnercompanyband',$row['vsub_company']);
			    $smarty->assign('innercaptionband', $row['vsub_caption']);
                            $smarty->assign('vsite_links', $row['vsub_sitelinks']);
				$smarty->assign('vsubsite_editable', $editabletext);
			    $html=$smarty->fetch('subpage.tpl', $cache_id = null, $compile_id = null, false);

				$fp=fopen("../workarea/tempsites/".$tmpsiteid."/$pagename","w");
		        fputs($fp,$html);
		        fclose($fp);
				file_replace ($temperory_location, ".", "../workarea/tempsites/".$tmpsiteid."/$pagename");
				
				//save editable text
				$fp=fopen("../sitepages/tempsites/$tmpsiteid/$pagename","w");
		        fputs($fp,$editabletext);
		        fclose($fp);

				//file_replace ($temperory_location, ".", "../sitepages/tempsites/$tmpsiteid/$pagename");

		  }


}
/*function to save changes to resource file
* var_deletedimages - list of deleted images seperated by |
* $var_newimages -list of new images
* this function remove all the entries for deleted images.add new entry for inserted images
*/

$resource_save_flag = false;
function SaveResource($resource_location,$var_deletedimages,$var_newimages) {
            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/".$_SESSION["session_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/".$_SESSION["session_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);
}
/* replace $search-search string (ie http://192.168.011)
*  $replace- replace string(.)
*  $filename-name of the file(ie workarealocation/home.htm
*/
function file_replace ($search, $replace, $filename) {
		   if (file_exists($filename)) {
			       $cnt = file_get_contents($filename);
				   $cnt = preg_replace($search,$replace,$cnt);

				     $htmlcontents=$cnt;
				      $headposition=strpos($htmlcontents,"<head>");
					  if(!$headposition){
								 $headposition=strpos($htmlcontents,"<HEAD>");
					  }
					  /* check whether <head> tag exist.if exist assign all the content between <head> and </head> to $headelements
					  *  then replace $headelements to "" at the end of this function
					  *  check whether the <body> tag exist .if exist assing all the content <body > to $bodyelemants
					  *  replace   $bodyelemants to ""
					  */
					  if($headposition){
					     $backslashheadposition=strpos($htmlcontents,"</head>");
						 if(!$backslashheadposition){
								 $backslashheadposition=strpos($htmlcontents,"</HEAD>");
					     }
						 $headelements=substr($htmlcontents, $headposition,$backslashheadposition-$headposition+7);

						 $bodyposition=strpos($htmlcontents,"<BODY");
						 if(!$bodyposition){
								 $bodyposition=strpos($htmlcontents,"<body");
					     }
						  if($bodyposition){
						      $bodyelemants=substr($htmlcontents,$bodyposition, strpos(substr($htmlcontents,$bodyposition),">")+1);

						  }
					  }
					 $htmlcontents=str_replace($bodyelemants,"",$htmlcontents );
					 $htmlcontents=str_replace($headelements,"",$htmlcontents );
					 $htmlcontents = preg_replace("<html>","",$htmlcontents);
					 $htmlcontents = preg_replace("</html>","",$htmlcontents);
					 $htmlcontents = preg_replace("</body>","",$htmlcontents);
				     $cnt=$htmlcontents;
			        fwrite(fopen($filename,"w"),$cnt);  //here file_put_contents() cannot be used since it is available only on php5
			   		return true;
		   }
		   return false;
}

 /*document.all("pageforsave").value =pag;
	  document.all("pageforsave_type").value ="saveandgo";

	  savePage(1);*/

if($_POST["actiontype"] == "save" || $_POST["actiontype"] == "saveandcreate") {
    
	 if(!validateSizePerUser($_SESSION["session_userid"],$size_per_user,$allowed_space)) {
           echo "<script> alert('Your space exceeded permitted limit." .
				"(Space taken by you: " . human_read($size_per_user) . " " .
				"Allowed space: " . human_read($allowed_space) . ") \\r\\n" .
				"Delete unused images or any/all of the sites created by you to proceed further.'); location.href='../usermain.php'; </script>";

     }else{

	        $pagename=$_POST['currentpage'];
			$var_deletedimages=$_POST["deletedimages"];
			$var_newimages=$_POST["newimages"];

			$resource_location="../workarea/tempsites/$tmpsiteid/resource.txt";

			$htmtext=$_POST["EditorHTM"].$_POST["EditorHTM2"].$_POST["EditorHTM3"].$_POST["EditorHTM4"].$_POST["EditorHTM5"];
			$htmtext=str_replace("src=\"../workarea/tempsites/$tmpsiteid/","src=\"",$htmtext);
			SaveSitepage($userid,$tmpsiteid,$templateid,$htmtext,$pagename);

			SaveResource($resource_location,$var_deletedimages,$var_newimages);
	}
	if($_POST['pageforsave_type']=="saveandgo"){
	 	$pagetogo=$_POST['pageforsave'];
    	$location="editor.php?page=".strtolower($pagetogo)."&";
    	header("location:$location");
		exit;
	}

}else if($_POST['pageforsave_type']=="go"){
    $pagetogo=$_POST['pageforsave'];
    $location="editor.php?page=".strtolower($pagetogo)."&";
    header("location:$location");
	exit;
}
/* every time when a user calls this page,page name will be passed as GET variable without extension(ie home)
*  if page name is empty ,page name will be set as default(ie Home)
*/
$pagename=addslashes(trim($_GET['page']));
$pagenamewithouthtm=$pagename;
if($pagename==""){
  $pagenamewithouthtm="Home";
  $pagename="home.htm";
}else{
  $pagename=$pagename.".htm";
}
$currenteditablefile=$pagename;
$currenteditableurllocation="../workarea/tempsites/$tmpsiteid/$currenteditablefile";
/*check for the user requested page exist in workarea location
*/
if( is_file("../sitepages/tempsites/$tmpsiteid/$pagename")){
       copy("../sitepages/tempsites/$tmpsiteid/$pagename","../workarea/tempsites/$tmpsiteid/$currenteditablefile");
       chmod($currenteditableurllocation,0777);
}else{
    $errormessage="Site pages temporarily removed. please contact administrator to resolve the issue!";
	echo $errormessage;
	exit;
}
include "./userheader.php";
?>
<!--
<script type="text/javascript" src="../code/jscripts/tiny_mce/tiny_mce.js"></script>
<SCRIPT language=JavaScript src="js/formatbar.js"></script>
-->
<script>
	//document.body.onload=loading();
</script>
<SCRIPT>
function savefile(){

//document.getElementById('htmltext').value=tinyMCE.get('ajaxfilemanager').getContent();//foo.document.body.innerHTML;
document.getElementById('htmltext').value=CKEDITOR.instances.editor1.getData();
document.frmbtnedit.submit();

}
function savePage(a) {
 		//document.all("EditorHTM").value = foo.document.body.innerHTML
		//alert(foo.document.body.innerHTML);
//		var content = tinyMCE.get('ajaxfilemanager').getContent();
                var content = CKEDITOR.instances.editor1.getData();
		//document.all("EditorHTM").value = tinyMCE.get('ajaxfilemanager').getContent();
		document.getElementById("EditorHTM").value = content;
		//document.all("EditorHTM").value = foo.document.documentElement.innerHTML;
		//re = /&amp;/g
		//document.all("EditorHTM").value = document.all("EditorHTM").value.replace(re,'&')
		htmlLength = document.getElementById("EditorHTM").value.length
		myHTML = document.getElementById("EditorHTM").value;
		var mcLength = parseInt( myHTML.length / 5);
		//var num = new Number(mcLen);
        //var mcLength = num.toFixed();
		document.getElementById("EditorHTM").value = content;//myHTML.substr(0, mcLength);
		var t1=(mcLength*2) + 1;
		t1=parseInt(t1);
		var t2= myHTML.substr(mcLength,t1);
		//document.getElementById("EditorHTM2").value = myHTML.substr(mcLength,t1);
		//document.getElementById("EditorHTM3").value = myHTML.substr(mcLength*2+1, mcLength*3 + 1);
		//document.getElementById("EditorHTM4").value = myHTML.substr(mcLength*3+1, mcLength*4 + 1);
		//document.getElementById("EditorHTM5").value = myHTML.substr(mcLength*4+1, myHTML.length);
		document.getElementById("deletedimages").value = checkForDeleted();
		document.getElementById("newimages").value = checkForNew();
		switch(a) {
			case 1:
					document.getElementById("actiontype").value = "save";
					break;
			case 2:
				document.getElementById("actiontype").value = "saveandcreate";
				break;
			default:
					alert("Invalid function call.");
					return;
		}
		/* checkid is used to track page refreshment.to avoid add more images in resource.txt file*/
		if(isNaN(document.getElementById("checkid").value) || document.getElementById("checkid").value.length <= 0 || (parseInt(document.getElementById("checkid").value) <= 0)) {
			document.getElementById("checkid").value=1;
		}
		else {
			document.getElementById("checkid").value = parseInt(document.getElementById("checkid").value) + 1;
		}
		document.getElementById("PageDetails").submit();
}
function viewpreview(){
/*
           if(foo.document.readyState != "complete") {
			alert('The page you are trying to priview has not yet loaded completely. Please wait for the page to load completely.');
			return;
		  }
*/
            var leftPos = (screen.availWidth-500) / 2;
		    var topPos = (screen.availHeight-400) / 2 ;
			var currentpage=document.getElementById("currentpage").value;
		    winurl="showsitepreview.php?currentpage="+currentpage+"&";
		    insertFormWin = window.open(winurl,'','width=' + screen.availWidth + ',height=' + screen.availHeight + ',scrollbars=yes,resizable=yes,titlebar=0,top=' + topPos + ',left=' + leftPos);


}
processFlag=false;
function process() {
	if(processFlag == false) {
		processFlag=true;
			var finalImages;
//			finalImages = tinyMCE.get('ajaxfilemanager').getContent().images;
                        finalImages = CKEDITOR.instances.editor1.getData();
			i=0;

			var sourceCount=source.length;
			if(finalImages)
				var finalCount=finalImages.length;
		    else
				var finalCount=0;
			

			while(i < sourceCount) {
				if(source[i] != "") {
					var strTemp=source[i];
					strTemp=strTemp.substr((strTemp.lastIndexOf("/") + 1),(strTemp.length));
					if(strTemp.substr(0,2) == "ug" || strTemp.substr(0,2) == "sg" || strTemp.substr(0,2) == "sl") {
						j=0;
						while(j < finalCount) {
							if(finalImages[j].src != "") {
								var strTemp2 = finalImages[j].src;
								if(strTemp == strTemp2.substr((strTemp2.lastIndexOf("/") + 1),(strTemp2.length))) {
									source[i]="";
									finalImages[j].src="";
									break;
								}
							}
							j++;
						}
					}
					else {
						source[i] == "";
					}
				}
				i++;
			}
	}
}
function checkForDeleted() {
	var strDeleted = "";
	process();
	var sourceCount=source.length;
	for(i=0;i<sourceCount;i++) {
		if(source[i] != "") {
			var strTemp=source[i];
			strTemp=strTemp.substr((strTemp.lastIndexOf("/") + 1),(strTemp.length));
			if(strTemp.substr(0,2) == "ug" || strTemp.substr(0,2) == "sg" || strTemp.substr(0,2) == "sl") {
				strDeleted = strDeleted + strTemp + "|";
			}
		}
	}
	if(strDeleted.length > 0) {
		strDeleted = strDeleted.substr(0,strDeleted.length-1);
	}
	return strDeleted;
}
function checkForNew() {
	var strNew = "";
	process();
	if (typeof(finalImages) != "undefined") 
		var finalCount=finalImages.length;
	else
		var finalCount=0;
	for(i=0;i<finalCount;i++) {
		if(finalImages[i].src != "") {
			var strTemp=finalImages[i].src;
			strTemp=strTemp.substr((strTemp.lastIndexOf("/") + 1),(strTemp.length));
			if(strTemp.substr(0,2) == "ug" || strTemp.substr(0,2) == "sg" || strTemp.substr(0,2) == "sl") {
				strNew = strNew + strTemp + "|";
			}
		}
	}
	if(strNew.length > 0) {
		strNew = strNew.substr(0,strNew.length-1);
	}
	return strNew;
}
function SaveCompelsory(pag){
	if(confirm("Do you want to save your current page ?")){
	  document.getElementById("pageforsave").value =pag;
	  document.getElementById("pageforsave_type").value ="saveandgo";

	  savePage(1);
	}else{
	  document.getElementById("pageforsave").value =pag;
	  document.getElementById("pageforsave_type").value ="go";

      document.getElementById("PageDetails").submit();
	}

}
</SCRIPT>

 <!-- ckeditor integration start here -->
 <script type="text/javascript" src="<?php echo fetchBasicLocation(1); ?>/ckeditor/ckeditor/ckeditor.js"></script>
        <script type="text/javascript" src="<?php echo fetchBasicLocation(1); ?>/ckeditor/js/jquery.js"></script>
        <script language=JavaScript src="js/formatbar.js"></script>
        <script type="text/javascript">
	 $(document).ready(function(){

		CKEDITOR.replace( 'editor1',
        {

            /*toolbar :
            [
                ['newplugin','footnote','Bold','Italic','Underline', '-', 'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock', '-', 'NumberedList','BulletedList','-','Outdent','Indent'],
                ['Link','Unlink','Anchor','Image', '-', 'Format','Font','FontSize', 'TextColor']
            ],*/

            filebrowserBrowseUrl : '<?php echo fetchBasicLocation(1); ?>/ckeditor/ckeditor/filemanager/index.php',
            filebrowserImageBrowseUrl : '<?php echo fetchBasicLocation(1); ?>/ckeditor/ckeditor/filemanager/index.php?Type=Images',
            filebrowserUploadUrl : '<?php echo fetchBasicLocation(1); ?>/ckeditor/ckeditor/filemanager/core/connector/php/filemanager.php?command=QuickUpload&type=Files',
            filebrowserImageUploadUrl : '<?php echo fetchBasicLocation(1); ?>/ckeditor/ckeditor/filemanager/core/connector/php/filemanager.php?command=QuickUpload&type=Images',
            filebrowserImageManagerUrl : '<?php echo fetchBasicLocation(1); ?>/ckeditor/ckeditor/filemanager/index.php?Type=Images&CKEditor=editor1&CKEditorFuncNum=4&langCode=en&filemode=server'
            });

     CKEDITOR.config.width = 900;
     CKEDITOR.config.height = 500;
     CKEDITOR.config.fullPage = true;
     CKEDITOR.config.removePlugins = 'smiley,link,save';
     CKEDITOR.on( 'dialogDefinition', function( ev ){

                // Take the dialog name and its definition from the event data.
		var dialogName = ev.data.name;
		var dialogDefinition = ev.data.definition;
		// Check if the definition is from the dialog we're
		// interested on (the Link dialog).
		if ( dialogName == 'link' ){
			// FCKConfig.LinkDlgHideAdvanced = true
                        dialogDefinition.removeContents('advanced');
                        dialogDefinition.removeContents('upload');
                        /*
                        var definition = ev.data.definition;
                        var content = definition.getContents( 'target' );
                        content.remove( 'linkTargetType' );
                        */
                        var info = dialogDefinition.getContents( 'info' );
                        info.remove('protocol');


                        info.add( {
					type : 'text',
					label : 'Protocol',
					id : 'protocol',
					'default' : 'http://',
					validate : function()
					{
						if ( /\d/.test( this.getValue() ) )
							return 'Protocol is must';
					}
				});

			// FCKConfig.LinkDlgHideTarget = true
			//dialogDefinition.removeContents( 'default' );
                         /*Enable this part only if you don't remove the 'target' tab in the previous block.*/
			// FCKConfig.DefaultLinkTarget = '_blank'
			// Get a reference to the "Target" tab.
			//var targetTab = dialogDefinition.getContents( 'target' );

                        /*
                        var cdrt  =   targetTab.get('linkTargetType');
                        cdrt.remove('_blank');
                        */

                        //targetTab.remove('PopupWindowFeatures');
                        //targetTab.remove('linkTargetType');

                        //$("#cke_81_select option[value='_blank']").remove();



                        /*
                        targetTab.add( {
					type : 'select',
                                        id : 'cke_81_select',
                                        label : 'Target',
                                        items : [ [ 'New Window', '_blank' ], [ 'Same Window', '_self' ] ],
                                        'default' : 'Football',
                                        onChange : function( api ) {
                                        //this = CKEDITOR.ui.dialog.select
                                        alert( 'Current value: ' + this.getValue() );
                                        }
                                       });
                        */
                      /*
                        targetTab.add( {
					type : 'radio',
					label : 'Link Type',
					id : 'cke_81_select',
					items   :   [ [ 'New Window', '_blank' ], [ 'Same Window', '_self' ] ]
				});
                       */
                      /*
                            targetTab.add( {
					type : 'file',
                                        id : 'upload',
                                        label : 'Select file from your computer',
                                        size : 38

				});
                        targetTab.add( {
					type : 'text',
					label : 'My Custom Field',
					id : 'customField',
					'default' : 'added new!',
					validate : function()
					{
						if ( /\d/.test( this.getValue() ) )
							return 'My Custom Field must not contain digits';
					}
				});
                        */

			// Set the default value for the URL field.
			//var targetField = targetTab.get( 'linkTargetType' );

			//targetField[ 'default' ] = '_blank';
		}
		if ( dialogName == 'image' ){

			dialogDefinition.removeContents( 'advanced' );
                       
                        
                        var info        =   dialogDefinition.getContents( 'info' );

                        var brwse       =   info.get('browse');
                        brwse.label     =   'Browse';

                        var alttxt      =   info.get('txtAlt');
                        alttxt.label    =   'Image Title';

                        var wdth        =   info.get('txtWidth');
                        wdth.label      =   'Image Width';
                        wdth.width      =   60;

                        var hght = info.get('txtHeight');
                        hght.label  =   'Image Height';
                        hght.width  =   60;

                        var valg = info.get('cmbAlign');
                        valg.items = [['left','left'],['right','right']];
                        valg['default'] =   'left';

                        var Link        =   dialogDefinition.getContents( 'Link' );
                        var Url         =   Link.get('txtUrl');
                        Url.label       =   'Make Image Clickable Link';
                        Url['default']  =   'http://';
                        Link.remove('browse');

                        var target       =   Link.get( 'cmbTarget' );
                        target.label     =   '<br />Target Page';
                        target.items     =   [['New Window','_blank'],['Same Window','_self']];

                        var Upload       =   dialogDefinition.getContents( 'Upload' );
                        var upload       =   Upload.get('uploadButton');
                        upload.label     =   'Upload Image';
                        dialogDefinition.removeContents( 'Upload' );


		}
		if ( dialogName == 'flash' )
		{
			dialogDefinition.removeContents( 'advanced' );
                        dialogDefinition.removeContents( 'Upload' );
                        dialogDefinition.removeContents( 'properties' );
		}
	});


	});

        </script>

<table width="100%"  border="0" cellspacing="0" cellpadding="0" class=background>
<tr>
<td  valign="top" align=center>
                <table width="100%"  border="0" cellspacing="0" cellpadding="0">
				<tr>
				  <td align=center>
				  <div class="stage_selector">
				  <span>4</span>&nbsp;&nbsp;Edit Contents
				  </div>
				  
				  
				  </td>
				</tr>
				<tr>
				  <td align=left><?php if(!empty($_POST)){ echo "<div style='color:green'>Page successfully saved</div>"; } ?> </td>
				</tr>
                <tr>
<td >
<!-- Main section starts here-->


<TABLE cellSpacing=0 cellPadding=0 width="100%" border=0>
          <TBODY>
          <?php
          
              $pagenamewithouthtm=addslashes(trim($_GET['page']));
                  if($pagenamewithouthtm=="")
                       $pagenamewithouthtm="home";
                  /* display all pages that the user created for the current site*/
                  $qry="select * from tbl_tempsite_pages where ntempsite_id='".$_SESSION['session_currenttempsiteid']."' order by ntempsp_id";
                  $res=mysql_query($qry);
                ?>
            <tr>
                    <td COLSPAN="2">
                           <table align=left border=0>
                               <tr>
                                    <?php
                                                $totalcharctercountinpagename=0;
                                                    while($row=mysql_fetch_array($res)){

                                                        $pagenamewithspace=$row['vpage_name'];
                                                        $row['vpage_name']=str_replace(" ","" , $row['vpage_name']);
                                                        $totalcharctercountinpagename=$totalcharctercountinpagename+strlen($row['vpage_name']);
                                                        if($totalcharctercountinpagename >100){
                                                          echo "</tr><tr>";
                                                          $totalcharctercountinpagename=0;
                                                        }
                                                        /* set different style for selected page and other page.if no page selected default page will be home
                                                           page name that will be passed as GET variable converted to lowercase.
                                                        */
                                                        if( strcasecmp($pagenamewithouthtm,$row['vpage_name'])==0){
                                        ?>
                                                                                    <td class=maintext  valign="top">

                                                                                           <table width="70px" height="45"  border="1" cellpadding="0" cellspacing="0" bordercolor="#1E63AE">
                                                                <tr>
                                                                  <td align="center" valign="top" bgcolor="#47B1E4" style="width:70px; word-wrap: break-word;">
                                                                                                           <a class=anchor href="./editor.php?page=<?php echo strtolower($row['vpage_name'])?>&">  <img border=0 src="images/pageclear.gif" width="30" height="35"></a><br>
                                                                                                           <a class=editorlinks href="./editor.php?page=<?php echo strtolower($row['vpage_name'])?>&" style="color:black;"> <?php echo strtolower($row['vpage_name']); ?></a>
                                                                                                          </td>
                                                                </tr>
                                                              </table>



</td>
<TD>&nbsp;</TD>

<?php
}else{
?>

<td class=maintext valign="top">

<table width="70px" height="45"  border="1" cellpadding="0" cellspacing="0" bordercolor="#A2BFCC">

<tr>
<?php
$pagenameforjs="";
$pagenameforjs=strtolower($row['vpage_name']);
?>
<td align="center" valign="top" bgcolor="#D0DFE6" style="width:70px; word-wrap: break-word;" >
<a class=anchor href="#" onclick="SaveCompelsory('<?php echo $pagenameforjs?>');"><img border=0 src="images/pagefade.gif" width="30" height="35"> </a>
<br>
<a class=editorlinks href="#" onclick="SaveCompelsory('<?php echo $pagenameforjs?>');">     <?php echo strtolower($row['vpage_name']); ?> </a>
</td>
</tr>

</table>

<!--/editor.php?page=<?php echo strtolower($row['vpage_name'])?>&-->

<!--<a class=anchor href="./editor.php?page=<?php echo strtolower($row['vpage_name'])?>&"><?php echo $row['vpage_name']; ?> </a>-->
</td>
<TD>&nbsp;</TD>

<?php
}

?>

<?php }

?>

</tr>

</table>
</td>

</tr>
<tr><td class=borderbg colspan=5><img src="./image/spacer.gif" width=0 height=1></td></tr>
<TR>
<TD class=bodyband height=22 COLSPAN="2"></TD></TR>
<tr>
<td>
<SELECT id=sPageSwitch style="DISPLAY: none" unselectable="on"
onchange=sGoTo(this.options[this.selectedIndex].value); ></SELECT>
</td>
</tr>
<!-- iframe window -->

<tr>
<td COLSPAN="2">
<?php 
//print_r($_SERVER);
$substr=str_replace("../workarea/tempsites/","",$currenteditableurllocation);
$sid=substr($substr,0,strpos($substr,"/"));
$replacepath=fetchBasicLocation(1)."/workarea/tempsites/$sid/";


$imgPath='';
$fileSavePath='';
/*
$imgPath="/davidpaul/workarea/tempsites/$sid/images";
$fileSavePath="/davidpaul/workarea/tempsites/$sid/flash";
//echo "../workarea/sites/".$tmpsiteid."/";
$_SESSION['imagesavepath']=$_SERVER['DOCUMENT_ROOT'].$imgPath;
$_SESSION['mediasavepath']=$_SERVER['DOCUMENT_ROOT'].$fileSavePath;
*/


    $repString="../workarea/tempsites/".$tmpsiteid."/";
    $replacepath=fetchBasicLocation(1)."/workarea/tempsites/$tmpsiteid/";
    $imgPath="workarea/tempsites/$tmpsiteid/images";
    $fileSavePath="workarea/tempsites/$tmpsiteid/flash";


$FileName=$currenteditableurllocation;



$roorLoc=$_SESSION['ROOT_PATH'];
$rootLoc=str_replace($_SERVER['DOCUMENT_ROOT'], "", $roorLoc);
$_SESSION['imagesavepath']=$_SESSION['ROOT_PATH'].$imgPath;
$_SESSION['mediasavepath']=$_SESSION['ROOT_PATH'].$fileSavePath;
$_SESSION['replacepath']=$replacepath.'images/';
$_SESSION['FILE_PATH'] = '/'.$rootLoc.$imgPath;
$_SESSION['FILE_PATH']=str_replace("//","/",$_SESSION['FILE_PATH']);
$_SERVER['DOCUMENT_ROOT'].fetchBasicLocation(1);




//$handle         =  fopen($FileName, 'rb');
//$f_contents     =  fread($handle, filesize($FileName));

//$f_contents=str_replace("src=\"","src=\"".$search_string."/",$f_contents);

//fclose($handle);

//$f_contents=str_replace("src=\"","src=\"".$replacepath,$f_contents);


$f_contents     =   file_get_contents($FileName);


$f_contents=str_replace($repString,"",$f_contents);
$f_contents=str_replace("src=\"./","src=\"",$f_contents);
$f_contents=str_replace("src=\"","src=\"".$replacepath,$f_contents);



?>
<textarea id="editor1" name="ajaxfilemanager"><?php echo $f_contents; ?></textarea>

</td>
</tr>
<tr>
<td>
<IFRAME id=fooStyles
contentEditable=true style="DISPLAY: none"
src="images/00af970f4b9590626dcfdb96a5f4b4d4.htm"></IFRAME>
</td>
</tr>

<tr><td align=right width="37%">
<form name=PageDetails id="PageDetails" method=post>
<input type="hidden" name="checkid" id="checkid" value="<?php echo($_SESSION["session_checkid"]); ?>">
<input type=hidden id=htmltext name=htmltext value="" >
<input type="hidden" name="pageurl" id="pageurl" value="<?php echo($currenteditableurllocation); ?>">
<input type=hidden id=currentpage name=currentpage value="<?php echo $pagename?>" >
<INPUT type=hidden name="EditorHTM" id="EditorHTM" value="">
<INPUT type=hidden name="EditorHTM2" id="EditorHTM2" value="">
<INPUT type=hidden name="EditorHTM3" id="EditorHTM3" value="">
<INPUT type=hidden name="EditorHTM4" id="EditorHTM4" value="">
<INPUT type=hidden name="EditorHTM5" id="EditorHTM5" value="">
<INPUT type=hidden name="pageforsave" id="pageforsave" value="">
<INPUT type=hidden name="pageforsave_type" id="pageforsave_type"  value="">
<input type="hidden" name="deletedimages" id="deletedimages" value="">
<input type="hidden" name="newimages" id="newimages" value="">
<input type="hidden" name="actiontype" id="actiontype" value="">
<input class=button type=button id=savedata name=savedata value="Save this page(<?php echo $pagenamewithouthtm?>)" onclick="savePage(1);">
<input class=button type=button id=sitepreview name=sitepreview value="Preview" onclick="viewpreview();">


</form>
</td><td align=left>
<form name=frmbackbuttons method=post>
&nbsp; <input class=button name="btnpayment" type=submit value="Publish using FTP/ZIP/SUBFOLDER" >
<input class=button name="btnaddpage" type=submit value="Add/Remove Pages" >
<input class=button name="btneditsite" type=submit value="Edit Site details" >
<input class=button name="btnback" type=submit value="Back" >
</form>
</td>


</tr>

<tr>
<td>&nbsp;</td>
</tr>
<!--<form name=frmbackbuttons method=post>

<tr>
<td>
<table width="40%" align=right>
<tr>
<td><input class=button name="btnpayment" type=submit value="Publish using FTP/ZIP" ></td>
<td><input class=button name="btnaddpage" type=submit value="Add/Remove Pages" ></td>
<td><input class=button name="btneditsite" type=submit value="Edit Site details" ></td>
<td><input class=button name="btnback" type=submit value="Back" ></td>
</tr>
</table>
</td>

</tr>
</form>-->
</TBODY>
</TABLE>


<!-- Main section ends here-->
</td>
</tr>
<tr><td>&nbsp;</td></tr>
<tr><td>&nbsp;</td></tr>
</table>
<?php
$reloadpage=basename($_SERVER['REQUEST_URI']);

?>
<form name=reloadpage action="<?php echo $reloadpage?>" method=post>

</form>
</td>
</tr>
</table>

<?php
include "./userfooter.php";
?>
<script>
//document.onload=loading();

</script>