<?php
/*
 * This file is part of a larger software package. Please read the License file 
 * in the root of this installation for terms of usage and distribution.
 * 
 * @author The Web Pro Miami, Inc. <info@thewebpro.com>
 * @copyright The Web Pro Miami, Inc. <info@thewebpro.com>, http://www.thewebpro.com/
 * 
 * CORE: manage/dialog/component_edit.php - version 1.01
*/

$nSecureMe=1;

// Secure and connect
require("../../inc/dbconnect.php");
require("../inc/secure_page.php");

// bring in other required files
require("../inc/langutil.php");
require("../../inc/config.php");
require("../inc/lang.php");

// config
$nCompPath = "../../comp/";
$nRefreshCall = "refreshParentsCompEdit();";

// pull in all active languages (used to create multiple fields, when needed)
$nActiveLangARRAY = nGetLangActiveARRAY("../../lang/");

// Get passed-in vars
$nRecID = (isset($_GET['id']) ? $_GET['id'] : NULL);
if(!$nRecID){ $nRecID = (isset($_POST['id']) ? $_POST['id'] : NULL); }

// AJAX Specific vars
$nPassThru = "";
$nDivToUpdate = "editModal";
$nPageInDiv = "dialog/component_edit.php";

// Get additional data
if($nRecID){
	$nSQL = "SELECT nContentID,nComponentID,nPageID FROM xComponentPage WHERE nID=$nRecID";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nContentID = $Row["nContentID"];
		$nCompID = $Row["nComponentID"];
		$nPageID = $Row["nPageID"];
		$nCompTitle = nGetComponentName($nCompID);
		$nCompFile = $nCompID; // nGetComponentFile($nCompID);
	}
	// Get associated content for component; if none exists, create one
	if($nContentID){
		$nSQL = "SELECT * FROM nContent WHERE nID=$nContentID";
		mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
		if($Row = mysql_fetch_array($Result)){
			$nText = $Row["nText"];
			$nTextarea = $Row["nTextarea"];
			$nLinkID = $Row["nLinkID"];
			$nImgID = $Row["nImgID"];
			$nOrderID = $Row["nOrderID"];
		}
	} else {
		$nContentID = nGetNextContentNum();
		// Create new row in nContent for this component
		$Query = "INSERT INTO nContent (nID) VALUES ($nContentID)";
		mysql_select_db($DBName);
		mysql_query($Query, $Link);
		// Update component
		$Query = "UPDATE xComponentPage SET nContentID=$nContentID WHERE nID=$nRecID";
		mysql_select_db($DBName);
		mysql_query($Query, $Link);
	}
	if($nPageID){
		$nSQL = "SELECT nType,nTitle FROM nPage WHERE nID=$nPageID LIMIT 1";
		mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
		if($Row = mysql_fetch_array($Result)){
			$nPageType = $Row["nType"];
			$nPageTitle = $Row["nTitle"];
		}
	}
	switch($nPageType){
		case "Homepage":
			break;
		case "Template":
		case "Content":
			break;
		case "Search":
			break;
	}
}
// initialize array to store calls for content fields
$nFieldCalledARRAY = array();
?>


<div id="<?php echo $nDivToUpdate;?>">

<?php
include("../inc/form_class.php");

$nFormName = "FormCompEdit";
$nForm1 = new Form();
//$nForm1->DEBUG = true;
$nForm1->Name = $nFormName;
$nForm1->Action = $_SERVER['PHP_SELF'];
$nForm1->CancelText = "Cancel";
$nForm1->CancelRedirect = "try{ $.colorbox.close(); }catch(e){} try{ dialogClose(); }catch(e){}";
$nForm1->CancelRedirectIsJS = true;
$nForm1->SubmitText = "Save Changes";
$nForm1->DBLink = $Link;
$nForm1->nUseADODB = false;
// AJAX settings
$nForm1->SubmitIsJS = true;
$nForm1->SubmitToJS = "return submitForm('$nDivToUpdate','$nPageInDiv$nPassThru','$nFormName'); return false;";
// Form styling
$nForm1->FormClass = "form no-border";
$nForm1->CleanMarkup = true;
$nForm1->SubmitClass = "button blue";
$nForm1->CancelClass = "button";
$nForm1->ButtonTemplate = "<div class=\"clearfix grey-highlight\"><div class=\"input no-label\">[#Buttons#]</div></div>\n";
$nForm1->FieldTemplate = "<div id=\"[#RowID#]\" class=\"clearfix\" style=\"[#RowStyle#]\">[#Label#]<div class=\"input\" style=\"[#ItemStyle#]\">[#BeforeField#][#Field#][#AfterField#]<span class=\"info\">[#Caption#]</span></div></div>\n";
$nForm1->GroupTemplate = "<div id=\"[#ID#]\" style=\"[#Style#]\" class=\"[#Class#]\">\n[#Name#][#FieldCode#]\n</div>\n";

// Create groups
$nFormGroup1 = new FormGroup();

// Create fields
$nFormField = new FormField("hidden","id");
$nFormField->Value = $nRecID;
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("hidden","nContentID");
$nFormField->Value = $nContentID;
$nFormGroup1->AddField($nFormField);

$nForm1->AddGroup($nFormGroup1);

// Build form fields from component
// A great place to put in callback processing for components wanting to display their own form
switch($nCompTitle){
	default:
		$nFilePath = "$nCompPath$nCompFile";
		$nCompFileName = str_ireplace(".php","",$nCompFile);
		if(file_exists($nFilePath)){
			// Build a new form group for each language
			$nFormGroupARRAY = array();
			foreach($nActiveLangARRAY as $nLangCode => $nLangName){
				$nFormGroup1 = new FormGroup();
				$nFormGroup1->Style = "width:794px; height:530px; overflow:auto;";
				//if($nLangCode!=$nDefaultLang){ $nFormGroup1->Style = "display:none;"; }
				$nFormGroupARRAY[$nLangCode] = $nFormGroup1;
			}
			// Include the component and let it's "addField" references build the form
			include($nFilePath);
			// Add all new form groups
			foreach($nFormGroupARRAY AS $nGroupLangCode => $nFormGroup1){
				$nForm1->AddGroup($nFormGroup1);
			}
			// Build the language tabs underneath
			if(count($nActiveLangARRAY)>1){ $nFormGroup1 = new FormGroup(); $nFormGroup1->AddField(nGetLangTabGroup()); $nForm1->AddGroup($nFormGroup1); }
		}
}

// Finalize and display form
$nFormToDisplay = $nForm1->GetForm();

// AJAX redirect if form submitted w/o error, otherwise display form (again, if necessary)
if($nForm1->HasProcessed){
	// Post-processing
	if(isset($_POST["id"])){ $nItemID = $_POST["id"]; } else { $nItemID = ""; }
	if(isset($_POST["nContentID"])){ $nContentID = $_POST["nContentID"]; } else { $nContentID = ""; }
	if(isset($_POST["nText"])){ $nText = nConvertIntChars($_POST["nText"]); } else { $nText = ""; }
	if(isset($_POST["nTextarea"])){ $nTextarea = nConvertIntChars(nStripEmpty($_POST["nTextarea"])); } else { $nTextarea = ""; }
	if(isset($_POST["nLinkID"])){ $nLinkID = $_POST["nLinkID"]; } else { $nLinkID = ""; }
	if(isset($_POST["nImgID"])){ $nImgID = $_POST["nImgID"]; } else { $nImgID = ""; }
	if(isset($_POST["nOrderID"])){ $nOrderID = $_POST["nOrderID"]; } else { $nOrderID = ""; }
	
	$Query = "UPDATE nContent SET nText='$nText',nTextarea='$nTextarea',nLinkID='$nLinkID',nOrderID='$nOrderID' WHERE nID=$nContentID LIMIT 1";
	//print "$Query<BR><BR>";
	mysql_select_db($DBName);
	mysql_query($Query, $Link);
	
	// first remove any currently translated content for this item
	if($nContentID){
		$nType = "comp";
		$Query = "DELETE FROM nTranslate WHERE nItemID='$nContentID' AND nType='$nType'";
		mysql_select_db($DBName);
		mysql_query($Query, $Link);
		
		// Now process all valid content fields into array for later saving (will come in like this 'nText_1' or this 'nText_3_es')
		$nOrderLangUsedARRAY = array();
		foreach($_POST AS $nPostItem => $nPostValue){
			if(preg_match("/^nText|nTextarea|nLinkID|nImgID/",$nPostItem)){
				$nContentItemARRAY = explode("_",$nPostItem);
				if(isset($nContentItemARRAY[0])){ $nFieldName = $nContentItemARRAY[0]; } else { $nFieldName = ""; }
				if(isset($nContentItemARRAY[1])){ $nOrderNum = $nContentItemARRAY[1]; } else { $nOrderNum = ""; }
				if(isset($nContentItemARRAY[2])){ $nLangCode = $nContentItemARRAY[2]; } else { $nLangCode = ""; }
				if(!$nLangCode){ $nLangCode = $nDefaultLang; }
				$nPostValue = nConvertIntChars($nPostValue);
				// save content
				if(array_search("$nOrderNum$nLangCode",$nOrderLangUsedARRAY)===false){
					$Query = "INSERT INTO nTranslate (nID,$nFieldName,nItemID,nLang,nOrderID,nType) VALUES ('','$nPostValue','$nContentID','$nLangCode','$nOrderNum','$nType')";
					mysql_select_db($DBName);
					mysql_query($Query, $Link);
					$nOrderLangUsedARRAY[] = "$nOrderNum$nLangCode";
				} else {
					$Query = "UPDATE nTranslate SET $nFieldName='$nPostValue' WHERE nItemID='$nContentID' AND nOrderID='$nOrderNum' AND nLang='$nLangCode' AND nType='$nType'";
					//print "$Query<BR><BR>";
					mysql_select_db($DBName);
					mysql_query($Query, $Link);
				}
			}
		}
	}
	
	// log system event
	$nSystemEventDesc = "Component [nCompID:$nCompID] edited on page [nPageID:$nPageID]";
	$Query = "INSERT INTO nSystemEventLog (nEventTime,nEventDesc,nEditorUser) VALUES ('".date("Y-m-d H:i:s")."','$nSystemEventDesc','$ValidUser')";
	mysql_select_db($DBName); mysql_query($Query, $Link);
	
	// echo print_r($_POST); // for testing purposes
	echo "<script>loadImages = function(){ $nImgJSCode }</script>";
	echo $nFormToDisplay;
	echo "<script>$nRefreshCall try{ $.colorbox.close(); }catch(e){} try{ dialogClose(); }catch(e){}</script>";
} else {
	echo "<script>loadImages = function(){ $nImgJSCode }</script>";
	echo $nFormToDisplay;
	//echo "<script>$.colorbox.resize();</script>";
}
?>
</div>

<script>
refreshParentsCompEdit = function(){
	try{ refreshMobileComps(); } catch(e){ }
	try{ refreshPageComps(); } catch(e){ setTimeout("location.reload(true);", 200); }
}
$(function() {
	try{ loadImages(); }catch(e){}
});
// Handle image callbacks
editImage = function(id){
	var xURL = "dialog/image_edit.php?id="+id;
	var xTitle = "Edit Image";
	$.colorbox({ href:xURL, title:xTitle, overlayClose:false, opacity:0.4, maxWidth:850, initialWidth:80, initialHeight:80 });
}
choiceSave = function(imgid,fld){
	// update field
	$('#'+fld).val(imgid);
	loadImages();
	$.colorbox.close();
	return false;
}
deleteImage = function(fld){
	$('#'+fld).val(0);
	loadImages();
}
</script>

<?php
// called from component files
$nImgJSCode = "";

function addField($nFldID="",$nTitle="",$nCaption="",$nDefVal="",$nFldStyle="",$nCustFuncMan="",$nCustFuncSite=""){
	global $nForm1,$nFormGroupARRAY,$nDefaultLang,$nContentID,$nActiveLangARRAY,$nFieldCalledARRAY,$nCompFileName,$nRecID,$nImgJSCode,$nPageType;
	
	// For each language, buld a seperate field for this field and add it to the appropriate form group (group was created earlier)
	foreach($nActiveLangARRAY as $nLangCode => $nLangName){
		if($nFormGroupARRAY[$nLangCode]){
			$nFormGroup1 = $nFormGroupARRAY[$nLangCode];
			if($nLangCode==$nDefaultLang){ $nLangSuffix = ""; } else { $nLangSuffix = "_$nLangCode"; } // $nFormGroup1->Style = "display:none;";
			
			if($nFldID=="rte"){ $nFldID = "textarea-rte"; } // fix for built-in error (until "rte" is renamed "textarea-rte")
			
			if(!$nFldID || !$nFormGroup1 || !is_object($nFormGroup1) || !$nForm1 || !is_object($nForm1)){ return; }
			if(count($nActiveLangARRAY)>1){ $nTitleText="$nTitle ($nLangName):"; } else { $nTitleText="$nTitle:"; }
			$nFldIDARRAY = explode("-",$nFldID); // split fldID into base,extension (e.g. image,Header)
			// Special field cases need more handling
			if($nFldIDARRAY[0]=="image" && isset($nFldIDARRAY[1])){ $nFldID="image"; $nImageLibrary = $nFldIDARRAY[1]; } else { $nImageLibrary = ""; }
			$nFldAppend = $nFldIDARRAY[0].$nLangSuffix;
			if(isset($nFieldCalledARRAY[$nFldAppend])){ $nFieldCalledARRAY[$nFldAppend]++; } else { $nFieldCalledARRAY[$nFldAppend] = 1; }
			switch($nFldID){
				case "text":
					$nLoadedValue = nGetLangContent($nLangCode,$nContentID,"comp","nText",$nFieldCalledARRAY[$nFldAppend]);
					$nFldName = "nText_".$nFieldCalledARRAY[$nFldAppend]."$nLangSuffix"; // e.g. nText~1_en
					$nFormField = new FormField("text","$nFldName","$nTitleText");
					if($nLoadedValue){ $nFormField->Value = $nLoadedValue; } else { $nFormField->Value = $nDefVal; }
					$nFormField = $nForm1->AddValidation("maxlength",$nFormField,200);
					$nFormField->RowID = "row_$nLangCode";
					$nFormField->Class = "xlarge";
					if($nLangCode!=$nDefaultLang){ $nFormField->RowStyle = "display:none;"; }
					break;
				case "textarea":
					$nLoadedValue = nGetLangContent($nLangCode,$nContentID,"comp","nTextarea",$nFieldCalledARRAY[$nFldAppend]);
					$nFldName = "nTextarea_".$nFieldCalledARRAY[$nFldAppend]."$nLangSuffix"; // e.g. nTextarea~1_en
					$nFormField = new FormField("textarea","$nFldName","$nTitleText");
					if($nLoadedValue){ $nFormField->Value = $nLoadedValue; } else { $nFormField->Value = $nDefVal; }
					$nFormField->RowID = "row_$nLangCode";
					if($nLangCode!=$nDefaultLang){ $nFormField->RowStyle = "display:none;"; }
					//$nFormField->Caption = "$nCaption <a href=\"popup_editor.php?nFieldName=$nFldName&nFormName=FormCompEdit\" target=\"popup_editor\" class=\"content\" onClick=\"PopUp(this.href,this.target,820,560,0);\">Open In Advanced Editor (WYSIWYG)</a>";
					break;
				case "textarea-rte":
					$nLoadedValue = nGetLangContent($nLangCode,$nContentID,"comp","nTextarea",$nFieldCalledARRAY[$nFldAppend]);
					$nFldName = "nTextarea_".$nFieldCalledARRAY[$nFldAppend]."$nLangSuffix"; // e.g. nTextarea~1_en
					$nFormField = new FormField("rte","$nFldName","$nTitleText");
					$nFormField = $nForm1->AddOnSubmitScript("$('#$nFldName').val(FCKeditorAPI.GetInstance('$nFldName').GetXHTML());",$nFormField);
					if($nLoadedValue){ $nFormField->Value = $nLoadedValue; } else { $nFormField->Value = $nDefVal; }
					$nFormField->RowID = "row_$nLangCode";
					if($nLangCode!=$nDefaultLang){ $nFormField->RowStyle = "display:none;"; }
					$nFormField->ItemStyle = "width:525px;";
					//$nFormField->Caption = "$nCaption <a href=\"popup_editor.php?nFieldName=$nFldName&nFormName=FormCompEdit\" target=\"popup_editor\" class=\"content\" onClick=\"PopUp(this.href,this.target,820,560,0);\">Open In Advanced Editor (WYSIWYG)</a>";
					break;
				case "link":
				case "link-Page":
					$nLinkIDSelected = nGetLangContent($nLangCode,$nContentID,"comp","nLinkID",$nFieldCalledARRAY[$nFldAppend]);
					$nFldName = "nLinkID_".$nFieldCalledARRAY[$nFldAppend]."$nLangSuffix"; // e.g. nLinkID~1_en
					$nFormField = new FormField("select","$nFldName","$nTitleText");
					$nFormField->DataARRAY = nGetPageARRAY();
					if($nLinkIDSelected){
						$nFormField->SelectedARRAY = array("$nLinkIDSelected" => "selected");
					} else {
						$nFormField->SelectedARRAY = array("0" => "selected"); // default
					}
					$nFormField->RowID = "row_$nLangCode";
					if($nLangCode!=$nDefaultLang){ $nFormField->RowStyle = "display:none;"; }
					break;
				case "link-Section":
					$nLinkIDSelected = nGetLangContent($nLangCode,$nContentID,"comp","nLinkID",$nFieldCalledARRAY[$nFldAppend]);
					$nFldName = "nLinkID_".$nFieldCalledARRAY[$nFldAppend]."$nLangSuffix"; // e.g. nLinkID~1_en
					$nFormField = new FormField("select","$nFldName","$nTitleText");
					$nFormField->DataARRAY = nGetSectionARRAY();
					if($nLinkIDSelected){
						$nFormField->SelectedARRAY = array("$nLinkIDSelected" => "selected");
					} else {
						$nFormField->SelectedARRAY = array("0" => "selected"); // default
					}
					$nFormField->RowID = "row_$nLangCode";
					if($nLangCode!=$nDefaultLang){ $nFormField->RowStyle = "display:none;"; }
					break;
				case "image":
					$nImgIDSelected = nGetLangContent($nLangCode,$nContentID,"comp","nImgID",$nFieldCalledARRAY[$nFldAppend]);
					$nFldName = "nImgID_".$nFieldCalledARRAY[$nFldAppend]."$nLangSuffix"; // e.g. nImgID~1_en
					if($nImageLibrary){ $nImgType = $nImageLibrary; } else { $nImgType = "Content"; }
					
					$nFormField = new FormField("static","","$nTitleText");
					if($nCaption){ $nFormField->Caption = "$nCaption"; }
					$nFormField->Value = "<div id=\"nImagePreview_$nFldName\"></div><BR style=\"clear:both; float:none;\">";
					$nFormField->RowStyle = "clear:both;float:none;";
					$nFormField->RowID = "row_$nLangCode";
					if($nLangCode!=$nDefaultLang){ $nFormField->RowStyle = "display:none;"; }
					$nFormGroup1->AddField($nFormField);
					
					// Add Javascript to control this field
					$nImgJSCode.=<<<CODE
						$('#nImagePreview_$nFldName').html(loaderImgL).load('list/images_show.php?fld=$nFldName&id='+$('#$nFldName').val(), function(){
							// check if loaded images are empty, and if so, replace it with a button
							var galleryHTML = $.trim( $('#imageGallery').html() );
							if(galleryHTML==""){
								if($('#nImagePreview_$nFldName').html('<a href="list/images_choose.php?fld=$nFldName" title="Choose an image" class="button modal" style="margin-bottom:-10px; display:block;">Choose an image...</a>')){
									updateStyles();
								}
							} else { updateStyles(); }
						});
CODE;
					
					// Field to hold actual image ID
					$nFormField = new FormField("hidden","$nFldName","$nTitleText");
					$nFormField->Value = $nImgIDSelected;
					break;
				case "text-ImageLibrary":
					$nLoadedValue = nGetLangContent($nLangCode,$nContentID,"comp","nText",$nFieldCalledARRAY[$nFldAppend]);
					$nFldName = "nText_".$nFieldCalledARRAY[$nFldAppend]."$nLangSuffix"; // e.g. nText~1_en
					$nFormField = new FormField("select","$nFldName","$nTitleText");
					$nFormField->DataARRAY = nGetLibImgARRAY();
					if($nLoadedValue){
						$nFormField->SelectedARRAY = array("$nLoadedValue" => "selected");
					} else {
						$nFormField->SelectedARRAY = array("0" => "selected"); // default
					}
					$nFormField->RowID = "row_$nLangCode";
					if($nLangCode!=$nDefaultLang){ $nFormField->RowStyle = "display:none;"; }
					break;
			}
			
			// If custom build function exists, override built-in field with custom function
			$nFunctionName = "";
			if($nCompFileName && $nCustFuncMan){ $nFunctionName = $nCompFileName."_".$nCustFuncMan; }
			if(function_exists($nFunctionName)){
				eval("\$nCustFuncReturn = $nFunctionName(\$nFldName,\$nLoadedValue);");
				$nFormField = new FormField("static","","<div>$nTitle</div>");
				$nFormField->Value = $nCustFuncReturn;
			}
			
			// Finally, finish up and add field to form
			if($nFormField){
				if($nCaption && !$nFormField->Caption){ $nFormField->Caption = "$nCaption"; }
				if($nFldStyle){ $nFormField->Style = "$nFldStyle"; }
				$nFormGroup1->AddField($nFormField);
			}
		}
	}
}

function nGetComponentName($nRecID){
	global $DBName,$Link;
	$nSQL = "SELECT nName FROM nComponent WHERE nCompFile='$nRecID' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nName = $Row["nName"];
	}
	return $nName;
}

function nGetComponentFile($nRecID){
	global $DBName,$Link;
	$nSQL = "SELECT nCompFile FROM nComponent WHERE nID='$nRecID' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nCompFile = $Row["nCompFile"];
	}
	return $nCompFile;
}

function nGetImageTagFromID($nImgID,$nAltTag="",$nMaxWidth="",$nMaxHeight=""){
	global $DBName,$Link,$nJSOnloadARRAY;
	//if(!$nImgID){ return 0; }
	$nSQL = "SELECT nPath,nPathOver FROM nImage WHERE nID='$nImgID' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nPath = $Row["nPath"];
		$nPathOver = $Row["nPathOver"];
	}
	// search a few levels up in case this image is being shown in editor
	if(!file_exists($nPath)){ $nPath = "../$nPath"; $nPathOver = "../$nPathOver"; }
	if(!file_exists($nPath)){ $nPath = "../$nPath"; $nPathOver = "../$nPathOver"; }
	if(file_exists($nPath)){
		$nImgTag = nGetImgTag($nPath,$nAltTag,$nMaxWidth,$nMaxHeight);
		if($nPathOver){ $nJSOnloadARRAY[]="new Rollover('img$nImgID');"; }
		return $nImgTag;
	} else {
		return "$nPath";
	}
}

function nGetImgTag($nImgFile,$nAltTag="",$nMaxWidth="",$nMaxHeight=""){
	global $nFullSitePath;
	if(!$nImgFile){ return; }
	if(file_exists("$nImgFile")){
		$nImgTagARRAY = getimagesize($nImgFile);
		$nImgTagW = $nImgTagARRAY[0];
		$nImgTagH = $nImgTagARRAY[1];
		// Resize image dimensions, if needed
		if($nMaxWidth && !$nMaxHeight){ $nMaxHeight = 9999; }
		if($nMaxHeight && !$nMaxWidth){ $nMaxWidth = 9999; }
		if($nMaxWidth && $nMaxHeight && ($nImgTagW>$nMaxWidth || $nImgTagH>$nMaxHeight)){
			$nResizeRatio = MIN( $nMaxWidth / $nImgTagW, $nMaxHeight / $nImgTagH );
			$nImgTagW = $nResizeRatio * $nImgTagW;
			$nImgTagH = $nResizeRatio * $nImgTagH;
		}
		$nImgTagWH = "width=\"".round($nImgTagW)."\" height=\"".round($nImgTagH)."\"";
	}
	// build absolute path so image shows in both editor and front-end
	$nFinalPath = $nFullSitePath.$nImgFile;
	$nFinalPath = str_replace("../","",$nFinalPath);
	$nTag = "<img src=\"$nFinalPath\" alt=\"$nAltTag\" $nImgTagWH border=\"0\">";
	return $nTag;
}

function nGetSectionARRAY(){
	global $DBName,$Link;
	global $nRecID;
	$nDataARRAY = array();
	$nSQL = "SELECT * FROM nSection ORDER BY nParentID,nName ASC";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"];
		$nName = $Row["nName"];
		$nParentID = $Row["nParentID"];
		$nPageCount = nGetPageCount($nID);
		if($nParentID){
			if($nPageCount){ $nDataARRAY["$nID"] = "- $nName ($nPageCount pages)"; }
		} else {
			if($nPageCount){ $nDataARRAY["$nID"] = "$nName ($nPageCount pages)"; }
		}
	}
	return $nDataARRAY;
}

function nGetPageARRAY(){
	global $DBName,$Link;
	global $nRecID;
	$nDataARRAY = array();
	$nDataARRAY[0] = "- Do not link to a Page -";
	$nDataARRAY[-1] = "- Link to same image, if available -";
	$nSQL = "SELECT nID,nNavTitle FROM nPage ORDER BY nNavTitle"; // ORDER BY nType,nSectionID,nOrderID
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"];
		$nNavTitle = $Row["nNavTitle"];
		$nDataARRAY["$nID"] = "$nNavTitle";
	}
	$nSQL = "SELECT nID,nPath,nType FROM nFile ORDER BY nType"; // ORDER BY nType,nSectionID,nOrderID
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"];
		$nType = $Row["nType"];
		$nPath = $Row["nPath"];
		$nFilename = nGetImageNameFromPath($nPath);
		$nDataARRAY["$nPath"] = "FILE: $nFilename";
	}
	return $nDataARRAY;
}

function nGetImageNameFromPath($nPath){
	if(!$nPath){ return; }
	$nPathARRAY = explode("/",$nPath);
	$nImgName = $nPathARRAY[(count($nPathARRAY)-1)];
	return $nImgName;
}

function nGetImgARRAY($nFilter="",$nAllowNone=false){
	global $DBName,$Link;
	$nWhereSQL = "";
	$nDataARRAY = array();
	if($nAllowNone){ $nDataARRAY[0] = "- None -"; }
	if($nFilter){ $nWhereSQL = "WHERE nType='$nFilter'"; }
	$nSQL = "SELECT nID,nPath FROM nImage $nWhereSQL";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"];
		$nPath = $Row["nPath"];
		$nDataARRAY["$nID"] = "$nPath";
	}
	return $nDataARRAY;
}
function nGetLibImgARRAY(){
	global $DBName,$Link;
	$nDataARRAY = array();
	$nSQL = "SELECT * FROM nLibrary";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nLibraryID = $Row["nID"];
		$nName = $Row["nName"];
		$nDataARRAY["image-$nName"]="$nName";
	}
	return $nDataARRAY;
}

function nGetPageCount($nSectionID){
	global $DBName,$Link;
	if($nSectionID===""){ return 0; }
	$nNumRecords = 0;
	$nSQL = "SELECT nID FROM nPage WHERE nSectionID=$nSectionID";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	$nNumRecords = mysql_num_rows($Result);
	return $nNumRecords;
}

function nGetNextContentNum(){
	global $DBName,$Link;
	$nSQL = "SELECT Max(nID) AS nID FROM nContent";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"] + 1;
	}
	return $nID;
}

// returns array of active storefront languages in alpha order, default will be first item in list 
function nGetLangActiveARRAY($nPathOverride=""){
	global $nDefaultLang;
	$nDefaultLangARRAY = array();
	$nLangARRAY = array();
	// Get all files in directory
	if($nPathOverride){ $path = $nPathOverride; } else { $path = "lang/"; }
	$dir_handle = @opendir($path) or die("Unable to open $path");    
	while ($file = readdir($dir_handle)) {
		if($file == "." || $file == ".." || $file == "index.php" )
			continue;
		$nFileCode = str_replace(".php","",$file);
		if(!is_dir("$path$file/")){
			if(file_exists("$path$file")){ require("$path$file"); }
			if($nFileCode == $nDefaultLang){
				if($nLang){ $nDefaultLangARRAY["$nFileCode"] = $nLang; } // default language
			} else {
				if($nLang){ $nLangARRAY["$nFileCode"] = $nLang; }
			}
		}
	}
	closedir($dir_handle);
	// sorting, and add default to top of list
	krsort($nLangARRAY);
	foreach($nDefaultLangARRAY as $nLangCode => $nLangName) {
		$nLangARRAY["$nLangCode"] = $nLangName;
	}
	$nLangARRAY = array_reverse($nLangARRAY,true);
	return $nLangARRAY;
}

// returns an array of content found for that particular field
function nGetLangContent($nLangCode,$nItemID,$nType,$nFieldName,$nOrderID){
	global $DBName, $Link;
	if(!$nLangCode || !$nItemID || !$nType || !$nFieldName){ return; };
	$nContent = "";
	$Query = "SELECT $nFieldName AS nContent FROM nTranslate WHERE nLang='$nLangCode' AND nItemID='$nItemID' AND nType='$nType' AND nOrderID='$nOrderID'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	while ($Row = mysql_fetch_array($Result)) {
		$nContent = $Row["nContent"];
	}
	// Replace special characters
	$nContent = stripslashes($nContent);
	$nContent = str_replace("\"","&quot;",$nContent);
	return $nContent;
}

function nGetLangTabGroup(){
	global $nActiveLangARRAY,$nDefaultLang;
	//$nFormGroup1 = new FormGroup();
	$nHideCodeJS = "";
	$nLangDivARRAY = array();
	$nLangTabARRAY = array();
	foreach($nActiveLangARRAY as $nLangCode => $nLangName) { $nLangDivARRAY[] = "[id=row_$nLangCode]"; $nLangTabARRAY[] = "#tab_$nLangCode"; }
	if($nLangDivARRAY){ $nLangDivList = implode(",",$nLangDivARRAY); }
	if($nLangTabARRAY){ $nLangTabList = implode(",",$nLangTabARRAY); }
	$nHideCodeJS.="$('$nLangDivList').hide(); $('$nLangTabList').removeClass('langTabActive').addClass('langTab');";
	$nLangLinks = "";
	foreach($nActiveLangARRAY as $nLangCode => $nLangName) {
		if($nLangCode==$nDefaultLang){ $nLangSuffix = ""; $nClass="langTabActive"; } else { $nLangSuffix = "_$nLangCode"; $nClass="langTab"; }
		$nLangLinks.="<a href=\"javascript:;\" onClick=\"$nHideCodeJS $('[id=row_$nLangCode]').show(); $('#tab_$nLangCode').removeClass('langTab').addClass('langTabActive');\" id=\"tab_$nLangCode\" class=\"$nClass\">$nLangName</a> ";
	}
	$nFormField = new FormField("static","",_("Language:"));
	$nFormField->Value = $nLangLinks;
	$nFormField->ItemStyle = "font-weight:bold;";
	//$nFormGroup1->AddField($nFormField);
	return $nFormField;
}

function nUnconvertIntChars($nText){
	if(!$nText){ return; }
	// lowercase
	$nText = str_replace("&uacute;","ú",$nText);
	$nText = str_replace("&iacute;","í",$nText);
	$nText = str_replace("&oacute;","ó",$nText);
	$nText = str_replace("&eacute;","é",$nText);
	$nText = str_replace("&aacute;","á",$nText);
	$nText = str_replace("&ntilde;","ñ",$nText);
	// uppercase
	$nText = str_replace("&Uacute;","Ú",$nText);
	$nText = str_replace("&Iacute;","Í",$nText);
	$nText = str_replace("&Oacute;","Ó",$nText);
	$nText = str_replace("&Eacute;","É",$nText);
	$nText = str_replace("&Aacute;","Á",$nText);
	$nText = str_replace("&Ntilde;","Ñ",$nText);
	return $nText;
}

/**
 * Check the syntax of some PHP code.
 * @param string $code PHP code to check.
 * @return boolean|array If false, then check was successful, otherwise an array(message,line) of errors is returned.
 */
function php_syntax_error($code){
    $braces=0;
    $inString=0;
    foreach (token_get_all('<?php ' . $code) as $token) {
        if (is_array($token)) {
            switch ($token[0]) {
                case T_CURLY_OPEN:
                case T_DOLLAR_OPEN_CURLY_BRACES:
                case T_START_HEREDOC: ++$inString; break;
                case T_END_HEREDOC:   --$inString; break;
            }
        } else if ($inString & 1) {
            switch ($token) {
                case '`': case '\'':
                case '"': --$inString; break;
            }
        } else {
            switch ($token) {
                case '`': case '\'':
                case '"': ++$inString; break;
                case '{': ++$braces; break;
                case '}':
                    if ($inString) {
                        --$inString;
                    } else {
                        --$braces;
                        if ($braces < 0) break 2;
                    }
                    break;
            }
        }
    }
    $inString = @ini_set('log_errors', false);
    $token = @ini_set('display_errors', true);
    ob_start();
    $braces || $code = "if(0){{$code}\n}";
    if (eval($code) === false) {
        if ($braces) {
            $braces = PHP_INT_MAX;
        } else {
            false !== strpos($code,CR) && $code = strtr(str_replace(CRLF,LF,$code),CR,LF);
            $braces = substr_count($code,LF);
        }
        $code = ob_get_clean();
        $code = strip_tags($code);
        if (preg_match("'syntax error, (.+) in .+ on line (\d+)$'s", $code, $code)) {
            $code[2] = (int) $code[2];
            $code = $code[2] <= $braces
                ? array($code[1], $code[2])
                : array('unexpected $end' . substr($code[1], 14), $braces);
        } else $code = array('syntax error', 0);
    } else {
        ob_end_clean();
        $code = false;
    }
    @ini_set('display_errors', $token);
    @ini_set('log_errors', $inString);
    return $code;
}

function nStripEmpty($nData){
	$nData = str_replace("<p></p>","",$nData);
	$nData = str_replace("<p> </p>","",$nData);
	$nData = str_replace("<p>&nbsp;</p>","",$nData);
	$nData = str_replace("&nbsp;","",$nData);
	return $nData;
}
?>
<?php require("../../inc/db_close.php"); ?>
