<?php
/*
 * This file is part of Web Pro Manager.
 * 
 * Web Pro Manager is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Web Pro Manager is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Web Pro Manager.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @author The Web Pro Miami, Inc. <info@thewebpro.com>
 * @copyright The Web Pro Miami, Inc. <info@thewebpro.com>, http://www.thewebpro.com/
 * @license http://www.gnu.org/licenses/gpl.html GNU GPL
 * @package WebProManager
*/

// config
$nCompPath = "comp/";
$nUserCompPath = "comp/";
if(!file_exists($nCompPath)){
	$nCompPath = "../comp/";
	$nUserCompPath = "../comp/";
}
if(!file_exists($nCompPath)){
	$nCompPath = "../../comp/";
	$nUserCompPath = "../../comp/";
}

/* ------ MAIN Template Functions ------ */

$nOpenerTag="[#"; $nCloserTag="#]"; $nTagParamDelim="_";

function tmplShow($nTemplate){
	global $DBName,$Link;
	global $nTmplPath,$nReqTagsAdded,$nDefaultLang,$nSFLang,$nCurrentTheme,$nPageID;
	if(!$nTemplate){ return ""; }
	// Pull in template file ($nPath = "home.html"; $nPathLang = "home_$nSFLang.html")
	if($nTemplate=="content"){
		$nTemplate = strtolower(nGetPageType($nPageID));
	}
	$nPath = strtolower($nTemplate).".html"; $nPathLang = strtolower($nTemplate)."_$nSFLang.html";
	if($nCurrentTheme){
		$nTmplPath = $nCurrentTheme.$nPath;
		$nTmplPathLang = $nCurrentTheme.$nPathLang;
	} else {
		exit("No current theme set. Please update your Theme Library settings.");
	}
	// Get language-specific template, if available
	$nFullTmplPathLang = "tmpl/$nTmplPathLang";
	if(file_exists($nFullTmplPathLang) && is_file($nFullTmplPathLang)){
		$nTemplateCode = file_get_contents($nFullTmplPathLang);
	} else {
		// Get default template
		$nFullTmplPath = "tmpl/$nTmplPath";
		if(file_exists($nFullTmplPath) && is_file($nFullTmplPath)){ $nTemplateCode = file_get_contents($nFullTmplPath); } else {
			exit("Theme template does not exist: $nFullTmplPath. Please check your system configuration.");
		}
	}
	$nTemplateCode = tmplParse($nTemplateCode);
	if(!$nReqTagsAdded){ $nTemplateCode = tmplAddRequiredTags($nTemplateCode); }
	return $nTemplateCode;
}

function nGetIfMobileAgent(){
	global $nForceMobile,$nAllowMobile;
	if(!$nAllowMobile){ return false; }
	// START mobile check
	$nAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
	$iphone = strpos($nAgent,"iphone");
	$android = strpos($nAgent,"android");
	$palmpre = strpos($nAgent,"webos");
	$ipod = strpos($nAgent,"ipod");
	// $ipad = strpos($nAgent,"ipad"); // works for both ipad and ipad2
	if($nForceMobile || $iphone || $android || $palmpre || $ipod){
		return true;
	} else {
		return false;
	}
}

function tmplAddRequiredTags($nTemplateCode){
	global $nReqTagsAdded,$nJSOnloadARRAY,$nRequiredAtBeginOfHeadARRAY,$nRequiredAtEndOfHeadARRAY,$nRequiredAtBeginOfBodyARRAY,$nRequiredAtEndOfBodyARRAY,$nFullSitePath,$nSSLSitePath,$_SERVER,$nPageID;
	$nHTTPS = (isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : NULL);
	if($nHTTPS==="on"){ $nFullSitePath=$nSSLSitePath; }
	
	// add required tags to end of body
	$nRequiredAtEndOfBodyARRAY[] = "<div id=\"status\" style=\"display:none;\"><table><tr><td class=\"padRight\"><img src=\"".$nFullSitePath."manage/img/load.gif\" alt=\"\" width=\"16\" height=\"16\" border=\"0\"></td><td><div align=\"center\">Loading...<BR>Please wait<BR></div></td></tr></table></div>";
	
	/*
	if($_SERVER['HTTPS']!=="on"){ 
		$nRequiredAtBeginOfHeadARRAY[] = "<script type=\"text/javascript\" src=\"".$nFullSitePath."js/lightbox/lightbox.js\"></script>";
		$nRequiredAtBeginOfHeadARRAY[] = "<link rel=\"stylesheet\" href=\"".$nFullSitePath."css/lightbox.css\" type=\"text/css\" media=\"screen\" />";
		$nRequiredAtBeginOfHeadARRAY[] = "<link rel=\"stylesheet\" href=\"".$nFullSitePath."css/tooltip.css\" type=\"text/css\" media=\"screen\" />";
	}
	$nRequiredAtBeginOfHeadARRAY[] = "<script type=\"text/javascript\" src=\"".$nFullSitePath."js/utility.js\"></script>";
	$nRequiredAtBeginOfHeadARRAY[] = "<link rel=\"stylesheet\" href=\"".$nFullSitePath."tmpl/global.css\" type=\"text/css\" media=\"screen\" />";
	// add required tags to end of body
	$nRequiredAtEndOfBodyARRAY[] = "<div id=\"minicartNote\" style=\"display:none;\"><table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td><img src=\"".$nFullSitePath."img/note_top.gif\" alt=\"\" width=\"149\" height=\"8\" border=\"0\"></td></tr><tr><td align=\"center\" class=\"minicartNoteContent\">Item added to cart <a href=\"javascript:;\" onClick=\"hideMCNote();return false;\"><img src=\"".$nFullSitePath."img/note_close.gif\" alt=\"\" width=\"10\" height=\"10\" border=\"0\" style=\"margin:0px 0px -2px 10px;\"></a></td></tr><tr><td><img src=\"".$nFullSitePath."img/note_bot.gif\" alt=\"\" width=\"149\" height=\"3\" border=\"0\"></td></tr></table></div>";
	$nRequiredAtEndOfBodyARRAY[] = nGetAnalyticsCode();
	*/
	// add required tags to header and body
	//if(!$nTemplateCodeARRAY[1]){ exit("Head tag does not exist or does not properly close in your template. Please check and fix your template."); }
	
	// add required tags to head
	if($nRequiredAtBeginOfHeadARRAY){
		$nReqBeginHeadTags = implode("\n",$nRequiredAtBeginOfHeadARRAY);
		$nTemplateCode = preg_replace("/<head([A-Za-z0-9_ ><.:;\/#=\"'-]*)>/","<head$1>".$nReqBeginHeadTags,$nTemplateCode,1);
	}
	if($nRequiredAtEndOfHeadARRAY){
		$nTemplateCodeARRAY = explode("</head>",$nTemplateCode);
		$nTemplateCode = $nTemplateCodeARRAY[0].implode("\n",$nRequiredAtEndOfHeadARRAY)."</head>\n".$nTemplateCodeARRAY[1];
	}
	if($nRequiredAtEndOfBodyARRAY){
		$nTemplateCodeARRAY = explode("</body>",$nTemplateCode);
		$nTemplateCode = $nTemplateCodeARRAY[0].implode("\n",$nRequiredAtEndOfBodyARRAY)."</body>\n".$nTemplateCodeARRAY[1];
	}
	if($nJSOnloadARRAY){
		$nTemplateCodeARRAY = explode("<body",$nTemplateCode);
		$nTemplateCode = $nTemplateCodeARRAY[0]."<body onLoad=\"".implode("\n",$nJSOnloadARRAY)."\"".$nTemplateCodeARRAY[1];
	}
	// add required tags to beginning of body
	if($nRequiredAtBeginOfBodyARRAY){
		$nReqBeginBodyTags = implode("\n",$nRequiredAtBeginOfBodyARRAY);
		$nTemplateCode = preg_replace("/<body([A-Za-z0-9_ ><.:;\/#=\"'-]*)>/","<body$1>".$nReqBeginBodyTags,$nTemplateCode,1);
	}
	$nReqTagsAdded = 1;
	return $nTemplateCode;
}

function tmplParse($nTemplateCode,$nItemID="",$nItemType=""){
	global $nOpenerTag,$nCloserTag,$nTagParamDelim;
	if(!$nTemplateCode){ return ""; }
	// Parse elements
	do{
		$nOpenerPos = strpos($nTemplateCode,$nOpenerTag);
		$nCloserPos = strpos($nTemplateCode,$nCloserTag,$nOpenerPos);
		if($nOpenerPos!==false && $nCloserPos!==false){
			$nInnerTag = substr($nTemplateCode,($nOpenerPos+strlen($nOpenerTag)),($nCloserPos-strlen($nCloserTag)-$nOpenerPos));
			$nReplacement = "";
			$nInnerTagARRAY = explode($nTagParamDelim,$nInnerTag);
			$nTemplateItem = $nInnerTagARRAY[0];
			unset($nInnerTagARRAY[0]);
			switch($nTemplateItem){
				/* -------------- Components ----------------- */
				case "comp":
					$nReplacement = tmplGetComp($nTemplateItem,$nInnerTagARRAY);
					break;
				case "compColumnComps":
					$nReplacement = tmplGetColumnComps($nTemplateItem,$nInnerTagARRAY);
					break;
				case "compPageNav":
					$nReplacement = tmplGetCompPageNav($nItemID,$nInnerTagARRAY);
					break;
				case "compProdList":
					$nReplacement = tmplGetCompProdList($nTemplateItem,$nInnerTagARRAY);
					break;
				case "compLangNav":
					$nReplacement = tmplGetCompLangNav($nItemID,$nInnerTagARRAY);
					break;
				case "compSearchBox":
					$nReplacement = tmplCompSearchBox($nTemplateItem,$nInnerTagARRAY);
					break;
				case "compSearchResults":
					$nReplacement = tmplCompSearchRes($nTemplateItem,$nInnerTagARRAY);
					break;
				/* -------------- Content Items ----------------- */
				case "nPageBGColor":
					$nReplacement = tmplGetPageBGColor($nTemplateItem,$nInnerTagARRAY);
					break;
				case "nBGImagePath":
					$nReplacement = tmplGetPageBGImgPath($nTemplateItem,$nInnerTagARRAY);
					break;
				case "nPageBaseColor":
					$nReplacement = tmplGetPageBaseColor($nTemplateItem,$nInnerTagARRAY);
					break;
				case "nBackBGColor":
					$nReplacement = tmplGetPageBackBGColor($nTemplateItem,$nInnerTagARRAY);
					break;
				case "langChange":
					$nReplacement = tmplGetLangChange($nTemplateItem,$nInnerTagARRAY);
					break;
				case "text":
				case "pageName":
				case "pageTitle":
					$nReplacement = tmplGetPageName($nItemID,$nInnerTagARRAY);
					break;
				case "link":
				case "pageLinkPath":
					$nReplacement = tmplGetPageLinkPath($nItemID,$nInnerTagARRAY);
					break;
				
				case "pageClickPath":
					$nReplacement = tmplGetClickPath($nTemplateItem,$nInnerTagARRAY);
					break;
				case "linkCustomPage":
					$nReplacement = tmplGetLinkCustomPage($nTemplateItem,$nInnerTagARRAY);
					break;
				case "wordLanguage":
				case "wordHome":
					$nReplacement = tmplGetWord($nTemplateItem,$nInnerTagARRAY);
					break;
				/* -------------- General Items ----------------- */
				case "sitePath":
				case "siteSSLPath":
				case "siteTmplPath":
					$nReplacement = tmplGetPath($nTemplateItem,$nInnerTagARRAY);
					break;
				case "buttonPath":
					$nReplacement = tmplGetButtonPath($nTemplateItem,$nInnerTagARRAY);
					break;
				case "siteName":
					$nReplacement = tmplGetSiteName($nTemplateItem,$nInnerTagARRAY);
					break;
				case "siteTitle":
					$nReplacement = tmplGetSiteTitle($nTemplateItem,$nInnerTagARRAY);
					break;
				case "linkHome":
				case "linkCart":
					$nReplacement = tmplGetLink($nTemplateItem,$nInnerTagARRAY);
					break;
				case "searchFormOpen":
				case "searchFormClose":
				case "searchField":
					$nReplacement = tmplGetSearchItem($nTemplateItem,$nInnerTagARRAY);
					break;
				case "showDateTime":
					$nReplacement = tmplGetDateTime($nTemplateItem,$nInnerTagARRAY);
					break;
			}
			$nTemplateCode = str_replace(($nOpenerTag.$nInnerTag.$nCloserTag),$nReplacement,$nTemplateCode);
		}
	} while($nOpenerPos!==false);
	return $nTemplateCode;
}

/* ------ COMPONENT Template Functions ------ */

function tmplGetComp($nItem,$nFullParamARRAY=""){
	global $DBName,$Link,$nUserCompPath;
	$nRepeatType = "";
	$nCompFile = nGetParam("FILE",$nFullParamARRAY);
	$nCompFilePath = tmplGetPath("siteTmplPath",array("ABS=0","SSL=0"))."$nUserCompPath$nCompFile";
	if(file_exists($nCompFilePath)){ $nCompCode = file_get_contents($nCompFilePath); } else { return ""; }
	$nCompCode = tmplParse($nCompCode);
	return $nCompCode;
}

function tmplGetCompPageNav($nItemID,$nFullParamARRAY=""){
	global $DBName,$Link,$nPageID,$nUserCompPath;
	$nCompFile = nGetParam("FILE",$nFullParamARRAY);
	$nCompActiveFile = nGetParam("FILE-ACTIVE",$nFullParamARRAY);
	$nShowSubs = nGetParam("SHOWSUBS",$nFullParamARRAY);
	$nCompSub = nGetParam("SUBCOMP",$nFullParamARRAY);
	$nFilterID = nGetParam("NAVID",$nFullParamARRAY);
	$nBefore = nGetParam("BEFORE",$nFullParamARRAY);
	$nAfter = nGetParam("AFTER",$nFullParamARRAY);
	if(!$nFilterID && $nItemID){
		// if this function was called from a sub-nav, let's return this pages related subnav
		// search by name for a section that has the same name as this page and return it if found
		$nPageName = nGetPageName($nItemID);
		if($nPageName){ $nFilterID = nGetSectionIDByName($nPageName); }
	}
	if(!$nFilterID){ $nFilterID=0; }
	if(!$nShowSubs){ $nShowSubs="no"; }
	$nCompFilePath = tmplGetPath("siteTmplPath",array("ABS=0","SSL=0"))."$nUserCompPath$nCompFile";
	$nCompActiveFilePath = tmplGetPath("siteTmplPath",array("ABS=0","SSL=0"))."$nUserCompPath$nCompActiveFile";
	$nCompSubFilePath = tmplGetPath("siteTmplPath",array("ABS=0","SSL=0"))."$nUserCompPath$nCompSub";
	if(!$nFilterID){ $nFilePath=$nCompFilePath; }
	$nActiveNavPageIDARRAY[] = $nPageID;
	$nCompCode = "";
	if($nPageID){
		// get this page's section and parent first
		$Query = "SELECT nSectionID FROM nPage WHERE nID=$nPageID";
		mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
		if($Row = mysql_fetch_array($Result)) {
			$nSectionID = $Row["nSectionID"];
			if($nSectionID){ $nActiveSectionARRAY[] = $nSectionID; }
		}
		// get any additional section parents, if any, for active highlights
		if($nSectionID){
			// add do/while loop here to get any additional parents
			$Query = "SELECT nParentID FROM nSection WHERE nID=$nSectionID LIMIT 1";
			mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
			if($Row = mysql_fetch_array($Result)) {
				$nParentID = $Row["nParentID"];
				if($nParentID){ $nActiveSectionARRAY[] = $nParentID; }
			}
		}
	}
	// for each section, see if there is a page name that matches it, and if so, add it to be hilited
	if(count($nActiveSectionARRAY)){
		foreach($nActiveSectionARRAY AS $nSectionID){
			$nSectionName = nGetSectionName($nSectionID);
			if($nSectionName){
				$nHilitablePageID = nGetPageIDByName($nSectionName);
				if($nHilitablePageID){ $nActiveNavPageIDARRAY[] = $nHilitablePageID; }
			}
		}
	}
	// return navigation
	$Query = "SELECT nID,nType FROM nPage WHERE nSectionID=$nFilterID ORDER BY nOrderID";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	while ($Row = mysql_fetch_array($Result)) {
		$nType = $Row["nType"];
		switch($nType){
			case "Search":
				$nTempCompCode = "[#compSearchBox#]";
				break;
			default:
				if(array_search($Row["nID"],$nActiveNavPageIDARRAY)!==false && $nCompActiveFile){ $nFilePath=$nCompActiveFilePath; } else { $nFilePath=$nCompFilePath; } // for active items
				if(file_exists($nFilePath)){ $nTempCompCode = file_get_contents($nFilePath); } else { return ""; }
				break;
		}
		$nCompCode.=tmplParse($nTempCompCode,$Row["nID"],"cat");
	}
	if($nCompCode){ $nCompCode = "$nBefore$nCompCode$nAfter"; }
	return $nCompCode;
}

function tmplGetColumnComps($nItem,$nFullParamARRAY=""){
	global $DBName,$Link,$nPageID;
	$nColumnID = nGetParam("COLID",$nFullParamARRAY);
	if(!$nColumnID || !$nPageID){ return; }
	$nCompCode = "";
	$nSQL = "SELECT nComponentID,nContentID FROM xComponentPage LEFT JOIN nComponent ON nComponentID=nComponent.nCompFile WHERE nComponent.nActive=1 AND nColumnID=$nColumnID AND nPageID=$nPageID ORDER BY nOrderID";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nContentID = $Row["nContentID"];
		$nCompID = $Row["nComponentID"];
		$nCompTitle = nGetComponentName($nCompID);
		$nCompFile = $nCompID;// nGetComponentFile($nCompID);
		$nCompCode.=tmplComp("",array("CID=$nContentID","CFILE=$nCompFile"));
	}
	return $nCompCode;
}

/* ------ COMPONENT (Template-defined) Template Functions ------ */

function tmplComp($nItem,$nFullParamARRAY=""){
	global $DBName,$Link,$nFullSitePath,$nDefaultLang,$nSFLang,$nCompPath,$nUserCompPath,$nPageID,$nSiteRootPath;
	global $nOpenerTag,$nCloserTag,$nTagParamDelim;
	global $nAllFieldARRAY,$nRequiredAtBeginOfHeadARRAY;
	
	$nContentID = nGetParam("CID",$nFullParamARRAY);
	$nCompFile = nGetParam("CFILE",$nFullParamARRAY);
	$nTranslateLang = nGetParam("LANG",$nFullParamARRAY); // override translation language
	$nShowInEditor = nGetParam("EDIT",$nFullParamARRAY); // toggle showing in editor (0,1)
	
	$nFilePath = "$nCompPath$nCompFile";
	$nSiteTmplPath = tmplGetPath("siteTmplPath",array("ABS=0","SSL=0"));
	$nCompFileName = str_ireplace(".php","",$nCompFile);
	
	$nMaxImgWidth = "500";
	$nMaxImgHeight = "250";
	
	// Pull in component settings file (or return nothing if it no longer exists)
	$nAllFieldARRAY = array();
	if(file_exists($nFilePath)){ include($nFilePath); } else { return; }
	
	// Get template code
	$nTemplateOverridePath = nGetTmplOverridePath($nTemplateFile,$nTranslateLang);
	if($nTemplateOverridePath){ $nTemplateCode = file_get_contents($nTemplateOverridePath); } else { return; }
	
	// Get content to fill template
	$nContentARRAY = nGetContentARRAY($nContentID,$nTranslateLang,"comp");
	if(!$nContentARRAY){ return; }
	
	// Override certain special content (navigation) by looping through "addField" calls from comp config file
	$nFieldCalledARRAY = array();
	
	foreach($nAllFieldARRAY AS $nFieldARRAY){
		$nFldID = $nFieldARRAY["nFldID"];
		// Special cases for fields that use the same db columns, but have different names
		$nFldIDToMatch = $nFldID;
		$nFldIDToMatch = str_replace("-ImageLibrary","",$nFldIDToMatch);
		$nFldIDToMatch = str_replace("-Section","",$nFldIDToMatch);
		$nFldIDToMatch = str_replace("-Page","",$nFldIDToMatch);
		
		if(!isset($nFieldCalledARRAY[$nFldIDToMatch])){ $nFieldCalledARRAY[$nFldIDToMatch]=1; } else { $nFieldCalledARRAY[$nFldIDToMatch]++; }
		$nTimesFldCalled = $nFieldCalledARRAY[$nFldIDToMatch];
		
		// add any custom function calls on front-end for later processing (stored as nCustFuncSite_[nFldID] to allow more than one custom function per "level")
		$nFldIDLC = strtolower($nFldID);
		if($nFieldARRAY["nCustFuncSite"]){
			$nContentARRAY[$nTimesFldCalled]["nCustFuncSite_$nFldIDLC"] = $nFieldARRAY["nCustFuncSite"];
			$nContentARRAY[$nTimesFldCalled]["nCustFuncSite_linked$nFldIDLC"] = $nFieldARRAY["nCustFuncSite"]; // available for linked items as well
		} else {
			$nContentARRAY[$nTimesFldCalled]["nCustFuncSite_$nFldIDLC"] = "";
			$nContentARRAY[$nTimesFldCalled]["nCustFuncSite_linked$nFldIDLC"] = "";
		}
		
		switch($nFieldARRAY["nFldID"]){
			case "link-Section":
				// process navigation
				$nNavPageIDARRAY = array();
				$nActiveNavPageIDARRAY = array();
				$nActiveNavSectionARRAY = array();
				if(isset($nContentARRAY[$nTimesFldCalled]["nLinkID"])){ $nFilterID = $nContentARRAY[$nTimesFldCalled]["nLinkID"]; } else { $nFilterID = ""; }
				if(!$nFilterID){ $nFilterID=0; }
				$Query = "SELECT nID FROM nPage WHERE nSectionID=$nFilterID ORDER BY nOrderID";
				mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
				while ($Row = mysql_fetch_array($Result)) {
					$nNavPageIDARRAY[] = $Row["nID"];
				}
				$nActiveNavPageIDARRAY[] = $nPageID;
				break;
			case "link":
			case "link-Page":
				// process page link
				$nContentARRAY[$nTimesFldCalled]["nLink"] = "";
				if(isset($nContentARRAY[$nTimesFldCalled]["nLinkID"])){
					if(!$nShowInEditor){
						if($nContentARRAY[$nTimesFldCalled]["nLinkID"]==-1){ // if not link to self
							$nContentARRAY[$nTimesFldCalled]["nLink"] = -1;
						} else {
							if(is_numeric($nContentARRAY[$nTimesFldCalled]["nLinkID"])){ $nContentARRAY[$nTimesFldCalled]["nLink"] = tmplGetPageLinkPath($nContentARRAY[$nTimesFldCalled]["nLinkID"]); } else { $nContentARRAY[$nTimesFldCalled]["nLink"] = $nContentARRAY[$nTimesFldCalled]["nLinkID"]; if($nContentARRAY[$nTimesFldCalled]["nLink"]){ $nContentARRAY[$nTimesFldCalled]["nLink"] = $nFullSitePath.$nContentARRAY[$nTimesFldCalled]["nLink"]; } }
						}
					} else {
						if($nContentARRAY[$nTimesFldCalled]["nLinkID"]==-1){ // if not link to self
							$nContentARRAY[$nTimesFldCalled]["nLink"] = -1;
						} else {
							if(is_numeric($nContentARRAY[$nTimesFldCalled]["nLinkID"])){ $nContentARRAY[$nTimesFldCalled]["nLink"] = tmplGetEditorPageLinkPath($nContentARRAY[$nTimesFldCalled]["nLinkID"]); } else { $nContentARRAY[$nTimesFldCalled]["nLink"] = $nContentARRAY[$nTimesFldCalled]["nLinkID"]; if($nContentARRAY[$nTimesFldCalled]["nLink"]){ $nContentARRAY[$nTimesFldCalled]["nLink"] = $nFullSitePath.$nContentARRAY[$nTimesFldCalled]["nLink"]; } }
						}
					}
				} else { $nContentARRAY[$nTimesFldCalled]["nLinkID"] = ""; $nContentARRAY[$nTimesFldCalled]["nLink"] = ""; }
				break;
		}
	}
	
	// Parse template
	do{
		$nOpenerPos = strpos($nTemplateCode,$nOpenerTag);
		$nCloserPos = strpos($nTemplateCode,$nCloserTag,$nOpenerPos);
		if($nOpenerPos!==false && $nCloserPos!==false){
			$nInnerTag = substr($nTemplateCode,($nOpenerPos+strlen($nOpenerTag)),($nCloserPos-strlen($nCloserTag)-$nOpenerPos));
			$nReplacement = "";
			$nInnerTagARRAY = explode($nTagParamDelim,$nInnerTag);
			$nTemplateItem = $nInnerTagARRAY[0];
			unset($nInnerTagARRAY[0]);
			$nNum = 0;
			
			switch($nTemplateItem){
				case "pageid":
					$nReplacement = $nPageID;
					break;
				case "compid":
					$nReplacement = $nContentID;
					break;
				case "showDateTime":
					$nReplacement = tmplGetDateTime($nTemplateItem,$nInnerTagARRAY);
					break;
				case "text":
					$nNum = nGetParam("NUM",$nInnerTagARRAY); if(!$nNum){ $nNum=1; }
					$nBefore = nGetParam("BEFORE",$nInnerTagARRAY);
					$nAfter = nGetParam("AFTER",$nInnerTagARRAY);
					if(isset($nContentARRAY[$nNum]["nText"])){ $nReplacement = $nContentARRAY[$nNum]["nText"]; } else { $nReplacement = ""; }
					if($nReplacement){ $nReplacement = "$nBefore$nReplacement$nAfter"; }
					break;
				case "textarea":
				case "rte":
					$nNum = nGetParam("NUM",$nInnerTagARRAY); if(!$nNum){ $nNum=1; }
					$nBefore = nGetParam("BEFORE",$nInnerTagARRAY);
					$nAfter = nGetParam("AFTER",$nInnerTagARRAY);
					if(isset($nContentARRAY[$nNum]["nTextarea"])){ $nReplacement = $nContentARRAY[$nNum]["nTextarea"]; } else { $nReplacement = ""; }
					if($nReplacement){ $nReplacement = "$nBefore$nReplacement$nAfter"; }
					break;
				case "linkedtext":
					$nNum = nGetParam("NUM",$nInnerTagARRAY); if(!$nNum){ $nNum=1; }
					$nLinkNum = nGetParam("LINKNUM",$nInnerTagARRAY); if(!$nLinkNum){ $nLinkNum=1; }
					$nBefore = nGetParam("BEFORE",$nInnerTagARRAY);
					$nAfter = nGetParam("AFTER",$nInnerTagARRAY);
					$nShowUnlinked = nGetParam("SHOWUNLINKED",$nInnerTagARRAY);
					if(isset($nContentARRAY[$nNum]["nText"])){ $nText = $nContentARRAY[$nNum]["nText"]; } else { $nText = ""; }
					$nNoText = nGetParam("NOTEXT",$nInnerTagARRAY);
					if(isset($nContentARRAY[$nLinkNum]["nLink"])){ $nLink = $nContentARRAY[$nLinkNum]["nLink"]; } else { $nLink = ""; }
					if($nNoText && !$nText){ $nText=$nNoText; }
					if($nLink && $nText){
						$nLinkedText = "<a href=\"$nLink\">$nText</a>";
					} else {
						if($nShowUnlinked!=="0" && $nShowUnlinked!=="false"){ $nLinkedText = $nText; }
					}
					if($nLinkedText){ $nReplacement = "$nBefore$nLinkedText$nAfter"; }
					break;
				case "linkedtextarea":
					$nNum = nGetParam("NUM",$nInnerTagARRAY); if(!$nNum){ $nNum=1; }
					$nLinkNum = nGetParam("LINKNUM",$nInnerTagARRAY); if(!$nLinkNum){ $nLinkNum=1; }
					$nBefore = nGetParam("BEFORE",$nInnerTagARRAY);
					$nAfter = nGetParam("AFTER",$nInnerTagARRAY);
					$nShowUnlinked = nGetParam("SHOWUNLINKED",$nInnerTagARRAY);
					$nText = $nContentARRAY[$nNum]["nTextarea"];
					$nNoText = nGetParam("NOTEXT",$nInnerTagARRAY);
					$nLink = $nContentARRAY[$nLinkNum]["nLink"];
					if($nNoText && !$nText){ $nText=$nNoText; }
					if($nLink && $nText){
						$nReplacement = "<a href=\"$nLink\">$nText</a>";
					} else {
						if($nShowUnlinked!=="0" && $nShowUnlinked!=="false"){ $nReplacement = $nText; }
					}
					if($nReplacement){ $nReplacement = "$nBefore$nReplacement$nAfter"; }
					break;
				case "image":
					$nNum = nGetParam("NUM",$nInnerTagARRAY); if(!$nNum){ $nNum=1; }
					$nBefore = nGetParam("BEFORE",$nInnerTagARRAY);
					$nAfter = nGetParam("AFTER",$nInnerTagARRAY);
					$nPathOnly = nGetParam("PATHONLY",$nInnerTagARRAY); // get image path only
					$nTagParams = nGetParam("PARAMS",$nInnerTagARRAY);
					$nImageID = $nContentARRAY[$nNum]["nImgID"];
					if(!$nShowInEditor){
						if($nImageID){ $nReplacement = nGetImageTagFromID($nImageID,"","","",$nPathOnly,$nTagParams); }
					} else {
						if($nImageID){ $nReplacement = nGetImageTagFromID($nImageID,"",$nMaxImgWidth,$nMaxImgHeight,"",$nTagParams); } // in editor, show a smaller image, if needed
					}
					if($nReplacement){ $nReplacement = "$nBefore$nReplacement$nAfter"; }
					break;
				case "linkedimage":
					$nNum = nGetParam("NUM",$nInnerTagARRAY); if(!$nNum){ $nNum=1; }
					$nLinkNum = nGetParam("LINKNUM",$nInnerTagARRAY); if(!$nLinkNum){ $nLinkNum=1; }
					$nBefore = nGetParam("BEFORE",$nInnerTagARRAY);
					$nAfter = nGetParam("AFTER",$nInnerTagARRAY);
					$nShowUnlinked = nGetParam("SHOWUNLINKED",$nInnerTagARRAY);
					$nTagParams = nGetParam("PARAMS",$nInnerTagARRAY);
					$nLinkParams = nGetParam("LINKPARAMS",$nInnerTagARRAY);
					if(isset($nContentARRAY[$nNum]["nImgID"])){ $nImageID = $nContentARRAY[$nNum]["nImgID"]; } else { $nImageID = ""; }
					$nAltTag = nGetParam("ALT",$nInnerTagARRAY);
					if($nAltTag=="text"){ $nAltTag = $nContentARRAY[$nNum]["nText"]; }
					$nImage = "";
					if(!$nShowInEditor){
						if($nImageID){ $nImage = nGetImageTagFromID($nImageID,"","","","",$nTagParams); }
					} else {
						if($nImageID){ $nImage = nGetImageTagFromID($nImageID,"",$nMaxImgWidth,$nMaxImgHeight,"",$nTagParams); } // in editor, show a smaller image, if needed
					}
					$nNoImage = nGetParam("NOIMAGE",$nInnerTagARRAY);
					// image link
					if(isset($nContentARRAY[$nLinkNum]["nLink"])){ $nLink = $nContentARRAY[$nLinkNum]["nLink"]; } else { $nLink = ""; }
					if($nLink==-1){ // link to self
						$nPathOnly = 1;
						$nLink = nGetImageTagFromID($nImageID,"","","",$nPathOnly,$nTagParams);
						if($nLink){ $nLink = $nFullSitePath.$nLink; }
					}
					
					if($nNoImage && !$nImage){ $nImage=$nNoImage; }
					if($nLink && $nImage){
						$nReplacement = "<a href=\"$nLink\" $nLinkParams>$nImage</a>";
					} else {
						if($nShowUnlinked!=="0" && $nShowUnlinked!=="false"){ $nReplacement = $nImage; }
					}
					if($nReplacement){ $nReplacement = "$nBefore$nReplacement$nAfter"; }
					break;
				case "link":
					$nNum = nGetParam("NUM",$nInnerTagARRAY); if(!$nNum){ $nNum=1; }
					$nBefore = nGetParam("BEFORE",$nInnerTagARRAY);
					$nAfter = nGetParam("AFTER",$nInnerTagARRAY);
					if($nNavPageIDARRAY){
						// navigation links
						$nNavCompFile = nGetParam("FILE",$nInnerTagARRAY);
						if($nNavCompFile){
							$nNavCompActiveFile = nGetParam("FILE-ACTIVE",$nInnerTagARRAY);
							$nNavCompFilePath = nGetTmplOverridePath($nNavCompFile);
							$nNavCompActiveFilePath = nGetTmplOverridePath($nNavCompActiveFile);
						}
						foreach($nNavPageIDARRAY AS $nNavPageID){
							$nPageType = nGetPageType($nNavPageID);
							if(in_array($nNavPageID,$nActiveNavPageIDARRAY) && $nNavCompActiveFile){ $nNavFilePath=$nNavCompActiveFilePath; } else { $nNavFilePath=$nNavCompFilePath; } // for active items
							if(!$nShowInEditor){
								if(file_exists($nNavFilePath)){
									$nTempCompCode = file_get_contents($nNavFilePath);
								} else {
									$nTempCompCode = "<li><a href=\"[#link#]\">[#text#]</a></li>";
								}
							} else {
								$nTempCompCode = "<li><a href=\"".tmplGetEditorPageLinkPath($nNavPageID)."\">[#text#]</a></li>";
							}
							//if($nPageType=="Search"){ $nTempCompCode = "<li>*[#compSearchBox#]*</li>"; }
							$nTempCompCode = tmplParse($nTempCompCode,$nNavPageID,"comp");
							if($nTempCompCode){ $nReplacement.= $nTempCompCode; }
						}
					} else {
						// simple link
						if(isset($nContentARRAY[$nNum]["nLink"])){ $nReplacement = $nContentARRAY[$nNum]["nLink"]; } else { $nReplacement = ""; }
					}
					if($nReplacement){ $nReplacement = "$nBefore$nReplacement$nAfter"; }
					break;
				case "text-imagelibrary":
					$nNum = nGetParam("NUM",$nInnerTagARRAY); if(!$nNum){ $nNum=1; }
					$nBefore = nGetParam("BEFORE",$nInnerTagARRAY);
					$nAfter = nGetParam("AFTER",$nInnerTagARRAY);
					$nImageFile = nGetParam("FILE",$nInnerTagARRAY);
					$nAllowEnlarge = nGetParam("ENLARGE",$nInnerTagARRAY);
					$nTagParams = nGetParam("PARAMS",$nInnerTagARRAY);
					$nLinkParams = nGetParam("LINKPARAMS",$nInnerTagARRAY);
					if($nAllowEnlarge!=="0"){ $nAllowEnlarge = 1; } // default on
					// Get file template for each image (if available)
					$nImageTmplCode = "";
					if($nImageFile){
						$nImageFilePath = nGetTmplOverridePath($nImageFile,$nTranslateLang);
						if($nImageFilePath){ $nImageTmplCode = file_get_contents($nImageFilePath); }
					}
					if(!$nImageTmplCode){
						$nImageTmplCode = "[#imageTag#]"; // default template
					}
					
					if(isset($nContentARRAY[$nNum]["nText"])){ $nLibrary = $nContentARRAY[$nNum]["nText"]; } else { $nLibrary = ""; }
					$nImageIDARRAY = array();
					$nImageIDARRAY = nGetImageIDARRAY($nLibrary);
					
					$nReplacement = "";
					if($nImageIDARRAY){
						foreach($nImageIDARRAY AS $nImageID => $nImgPath){
							$nMaxHeight = 121; // maximum height image is allowed to have
							if(file_exists("$nImgPath")){
								$nTitle = nGetImageInfoFromID($nImageID,"nTitle");
								$nCaption = nGetImageInfoFromID($nImageID,"nCaption");
								$nFilesize = filesize("$nImgPath");
								if($nFilesize){ $nFilesize = number_format(($nFilesize/1000),0,'.',''); }
								$nImgSizeARRAY = getimagesize("$nImgPath");
								$nImgW = $nImgSizeARRAY[0]; $nImgH = $nImgSizeARRAY[1]; $nResizeRatio = $nImgW/100;
								$nImageLink = "{$nFullSitePath}img_enlarge.php?id=$nImageID";
								$nFullImgPath = $nFullSitePath.$nImgPath;
								$nFullImgPath = str_replace("../","",$nFullImgPath);
								if($nImgH<$nMaxHeight){
									$nImgTag = "<img src=\"$nFullImgPath\" alt=\"\" width=\"$nImgW\" height=\"$nImgH\" border=\"0\" $nTagParams>";
								} else {
									$nImgTag = "<img src=\"$nFullImgPath\" alt=\"\" height=\"$nMaxHeight\" border=\"0\" $nTagParams>";
								}
								if($nAllowEnlarge){ $nImgTag = "<a href=\"$nImageLink\" class=\"gallery$nContentID\" title=\"$nTitle\" $nLinkParams>$nImgTag</a>"; }
								if($nResizeRatio && ($nImgH/$nResizeRatio)>100){ $nImgTag = "<div style=\"overflow:hidden; height:{$nMaxHeight}px; width:{$nMaxHeight}px; vertical-align:middle;\">$nImgTag</div>"; }
								$nImgTagCode = str_replace("[#imageTag#]",$nImgTag,$nImageTmplCode);
								$nImgTagCode = str_replace("[#imagePath#]",$nFullImgPath,$nImgTagCode);
								$nImgTagCode = str_replace("[#imageTitle#]",$nTitle,$nImgTagCode);
								
								$nTagARRAY = nGetTagArray($nImgTagCode); // [{tagname}]["tag"] holds original tag, [{tagname}]["params"]... holds param array
								
								// Image Caption
								$nBefore = $nAfter = "";
								if(isset($nTagARRAY["imageCaption"])){
									$nBefore = nGetParam("BEFORE",$nTagARRAY["imageCaption"]["params"]); 
									$nAfter = nGetParam("AFTER",$nTagARRAY["imageCaption"]["params"]);
								}
								if($nTitle && $nCaption){ $nCaption = "$nTitle. $nCaption"; }
								if($nCaption){ $nCaption = "$nBefore$nCaption$nAfter"; }
								if(isset($nTagARRAY["imageCaption"]["tag"])){
									$nImgTagCode = str_replace($nTagARRAY["imageCaption"]["tag"],$nCaption,$nImgTagCode);
								}
								
								$nReplacement.= $nImgTagCode;
							}
						}
						if($nAllowEnlarge){ $nReplacement.="<script>$(\".gallery$nContentID\").colorbox({rel:'gallery$nContentID', transition:\"fade\", opacity:0.2, maxWidth:850, initialWidth:80, initialHeight:80});</script>"; }
					}
					if($nReplacement){ $nReplacement = "$nBefore$nReplacement$nAfter"; }
					$nContentARRAY[$nNum]["nImageARRAY"] = $nImageIDARRAY; // Add image array to Content ARRAY so it's available for custom functions
					break;
				default:
					// For tags not directly modified by components, temporarily hide it so it can be parsed later
					$nReplacement = "]#".$nInnerTag."#[";
			}
			// check for custom processing function
			$nUseCustomFunction = "";
			if(!isset($nContentARRAY[$nNum]["nCustFuncSite_$nTemplateItem"])){ $nContentARRAY[$nNum]["nCustFuncSite_$nTemplateItem"] = ""; }
			if($nNum && $nContentARRAY[$nNum]["nCustFuncSite_$nTemplateItem"]){ $nUseCustomFunction = $nContentARRAY[$nNum]["nCustFuncSite_$nTemplateItem"]; }
			
			// use custom function override, if needed, else just use standard replacement
			$nFunctionName = "";
			if($nCompFileName && $nUseCustomFunction){ $nFunctionName = $nCompFileName."_".$nUseCustomFunction; }
			if($nFunctionName && function_exists($nFunctionName)){
				eval("\$nReplacement = $nFunctionName(\$nContentARRAY);");
				//echo "nTemplateItem; $nTemplateItem - nReplacements: $nReplacement<BR>";
			}
			$nTemplateCode = str_replace(($nOpenerTag.$nInnerTag.$nCloserTag),$nReplacement,$nTemplateCode);
		}
	} while($nOpenerPos!==false);
	
	// allow temporarily hidden tags to now be parsed
	$nTemplateCode = str_replace("]#","[#",$nTemplateCode);
	$nTemplateCode = str_replace("#[","#]",$nTemplateCode);
	
	$nCompCode = tmplParse($nTemplateCode);
	
	return $nCompCode;
}

// called from component files
function addField($nFldID="",$nTitle="",$nCaption="",$nDefVal="",$nFldStyle="",$nCustFuncMan="",$nCustFuncSite=""){
	global $nAllFieldARRAY;
	$nAllFieldARRAY[] = array("nFldID"=>$nFldID, "nTitle"=>$nTitle,"nCaption"=>$nCaption,"nDefVal"=>$nDefVal,"nFldStyle"=>$nFldStyle,"nCustFuncMan"=>$nCustFuncMan,"nCustFuncSite"=>$nCustFuncSite);
}

function nGetPageType($nPageID){
	global $DBName,$Link;
	if(!$nPageID){ return; }
	$nSQL = "SELECT nType FROM nPage WHERE nID=$nPageID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nType = $Row["nType"];
	}
	return $nType;
}

function nGetContentARRAY($nContentID,$nTranslateLang="",$nType="comp"){
	global $DBName,$Link,$nDefaultLang,$nSFLang;
	if(!$nContentID || !is_numeric($nContentID)){ return; }
	if(!$nTranslateLang){ $nTranslateLang = $nSFLang; }
	$nContentARRAY = array();
	$Query = "SELECT * FROM nTranslate WHERE nItemID='$nContentID' AND nLang='$nTranslateLang' AND nType='$nType'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	while($Row = mysql_fetch_array($Result)) {
		$nOrderID = $Row["nOrderID"];
		$nContentCompARRAY = array();
		$nContentCompARRAY["nText"] = stripslashes($Row["nText"]);
		$nContentCompARRAY["nTextarea"] = stripslashes($Row["nTextarea"]);
		$nContentCompARRAY["nLinkID"] = stripslashes($Row["nLinkID"]);
		$nContentCompARRAY["nImgID"] = $Row["nImgID"];
		$nContentCompARRAY["nLink"] = ""; // for later use, if needed
		// HTML conversion of any intl characters
		$nContentCompARRAY["nText"] = nConvertIntChars($nContentCompARRAY["nText"]);
		$nContentCompARRAY["nTextarea"] = nConvertIntChars($nContentCompARRAY["nTextarea"]);
		// Get default language text to fill in all content gaps
		if($nTranslateLang!=$nDefaultLang){
			$nDefContentARRAY = nGetContentARRAY($nContentID,$nDefaultLang,$nType);
			if(!$nContentCompARRAY["nText"]){ $nContentCompARRAY["nText"] = nConvertIntChars($nDefContentARRAY[$nOrderID]["nText"]); }
			if(!$nContentCompARRAY["nTextarea"]){ $nContentCompARRAY["nTextarea"] = nConvertIntChars($nDefContentARRAY[$nOrderID]["nTextarea"]); }
			if(!$nContentCompARRAY["nLinkID"]){ $nContentCompARRAY["nLinkID"] = $nDefContentARRAY[$nOrderID]["nLinkID"]; }
			if(!$nContentCompARRAY["nImgID"]){ $nContentCompARRAY["nImgID"] = $nDefContentARRAY[$nOrderID]["nImgID"]; }
		}
		// Add to main array
		$nContentARRAY[$nOrderID] = $nContentCompARRAY;
	}
	return $nContentARRAY;
}

// COMP: Search Box, optional: TRLBR
function tmplCompSearchBox($nItem,$nFullParamARRAY=""){
	global $DBName,$Link,$nSearch;
	$nNumBRs = nGetParam("TRLBR",$nFullParamARRAY);
	if($nNumBRs){ while($nNumBRs){ $nTrlBRs.="<BR>";$nNumBRs--; } }
	if($nSearch){ $nSearchValue = $nSearch; } else { $nSearchValue = "SEARCH"; }
	$nCompCode = <<<CODE
	<!-- BEGIN COMP: Search field //-->
	<form action="search.php" method="get" name="nSearchForm" id="nSearchForm" style="float:left;margin:0px;"><input type="text" name="nSearch" value="$nSearchValue" size="10" maxlength="25" class="searchInput" onFocus="clearSearch(this);" onBlur="revertSearch(this);"></form>
	<a href="javascript:document.nSearchForm.submit();"> &gt;&gt; </a>
CODE;
	return $nCompCode;
}

// COMP: Search Box, optional: TRLBR
function tmplCompSearchRes($nItem,$nFullParamARRAY=""){
	global $DBName,$Link,$xCat,$pg,$nSearchSQL,$nSearch;
	if(!$pg){ $pg=1; }
	if(!$nSearchSQL){ $nSearchSQL = nGetContentSearchSQL($nSearch); }
	// build results table
	$nShowPerPage = nGetShowPerPg();
	$nTotalRecords = nGetTotalResults($nSearch);
	$nStartRecord = nGetStartRecord();
	$nEndRecord = nGetEndRecord($nTotalRecords);
	// init vars/arrays
	$nItemARRAY = array();
	// items per row for this design
	$maxItemsPerRow = 1;
	$nLRDividerStyle = nGetParam("DIVRGHT",$nFullParamARRAY);
	$nTBDividerStyle = nGetParam("DIVBOTT",$nFullParamARRAY);
	$nCurrentProd = 1;
	if(!$nTotalRecords){ return "<div align=\"center\"><BR><BR>We're sorry...no content containing '<strong>$nSearch</strong>' found.<BR><BR>Please make sure all you search keywords are spelled correctly,<BR>or retry your search using fewer or broader keywords!<BR><BR><BR></div>"; }
	mysql_select_db($DBName); $Result = mysql_query($nSearchSQL,$Link);
	while ($Row = mysql_fetch_array($Result)) {
		if($nCurrentProd<=$nTotalRecords){
			// do only if products to show per page, and page number match
			if($nStartRecord<=$nCurrentProd && $nCurrentProd<=$nEndRecord){
				$nItemIDARRAY[] = $Row["nID"];
			}
			$nCurrentProd++;
		}
	}
	// display products, or if needed, sort them
	if($nItemIDARRAY){
		foreach($nItemIDARRAY as $nItemID){ $nItemARRAY[]="<li>".nGetContentBrief($nItemID); }
		$nCompCode = "<ol style=\"margin-left:20px;\">".implode("<BR>",$nItemARRAY)."</ol>";
	}
	// Get additional search results
	$nPageNameResults = nGetPageNameSearchRes($nSearch);
	if($nPageNameResults){ $nPageNameResults=$nPageNameResults."<BR>"; }
	if($nCompCode){ $nResHeader = "<span class=\"caption\">Your search for '<strong>$nSearch</strong>' returned <strong>$nEndRecord result(s)</strong>.</span><BR><BR>"; }
	$nCompCode = "$nResHeader $nPageNameResults <div style=\"border:1px solid #CDCDCD;padding:8px 10px 10px 10px\"><strong>Search results:</strong><BR><BR> $nCompCode<BR></div>";
	return $nCompCode;
}

function nGetContentBrief($nTranslateID){
	global $DBName,$Link;
	if(!$nTranslateID || !is_numeric($nTranslateID)){ return; }
	$Query = "SELECT nItemID,nText,nTextarea FROM nTranslate WHERE nID=$nTranslateID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	if ($Row = mysql_fetch_array($Result)) {
		$nContentID = $Row["nItemID"];
		$nText = stripslashes($Row["nText"]);
		$nTextarea = stripslashes($Row["nTextarea"]);
	}
	$nText = nConvertIntChars($nText); // HTML conversion of any intl characters
	$nTextarea = nConvertIntChars($nTextarea); // HTML conversion of any intl characters
	if($nText || $nTextarea){
		// Get link to page where content shows (yeah, it can show up on more than one page, i know, just getting first for now...)
		$nPageLinkID = nGetFirstPageIDFromContentID($nContentID);
		$nPageLinkPath = tmplGetPageLinkPath($nPageLinkID);
		if($nText){ $nText="<h2><a href=\"$nPageLinkPath\">$nText</a></h2>"; }
		$nCompCode = <<<CODE
		<div onClick="document.location.href='$nPageLinkPath'" style="cursor:hand;">$nText $nTextarea</div><BR>
CODE;
	}
	return $nCompCode;
}
function nGetFirstPageIDFromContentID($nContentID){
	global $DBName,$Link;
	if(!$nContentID || !is_numeric($nContentID)){ return; }
	$Query = "SELECT nPageID FROM xComponentPage WHERE nContentID=$nContentID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	if ($Row = mysql_fetch_array($Result)) {
		$nPageID = $Row["nPageID"];
	}
	return $nPageID;
}

function tmplGetCompLangNav($nItem,$nFullParamARRAY=""){
	global $DBName,$Link,$nSFLang,$nDefaultLang,$nUserCompPath,$nLangARRAY;
	if(count($nLangARRAY)<=1){ return; } // if only one language, just return
	$nCompFile = nGetParam("FILE",$nFullParamARRAY);
	$nCompFilePath = tmplGetPath("siteTmplPath",array("ABS=0","SSL=0"))."$nUserCompPath$nCompFile";
	if(file_exists($nCompFilePath)){ $nTempCompCode = file_get_contents($nCompFilePath); } else { return ""; }
	$nCompCode=tmplParse($nTempCompCode);
	return $nCompCode;
}

/* ------ INDIVIDUAL ITEM Template Functions ------ */

/* --- GENERAL --- */
function tmplGetPageBGColor($nItem,$nFullParamARRAY=""){
	global $DBName,$Link,$nPageID,$_GET;
	if(!$nPageID){ $nPageID=$_GET["id"]; }
	if(!$nPageID || !is_numeric($nPageID)){ return; }
	$Query = "SELECT nBGColor AS nColor FROM nPage WHERE nID=$nPageID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	if ($Row = mysql_fetch_array($Result)) {
		$nColor = $Row["nColor"];
	}
	return $nColor;
}

function tmplGetPageBGImgPath($nItem,$nFullParamARRAY=""){
	global $DBName,$Link,$nPageID,$_GET;
	if(!$nPageID){ $nPageID=$_GET["id"]; }
	if(!$nPageID || !is_numeric($nPageID)){ return; }
	$Query = "SELECT nBGImgID FROM nPage WHERE nID=$nPageID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	if ($Row = mysql_fetch_array($Result)) {
		$nBGImgID = $Row["nBGImgID"];
	}
	if($nBGImgID){ $nBGImgPath = nGetImagePathFromID($nBGImgID); }
	return $nBGImgPath;
}

function tmplGetPageBaseColor($nItem,$nFullParamARRAY=""){
	global $DBName,$Link,$nPageID,$_GET;
	if(!$nPageID){ $nPageID=$_GET["id"]; }
	if(!$nPageID || !is_numeric($nPageID)){ return; }
	$Query = "SELECT nBaseColor AS nColor FROM nPage WHERE nID=$nPageID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	if ($Row = mysql_fetch_array($Result)) {
		$nColor = $Row["nColor"];
	}
	return $nColor;
}

function tmplGetPageBackBGColor($nItem,$nFullParamARRAY=""){
	global $DBName,$Link,$nPageID,$_GET;
	if(!$nPageID){ $nPageID=$_GET["id"]; }
	if(!$nPageID || !is_numeric($nPageID)){ return; }
	$Query = "SELECT nBackBGColor AS nColor FROM nPage WHERE nID=$nPageID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	if ($Row = mysql_fetch_array($Result)) {
		$nColor = $Row["nColor"];
	}
	return $nColor;
}

function tmplGetPath($nPathToGet,$nFullParamARRAY=""){
	global $nFullSitePath,$nSSLSitePath,$nTmplPath,$nType,$_SERVER,$nCurrentTheme;
	$nUseAbsolutePath = nGetParam("ABS",$nFullParamARRAY);
	$nUseSecure = nGetParam("SSL",$nFullParamARRAY);
	$nHTTPS = (isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : NULL);
	switch($nPathToGet){
		case "sitePath": $nPath = $nFullSitePath; break;
		case "siteSSLPath": $nPath = $nSSLSitePath; break;
		case "siteTmplPath":
			if($nTmplPath){
				$nPath = "tmpl/".nRemoveFileName($nTmplPath);
			} else {
				$nPath = "tmpl/".$nCurrentTheme; // for calls from inside manager
			}
			if($nUseAbsolutePath!=="0"){
				if($nUseSecure){
					$nPath = $nSSLSitePath.$nPath;
				} else {
					if($nHTTPS=="on" && $nUseSecure!=="0"){
						$nPath = $nSSLSitePath.$nPath; //force secure abs path on secure pages
					} else {
						$nPath = $nFullSitePath.$nPath;
					}
				}
			}
			break;
	}
	return $nPath;
}

// Utility functions
function nGetComponentName($nRecID){
	global $DBName,$Link;
	if(!$nRecID){ return; }
	$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 nGetContentSearchResultsARRAY($nSearch){
	global $DBName,$Link,$nDefaultLang,$nSFLang;
	if(!$nSearch){ return; }
	if($nSFLang){ $nLangClause = "AND nLang='$nSFLang' AND nType='comp'"; }
	$nPageIDResultsARRAY = array(); // holds pure results
	$nPageIDRelevanceARRAY = array(); // holds results (key) with relevance (value).. higher # = higher relevance
	$nSearchFieldsARRAY = array("nText","nTextarea");
	// SEARCH exact phrase (strict)
	$where_clauses = array();
	foreach($nSearchFieldsARRAY AS $nSearchField){ $where_clauses[] = "$nSearchField regexp '{$nSearch}'"; }
	$where_clause = " WHERE (" . join ("\n   OR ", $where_clauses).")";
	$Query = "SELECT nID FROM nTranslate $where_clause $nLangClause";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	$nTotalResults = mysql_num_rows($Result);
	while ($Row = mysql_fetch_array($Result)) {
		$nID = $Row["nID"]; $nPageIDResultsARRAY[] = $nID;
		if(array_key_exists($nID,$nPageIDRelevanceARRAY)){ $nPageIDRelevanceARRAY[$nID]++; } else { $nPageIDRelevanceARRAY[$nID] = 1; }
	}
	// SEARCH exact phrase (liberal)
	$Query = "SELECT nID FROM nTranslate WHERE MATCH (".implode(",",$nSearchFieldsARRAY).") AGAINST('$nSearch') $nLangClause";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	$nTotalResults = mysql_num_rows($Result);
	while ($Row = mysql_fetch_array($Result)) {
		$nID = $Row["nID"]; $nPageIDResultsARRAY[] = $nID;
		if(array_key_exists($nID,$nPageIDRelevanceARRAY)){ $nPageIDRelevanceARRAY[$nID]++; } else { $nPageIDRelevanceARRAY[$nID] = 1; }
	}
	// SEARCH by individual word (strict)
	$nSearchTermARRAY = array();
	$nSearchTermARRAY = explode(" ",$nSearch);  // split on whitespace
	foreach ($nSearchTermARRAY as $term){
	    $Query = "SELECT nID FROM nTranslate WHERE MATCH (".implode(",",$nSearchFieldsARRAY).") AGAINST('$term') $nLangClause";
		mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
		$nTotalResults = mysql_num_rows($Result);
		while ($Row = mysql_fetch_array($Result)) {
			$nID = $Row["nID"]; $nPageIDResultsARRAY[] = $nID;
			if(array_key_exists($nID,$nPageIDRelevanceARRAY)){ $nPageIDRelevanceARRAY[$nID]++; } else { $nPageIDRelevanceARRAY[$nID] = 1; }
		}
	}
	// SEARCH by individual word (liberal)
	$nSearchTermARRAY = array();
	$nSearchTermARRAY = explode(" ",$nSearch);  // split on whitespace
	foreach ($nSearchTermARRAY as $term){
	    $where_clauses = array();
		foreach($nSearchFieldsARRAY AS $nSearchField){ $where_clauses[] = "$nSearchField regexp '{$term}'"; }
		$where_clause = " WHERE (" . join ("\n   OR ", $where_clauses).")";
		$Query = "SELECT nID FROM nTranslate $where_clause $nLangClause";
		mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
		$nTotalResults = mysql_num_rows($Result);
		while ($Row = mysql_fetch_array($Result)) {
			$nID = $Row["nID"]; $nPageIDResultsARRAY[] = $nID;
			if(array_key_exists($nID,$nPageIDRelevanceARRAY)){ $nPageIDRelevanceARRAY[$nID]++; } else { $nPageIDRelevanceARRAY[$nID] = 1; }
		}
	}
	// SEARCH by individual word (VERY liberal)
	$terms = preg_split("/\s+/", $nSearch);  // split on whitespace
	$where_clauses = array();
	foreach ($terms as $term){
	    $where_clauses = array();
		foreach($nSearchFieldsARRAY AS $nSearchField){ $where_clauses[] = "$nSearchField LIKE '%{$term}%'"; }
	}
	$where_clause = " WHERE (" . join ("\n   OR ", $where_clauses).")";
	$Query = "SELECT nID FROM nTranslate $where_clause $nLangClause";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	$nTotalResults = mysql_num_rows($Result);
	while ($Row = mysql_fetch_array($Result)) {
		$nID = $Row["nID"]; $nPageIDResultsARRAY[] = $nID;
		if(array_key_exists($nID,$nPageIDRelevanceARRAY)){ $nPageIDRelevanceARRAY[$nID]++; } else { $nPageIDRelevanceARRAY[$nID] = 1; }
	}
	// final sorting
	arsort($nPageIDRelevanceARRAY,SORT_NUMERIC);
	return $nPageIDRelevanceARRAY;
}
function nGetPageNameSearchRes($nSearch){
	global $DBName,$Link,$nSFLang,$nDefaultLang;
	if(!$nSearch){ return ""; }
	
	if($nSFLang){ $nLangClause = "AND nLang='$nSFLang' AND nType='page'"; }
	$nCurrRow=1;
	$nColumnAmount=3;
	$nWidthPercent = round(100/$nColumnAmount);
	$nTable = "";
	$nPageIDFoundARRAY = array();
	
	$Query = "SELECT nID,nItemID,nText FROM nTranslate WHERE (nText LIKE '%".$nSearch."%') $nLangClause";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	$nTotalResults = mysql_num_rows($Result);
	while ($Row = mysql_fetch_array($Result)) {
		if($nCurrRow==1){ $nTable .= "<tr>"; }
		$nID = $Row["nID"];
		$nPageID = $Row["nItemID"];
		$nText = nConvertIntChars($Row["nText"]);
		$nPageLinkPath = tmplGetPageLinkPath($nPageID);
		$nTable .= "<td width=\"$nWidthPercent%\" valign=\"top\" class=\"content\" style=\"padding-right:10px;\"><ul><li><a href=\"$nPageLinkPath\">$nText</a></ul></td>";
		if ($nColumnAmount == $nCurrRow) { $nTable.="</tr>";$nCurrRow=1; } else { $nCurrRow++; }
	}
	// Open table
	$nOpener=<<<CODE
<div style="border:1px solid #CDCDCD;padding:8px 10px 10px 10px">
	<table width="88%" border="0" cellspacing="0" cellpadding="0">
	  <tr><td colspan="$nColumnAmount" class="content" style="padding-bottom:12px "><b>Full pages matching your search:</b></td></tr>
CODE;
	// Close table
	$nCloser="</tr></table></div>";
	if($nTable){ $nTable="$nOpener$nTable$nCloser"; }
	return $nTable;
}
function nGetContentSearchSQL($nSearch){
	global $DBName,$Link,$nDefaultLang,$nSFLang;
	if($nSFLang){ $nLangClause = "AND nLang='$nSFLang' AND nType='comp'"; }
	$nSearchResultsARRAY = nGetContentSearchResultsARRAY($nSearch); // returns ID (key) with relevance (value), ordered by highest relevance
	if($nSearchResultsARRAY){ foreach($nSearchResultsARRAY as $key => $item ){ $nFinalSearchResultsARRAY[]=$key; } } else { return; }// move keys to values
	$nOrderByList = "ORDER BY "; // Get correct order output (next 3 lines)
	if($nFinalSearchResultsARRAY){ foreach($nFinalSearchResultsARRAY as $nContentID){ $nOrderByList .= "nID=$nContentID DESC, ";  } } else { return; }
	$nOrderByList = rtrim($nOrderByList,", ");
	$Query = "SELECT nID FROM nTranslate WHERE nID IN (".implode(",",$nFinalSearchResultsARRAY).") $nLangClause $nOrderByList";
	return $Query;
}
function nGetTotalResults($nSearch){
	global $DBName,$Link;
	// Get total number of items
	$nTotalItems = 0;
	$nIDsAlreadyUsed = "";
	$nSearchSQL = nGetContentSearchSQL($nSearch);
	if(!$nSearchSQL){ return 0; }
	mysql_select_db($DBName); $Result = mysql_query($nSearchSQL,$Link);
	while ($Row = mysql_fetch_array($Result)) {
		$nTotalItems++;
		$nID = $Row["nID"];
		if($nIDsAlreadyUsed!=""){ $nIDsAlreadyUsed .= ",$nID"; } else { $nIDsAlreadyUsed = "$nID"; }
	}
	return $nTotalItems;
}
function nGetStartRecord(){
	global $DBName,$Link,$pg;
	$nShowPerPage = nGetShowPerPg();
	$nStartRecord = ($nShowPerPage*($pg-1))+1;
	return $nStartRecord;
}
function nGetEndRecord($nTotalRecords){
	global $DBName,$Link,$pg;
	$nShowPerPage = nGetShowPerPg();
	$nEndRecord = $nShowPerPage*$pg;
	// Return smaller of the two
	if ($nEndRecord>$nTotalRecords){return $nTotalRecords;} else {return $nEndRecord;}
}
function nGetShowPerPg(){
	return 20;
}
function nGetImageTagFromID($nImgID,$nAltTag="",$nMaxWidth="",$nMaxHeight="",$nPathOnly=false,$nTagParams=""){
	global $DBName,$Link,$nJSOnloadARRAY;
	//if(!$nImgID){ return 0; }
	if($nPathOnly){ $nPathOnly = true; } else { $nPathOnly = false; }
	$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,$nTagParams);
		if($nPathOnly){ return $nPath; }
		if($nPathOver){ $nJSOnloadARRAY[]="new Rollover('img$nImgID');"; }
		return $nImgTag;
	} else {
		return "$nPath";
	}
}
function nGetImagePathFromID($nImgID){
	global $DBName,$Link;
	$nSQL = "SELECT nPath 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"];
	}
	if(!file_exists($nPath)){ $nPath = "../$nPath"; }
	if(!file_exists($nPath)){ $nPath = "../$nPath"; }
	return $nPath;
}
function nGetImageInfoFromID($nImgID,$nData="nTitle"){
	global $DBName,$Link;
	$nSQL = "SELECT $nData AS nData FROM nImage WHERE nID='$nImgID' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nData = $Row["nData"];
	}
	return $nData;
}
function nGetImgTag($nImgFile,$nAltTag="",$nMaxWidth="",$nMaxHeight="",$nTagParams=""){
	$nSitePath = tmplGetPath("sitePath");
	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 = $nSitePath.$nImgFile;
	$nFinalPath = str_replace("../","",$nFinalPath);
	$nTag = "<img src=\"$nFinalPath\" alt=\"$nAltTag\" $nImgTagWH border=\"0\" $nTagParams>";
	return $nTag;
}
















function tmplGetButtonPath($nButtonToGet,$nFullParamARRAY=""){
	global $nSFLang;
	if(!$nButtonToGet){ return; }
	$nTemplatePath = tmplGetPath("siteTmplPath");
	$nNonSSLTemplatePath = tmplGetPath("siteTmplPath",array("ABS=0","SSL=0"));
	// internationalization
	$nIntlButtonPath = $nTemplatePath."buttons/".$nSFLang."/".$nButtonToGet;
	$nNonSSLButtonPath = $nNonSSLTemplatePath."buttons/".$nSFLang."/".$nButtonToGet;
	$nDefaultButtonPath = $nTemplatePath."buttons/".$nButtonToGet;
	if(file_exists("$nNonSSLButtonPath")){ $nButtonPath = "$nIntlButtonPath"; } else {  $nButtonPath = "$nDefaultButtonPath";}
	return $nButtonPath;
}

function tmplGetClickPath($nItem,$nFullParamARRAY=""){
	global $DBName,$Link,$nType,$_GET;
	global $nFullSitePath;
	$nPathDelim = "&raquo;";
	$nMaxWords = nGetParam("WRD",$nFullParamARRAY);
	$nPageTitle = tmplGetPageName($nItem);
	// if category or product, get parent...
	if($nType===0 || $nType==10){
		if(!$nCatID){ $nCatID=$_GET["xCat"]; }
		if(!$nCatID || !is_numeric($nCatID)){ return; }
		if($nCatID){
			if($nType===0){
				$Query = "SELECT nParent AS nParent FROM nCatInfo WHERE nID=$nCatID LIMIT 1";
				mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
				if($Row = mysql_fetch_array($Result)){
					$nParentID = $Row["nParent"];
				}
			}
			if($nType==10){ $nParentID = $nCatID; }
			if($nParentID){
				$nParentName = tmplGetPageName($nParentID);
				$nParentLink = tmplGetPageLinkPath($nParentID);
				if($nMaxWords){
					$nMaxChars = $nMaxWords*6; // limit characters based on avg word size
					$nParentName = nTruncateText($nParentName,$nMaxWords,$nMaxChars);
				}
				$nParent = "<a href=\"$nParentLink\"$nClass>$nParentName</a> $nPathDelim";
			}
		}
	}
	$nClass = nGetParam("CLASS",$nFullParamARRAY);
	if($nClass){ $nClass = " class=\"$nClass\""; }
	// Setup links
	$nHomeLink = tmplGetLink("linkHome");
	$wordHome = tmplGetWord("wordHome");
	$nClickPath = "<a href=\"$nHomeLink\"$nClass>$wordHome</a> $nPathDelim $nParent $nPageTitle";
	if($nClass){ $nClickPath = "<span$nClass>$nClickPath</span>"; }
	return $nClickPath;
}

function tmplGetLinkCustomPage($nLinkToGet,$nFullParamARRAY=""){
	global $nFullSitePath,$nSSLSitePath;
	$nCode = strtolower(nGetParam("ID",$nFullParamARRAY));
	$nPageName = nGetParam("NAME",$nFullParamARRAY);
	$nLink = "page.php?id=$nCode&pg=$nPageName";
	$nUseSecure = nGetParam("SSL",$nFullParamARRAY);
	if($nUseSecure){ return $nSSLSitePath.$nLink; }
	$nLink = $nFullSitePath.$nLink;
	return $nLink;
}

function tmplGetWord($nWordToGet,$nFullParamARRAY=""){
	global $wordLanguage,$wordHome;
	
	switch($nWordToGet){
		case "wordLanguage": $nWord=$wordLanguage; break;
		case "wordHome": $nWord=$wordHome; break;
	}
	$nWord = nConvertIntChars($nWord); // HTML conversion of any intl characters
	return $nWord;
}

function tmplGetLink($nLinkToGet,$nFullParamARRAY=""){
	global $nFullSitePath,$nSSLSitePath;
	switch($nLinkToGet){
		case "linkHome": return $nFullSitePath; break;
		case "linkCart": $nLink = "cart.php?nReferrer=$nThisPage"; break;
		case "linkAccount": $nLink = "welcome.php"; $nUseSecure=1; break;
		case "linkContact": $nLink = "contact.php"; break;
		case "linkProdNew": $nLink = "catnew.php"; break;
		case "linkProdSale": $nLink = "catsale.php"; break;
		case "linkProdBest": $nLink = "catbest.php"; break;
		case "linkPrivacy": $nLink = "privacy.php"; break;
		case "linkTerms": $nLink = "terms.php"; break;
		case "linkShipping": $nLink = "shipping.php"; break;
		case "linkAbout": $nLink = "about_us.php"; break;
		case "linkFriends": $nLink = "friends.php"; break;
		case "linkTestimonials": $nLink = "testimonials.php"; break;
		case "linkLogin": $nLink = "customer_login.php"; $nUseSecure=1; break;
		case "linkLogout": $nLink = "process_logout.php"; break;
	}
	if(!$nUseSecure){ $nUseSecure = nGetParam("SSL",$nFullParamARRAY); }
	if($nUseSecure){ return $nSSLSitePath.$nLink; }
	$nLink = $nFullSitePath.$nLink;
	return $nLink;
}

function tmplGetSiteName($nLinkToGet,$nFullParamARRAY=""){
	global $nSettingsARRAY;
	$nSiteName = $nSettingsARRAY["siteName"];
	return $nSiteName;
}

function tmplGetSiteTitle($nLinkToGet,$nFullParamARRAY=""){
	global $nSettingsARRAY;
	$nSiteTitle = $nSettingsARRAY["coName"];
	return $nSiteTitle;
}

function tmplGetDateTime($nLinkToGet,$nFullParamARRAY=""){
	$nFormat = nGetParam("FORMAT",$nFullParamARRAY);
	$nTimeZoneOverride = nGetParam("TIMEZONE",$nFullParamARRAY);
	if($nTimeZoneOverride){ date_default_timezone_set($nTimeZoneOverride); }
	if(!$nFormat){ $nFormat = "standard"; } //default
	switch($nFormat){
		case "year": $nDateTime = date("Y"); break;
		case "standard": $nDateTime = date("n/j/y"); break;
		case "fullText": $nDateTime = date("l, F dS, Y"); break;
		case "time": $nDateTime = date("h:i:sA"); break;
		default: $nDateTime = date("$nFormat"); break;
	}
	return $nDateTime;
}

/* --- SEARCH --- */

function tmplGetSearchItem($nSearchItem,$nFullParamARRAY=""){
	global $nFullSitePath,$nSearch;
	$nSearchFieldClass = nGetParam("CLASS",$nFullParamARRAY);
	switch($nSearchItem){
		case "searchFormOpen":
			$nSearchPath = $nFullSitePath."search.php";
			$nSearchCode="<form action=\"$nSearchPath\" method=\"get\" name=\"nSearchForm\" id=\"nSearchForm\" style=\"margin:0px;\">";
			break;
		case "searchFormClose": $nSearchCode="</form>"; break;
		case "searchField":
			$nSearchCode="<input type=\"text\" name=\"nSearch\" value=\"$nSearch\" name=\"nSearch\" maxlength=\"50\" class=\"$nSearchFieldClass\">";
			break;
	}
	return $nSearchCode;
}

/* --- MINI STUFF --- */
function tmplGetMiniCart($nItem,$nFullParamARRAY=""){
	global $nMemCartFormat,$nCurrencyFormat,$nCurrencyDecPt,$nCurrencyThousSep;
	$wordItems = strtolower(tmplGetWord("wordItems"));
	$wordItem = strtolower(tmplGetWord("wordItem"));
	$nIsAjaxCall = nGetParam("AJAXCALL",$nFullParamARRAY);
	
	$nProdAmount = nGetCartProdsAmount();
	$nCartTotal = nGetCartTotal();
	// format curreny (internationalization)
	$nCartTotalCurr = number_format($nCartTotal, 2, $nCurrencyDecPt, $nCurrencyThousSep);
	$nCartTotalText = str_replace("[nPrice]",$nCartTotalCurr,$nCurrencyFormat);
	if(!$nMemCartFormat){
		$nFormat = nGetParam("FORMAT",$nFullParamARRAY);
		if(!$nFormat){ $nFormat="standard"; } // Default format
		$nMemCartFormat = $nFormat; // memorize cart format for later calls to this function with format (i.e. AJAX)
	} else {
		$nFormat = $nMemCartFormat;
	}
	if($nProdAmount==1){ $nItemAmountText = $wordItem; } else { $nItemAmountText = $wordItems; }
	switch($nFormat){
		case "slim":
			$nMiniCartCode = "$nProdAmount $nItemAmountText, $nCartTotalText";
			break;
		case "standard":
			$nMiniCartCode = "$nProdAmount $nItemAmountText, Total: $nCartTotalText";
			break;
	}
	if(!$nIsAjaxCall){ $nMiniCartCode="<span id=\"ajaxMinicart\" style=\"position:relative\">$nMiniCartCode</span>"; } //if not a call from Ajax itself, set a ID for this minicart (for Ajax to use)
	return $nMiniCartCode;
}

function tmplGetAcceptCCImg($nItem,$nFullParamARRAY=""){
	global $DBName,$Link;
	$nUseAbsolutePath = nGetParam("ABS",$nFullParamARRAY);
	if($nUseAbsolutePath!=="0"){ $nHomeLink = tmplGetLink("linkHome"); }
	$Query = "SELECT * FROM nCartPrefs";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	if ($Row = mysql_fetch_array($Result)) {
		if($Row["nAcceptVisa"]){ $nVisa="<td><img src=\"$nHomeLink/img/accept_visa.gif\" alt=\"Proudly accepting Visa&reg; cards\" width=\"27\" height=\"17\" border=\"0\" style=\"margin-right: 2px;\"></td>"; }
		if($Row["nAcceptMC"]){ $nMC="<td><img src=\"$nHomeLink/img/accept_mc.gif\" alt=\"Proudly accepting MasterCard&reg;\" width=\"27\" height=\"17\" border=\"0\" style=\"margin-right: 2px;\"></td>"; }
		if($Row["nAcceptAmex"]){ $nAmex="<td><img src=\"$nHomeLink/img/accept_amex.gif\" alt=\"Proudly accepting American Express&reg; Cards\" width=\"27\" height=\"17\" border=\"0\" style=\"margin-right: 2px;\"></td>"; }
		if($Row["nAcceptDiscover"]){ $nDiscover="<td><img src=\"$nHomeLink/img/accept_disc.gif\" alt=\"Proudly accepting Discover&reg; Card\" width=\"27\" height=\"17\" border=\"0\" style=\"margin-right: 2px;\"></td>"; }
		if($Row["nAcceptPaypal"]){ $nPaypal="<td><img src=\"$nHomeLink/img/accept_paypal.gif\" alt=\"Proudly accepting payments through PayPal&reg;\" width=\"50\" height=\"17\" border=\"0\" style=\"margin-right: 2px;\"></td>"; }
	}
	$nCCImgCode = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr>$nVisa$nMC$nAmex$nDiscover$nPaypal</tr></table>";
	return $nCCImgCode;
}

function tmplGetMiniLogin($nItem,$nFullParamARRAY=""){
	global $nFullSitePath,$nSSLSitePath,$_SESSION;
	$wordLogin = tmplGetWord("wordLogin");
	
	$nCustUser = $_SESSION["nSessValidCust"];
	$nCustName = $_SESSION["nSessName"];
	$nUseAcctLink = 1;
	if($nCustUser=="Guest"){ $nUseAcctLink = 0; }
	if($nCustName && strlen($nCustName)>10){ $nCustName = substr($nCustName,0,8)."..."; }
	$nFormat = nGetParam("FORMAT",$nFullParamARRAY);
	$nLinkAccount = tmplGetLink("linkAccount");
	$nLinkLogin = tmplGetLink("linkLogin");
	$nLinkLogout = tmplGetLink("linkLogout");
	if(!$nFormat){ $nFormat="standard"; } // Default format
	if($nUseAcctLink){ $nCustName="<a href=\"$nLinkAccount\">$nCustName</a>"; } else { $nCustName="$nCustName"; }
	switch($nFormat){
		case "slim":
			$nLoggedInCode = $nCustName."&nbsp;&nbsp;|&nbsp;&nbsp;<a href=\"$nLinkLogout\">Logout</a>";
		  	$nLoggedOutCode = "<a href=\"$nLinkLogin\">$wordLogin</a>";
			break;
		case "standard":
			$nLoggedInCode = "Currently logged in as:<BR>$nCustName | <a href=\"$nLinkLogout\">Logout</a>";
		  	$nLoggedOutCode = "Not logged in: <a href=\"$nLinkLogin\">$wordLogin</a>";
			break;
	}
	if($nCustUser){ $nMiniLoginCode = $nLoggedInCode; } else { $nMiniLoginCode = $nLoggedOutCode; }
	return $nMiniLoginCode;
}

function tmplGetLangChange($nItem,$nFullParamARRAY=""){
	global $nThisPage,$nFullSitePath,$nSSLSitePath,$nSFLang,$_SERVER,$nPageID,$nLangARRAY;
	// Get homepage path
	//if($_SERVER['HTTPS']==="on"){ $nSitePath=$nSSLSitePath; } else { $nSitePath=$nFullSitePath; }
	//if(strpos($nThisPage,$nSitePath)===false){ $nPagePath = $nSitePath.$nThisPage; }
	//$nPagePath = str_replace("~~","?",$nPagePath);
	//$nPagePath = str_replace("~","&",$nPagePath);
	// Get this page path
	// $nPagePath = $_SERVER["REQUEST_URI"]; // removed in place of language-specific URL path added in next loop
	// create HTML (drop out currently selected language, not needed)
	foreach($nLangARRAY as $nLangCode => $nLangName){
		if($nLangCode!=$nSFLang){
			$nPagePath = tmplGetPageLinkPath($nPageID,array("LANG=$nLangCode"));
			if($nPagePath){
				if(strpos($nPagePath,"?")!==false){ $nPagePath.="&sfl=$nLangCode"; } else { $nPagePath.="?sfl=$nLangCode"; }
				$nLangCodeARRAY[]="<a href=\"$nPagePath\">$nLangName</a>";
			}
		}
	}
	$nFormat = nGetParam("FORMAT",$nFullParamARRAY);
	if(!$nFormat){ $nFormat="standard"; } // Default format
	switch($nFormat){
		case "slim":
			$nLangCode = implode("&nbsp;&nbsp;|&nbsp;&nbsp;",$nLangCodeARRAY);
			break;
		case "standard":
			$nLangCode = implode("<BR>",$nLangCodeARRAY);
			break;
		case "full":
			$nLangCode = implode("&nbsp;&nbsp;|&nbsp;&nbsp;",$nLangCodeARRAY);
			$nLangCode = tmplGetWord("wordLanguage").": $nLangCode";
			break;
	}
	return $nLangCode;
}

// Returns page name based on any array of parameters passed in
function tmplGetPageName($nPID,$nFullParamARRAY=""){
	global $DBName,$Link,$nDefaultLang,$nSFLang,$nPageID;
	if(!$nPID){ $nPID=$nPageID; }
	if(!$nPID || !is_numeric($nPID)){ return; }
	$Query = "SELECT nNavTitle FROM nPage WHERE nID=$nPID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	if ($Row = mysql_fetch_array($Result)) {
		$nPageName = $Row["nNavTitle"];
	}
	$nPageName = stripslashes($nPageName);
	$nPageName = str_replace("\"","&quot;",$nPageName);
	$nMaxWords = nGetParam("WRD",$nFullParamARRAY);
	if($nMaxWords){
		$nMaxChars = $nMaxWords*6; // limit characters based on avg word size
		$nPageName = nTruncateText($nPageName,$nMaxWords,$nMaxChars);
	}
	
	$nTranslateType="page"; $nTranslateID=$nPID;
	// if translation is needed...
	$nTranslateLang = nGetParam("LANG",$nFullParamARRAY); // override translation language
	if(!$nTranslateLang){ $nTranslateLang = $nSFLang; } // if no override, use session language
	$nTranslation = nGetTranslation($nTranslateLang,$nTranslateID,"nText",$nTranslateType);
	if($nTranslation){ $nPageName = $nTranslation; }
	
	$nPageName = nConvertIntChars($nPageName); // HTML conversion of any intl characters
	return $nPageName;
}

// Returns page link path based on any array of parameters passed in
function tmplGetPageLinkPath($nPageID,$nFullParamARRAY=""){
	global $DBName,$Link,$nDefaultLang,$nSFLang,$nPermalinks,$nForceMobile;
	global $nFullSitePath;
	if(!$nPageID){ return; }
	
	$nSQL = "SELECT nType,nTitle,nNavTitle FROM nPage WHERE nID=$nPageID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nType = $Row["nType"];
		$nTitle = $Row["nTitle"];
		$nNavTitle = $Row["nNavTitle"];
	}
	
	// Mobile version override
	$nForceMobileLink = $nForceMobile;
	$nForceMobileOverride = nGetParam("MOBILE",$nFullParamARRAY); // override force mobile
	if($nForceMobileOverride || $nForceMobileOverride===0){ $nForceMobileLink = $nForceMobileOverride; }
	
	$nTranslateType="page"; $nTranslateID=$nPageID;
	// if translation is needed...
	$nTranslateLang = nGetParam("LANG",$nFullParamARRAY); // override translation language
	if(!$nTranslateLang){ $nTranslateLang = $nSFLang; } // if no override, use session language
	$nTranslation = nGetTranslation($nTranslateLang,$nTranslateID,"nText",$nTranslateType);
	if($nTranslation){ $nNavTitle = $nTranslation; }
	
	switch($nType){
		case "Homepage": if(!$nForceMobileLink){ $nPagePath = $nFullSitePath; } else { $nPagePath = $nFullSitePath."?&m=1"; } break;
		case "Search": $nPagePath = $nFullSitePath."search.php"; break;
		case "Link":
			// get link extension
			$nLinkInfo = pathinfo($nTitle);
			if(isset($nLinkInfo["extension"])){ $nLinkExt = strtolower($nLinkInfo["extension"]); } else { $nLinkExt = ""; }
			$nSitePathARRAY = parse_url($nFullSitePath);
			$nLinkARRAY = parse_url($nTitle);
			// if the link is external or to a PDF, open in new window
			if(isExternalLink($nTitle) || $nLinkExt=="pdf"){
				$nPagePath = $nTitle."\" target=\"newWin\" onclick=\"PopUp(this.href,this.target,800,600,1);";
			} else {
				$nPagePath = $nTitle;
			}
			break;
		default:
			if($nPermalinks && !$nForceMobileLink){
				$nPageNameForPath = nPrepareNameForPath($nNavTitle); // for mod-rewrite
				$nPagePath = $nPageID."/".$nPageNameForPath.".html"; // for mod-rewrite
				$nPagePath = $nFullSitePath.$nPagePath;
			} else {
				if(!$nForceMobileLink){ $nPagePath = $nFullSitePath.strtolower($nType).".php?id=$nPageID"; } else { $nPagePath = $nFullSitePath.strtolower($nType).".php?id=$nPageID&m=1"; }
			}
			break;
	}
	return $nPagePath;
}
function tmplGetEditorPageLinkPath($nPageID,$nFullParamARRAY=""){
	global $DBName,$Link,$nDefaultLang,$nSFLang,$nPermalinks;
	global $nFullSitePath;
	if(!$nPageID){ return; }
	
	$nSQL = "SELECT nType,nTitle,nNavTitle FROM nPage WHERE nID=$nPageID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nType = $Row["nType"];
		$nTitle = $Row["nTitle"];
		$nNavTitle = $Row["nNavTitle"];
	}
	
	$nTranslateType="page"; $nTranslateID=$nPageID;
	// if translation is needed...
	$nTranslateLang = nGetParam("LANG",$nFullParamARRAY); // override translation language
	if(!$nTranslateLang){ $nTranslateLang = $nSFLang; } // if no override, use session language
	$nTranslation = nGetTranslation($nTranslateLang,$nTranslateID,"nText",$nTranslateType);
	if($nTranslation){ $nNavTitle = $nTranslation; }
	
	switch($nType){
		case "Link":
			// get link extension
			$nLinkInfo = pathinfo($nTitle);
			if(isset($nLinkInfo["extension"])){ $nLinkExt = strtolower($nLinkInfo["extension"]); } else { $nLinkExt = ""; }
			$nSitePathARRAY = parse_url($nFullSitePath);
			$nLinkARRAY = parse_url($nTitle);
			// if the link is external or to a PDF, open in new window
			if(isExternalLink($nTitle) || $nLinkExt=="pdf"){
				$nPagePath = $nTitle."\" target=\"newWin\" onclick=\"PopUp(this.href,this.target,800,600,1);";
			} else {
				$nPagePath = $nTitle;
			}
			break;
				case "Homepage":
		default:
			$nPagePath = "../manage/page_edit.php?id=$nPageID";
			break;
	}
	return $nPagePath;
}

/* ------ OTHER Needed Functions ------ */

function nGetParam($nParamToGet,$nFullParamARRAY){
	$nParamValue = "";
	if($nFullParamARRAY){
		foreach($nFullParamARRAY as $nParam) {
			$nParamARRAY = explode("=",$nParam,2); // explode, just getting the first '=' in array so user can add their own in params and not mess things up
			if($nParamARRAY[0]==$nParamToGet){ $nParamValue = $nParamARRAY[1]; }
		}
	}
	return $nParamValue;
}
function nGetFileName($nPath){
	$nPathARRAY = explode("/",$nPath);
	// make a duplicate of the last array item
	$nFileName = array_pop($nPathARRAY);
	return $nFileName;
}
function nRemoveFileName($nPath){
	$nPathARRAY = explode("/",$nPath);
	// make a duplicate of the last array item
	$nFileName = array_pop($nPathARRAY);
	$nPath = implode("/",$nPathARRAY);
	if(!$nPath){ return; }
	return $nPath."/";
}
function nGetRecPerPage(){
	global $DBName,$Link;
	$Query = "SELECT nShowPerPage FROM nCatPrefs";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	$Row = mysql_fetch_array($Result);
	return $Row["nShowPerPage"];
}
function nTableizeArray($nArrayToProcess,$nColumnAmount="",$nLRDividerStyle="",$nTBDividerStyle=""){
	if(!$nArrayToProcess){ return; }
	$nHeader = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"$nTBDividerStyle\">";
	$nFooter = "</table>";
	$nItemAmount = count($nArrayToProcess);
	if(!$nColumnAmount){ $nColumnAmount=3; } //default
	$nAmountPerColumn = round($nItemAmount/$nColumnAmount);
	$nWidthPercent = round(100/$nColumnAmount);
	if($nItemAmount<$nColumnAmount){ $nAmountPerColumn=1; }
	$nCurrRow=1;
	foreach ($nArrayToProcess as $nItem) {
		if($nCurrRow==1){ $nTable.="$nHeader<tr>"; }
		if($nCurrRow<$nColumnAmount){ $LRStyle = $nLRDividerStyle; } else { $LRStyle = ""; }
		$nTable.="<td width=\"$nWidthPercent%\" valign=\"top\" style=\"$LRStyle\">$nItem</td>";
		if ($nColumnAmount == $nCurrRow) { $nTable.="</tr>$nFooter";$nCurrRow=1; } else { $nCurrRow++; }
	}
	if($nCurrRow!=1){
		// fill in final cells if table is unfinished
		while($nColumnAmount>=$nCurrRow){
			$nTable.="<td width=\"$nWidthPercent%\">&nbsp;</td>";
			if ($nColumnAmount == $nCurrRow) { $nTable.="</tr>$nFooter"; }
			$nCurrRow++;
		}
	}
	return $nTable;
}
// Receives text string, returns formatted string (unspecified HTML removed, HTML line breaks added, optional: double spacing converted to single)
function nMakePresentable($nTextToFormat,$nAllowDoubleSpacing="1",$nRemoveCR="1",$nConvertNewLineToBR="1"){
	$nAllowedTags = "<h1><h2><h3><h4><h5><h6><strong><em><b><i><a><ul><li><pre><hr><blockquote><img><div><p><table><tr><td><br><span><font><object><embed><script>";
	$nFormattedText = strip_tags(stripslashes($nTextToFormat),$nAllowedTags);
	if($nRemoveCR){ $nFormattedText = str_replace("\r","",$nFormattedText); } else { $nFormattedText = str_replace("\r","<BR>",$nFormattedText); }
	if($nConvertNewLineToBR){ $nFormattedText = str_replace("\n","<BR>",$nFormattedText); }
	if(!$nAllowDoubleSpacing){ $nFormattedText = str_replace("<BR><BR>","<BR>",$nFormattedText); }
	return $nFormattedText;
}
// Receives text string, returns truncated string (allows only x words, with max. y chars, truncates rest and adds closer)
function nTruncateText($nTextToTruncate,$nWordCountAllowed,$nMaxChars,$nCloser="..."){
	$nWordCount = 0;
	$nTruncatedText = $nTextToTruncate;
	$nAddCloser=0;
	if(strlen($nTruncatedText)>$nMaxChars){
		$nTruncatedText = trim(substr($nTruncatedText,0,$nMaxChars));
		$nAddCloser=1;
	}
	$nTextARRAY = explode(" ",$nTruncatedText);
	if(count($nTextARRAY)>$nWordCountAllowed){
		$nTruncatedText="";
		foreach($nTextARRAY as $nWord){
			$nWordCount++;
			if($nWordCount<=$nWordCountAllowed){
				$nTruncatedText.="$nWord ";
			}
		}
		$nAddCloser=1;
	}
	if($nAddCloser){ $nTruncatedText.=$nCloser; }
	return $nTruncatedText;
}

function parseDynamicFile($nFile){
	ob_start();
	include($nFile);
	$nBuffer = ob_get_contents();
	ob_end_clean();
	$nBuffer = tmplParse($nBuffer);
	return $nBuffer;
}

$nRandNumArray = array();
function nGetRandomNum($nNum){
	global $nRandNumArray;
	// Get a random ID number for this option set, 
	// but look to see if it's already been asked for first
	// if so, then just send that back
	if(!$nRandNumArray["$nNum"]){
		$nRandNumArray["$nNum"] = get_rand_letters(5);
	}
	return $nRandNumArray["$nNum"];
}

function get_rand_letters($length) { 
	$alphanum = array("", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"); 
	if($length>0) { 
		$rand_id=""; 
		for($i=1; $i<=$length; $i++) { 
			mt_srand((double)microtime() * 1000000); 
			$num = mt_rand(1,52); 
			$rand_id .= assign_rand_value($num, $alphanum); 
		}
	}
	return $rand_id; 
}

function assign_rand_value($num, $alphanums) { 
	// accepts 1 - 62 (1-52 alpha, 53-62 numeric) 
	$rand_value = $alphanums[$num]; 
	return $rand_value; 
}

// receives a multi-dimensional array, sorts by inner array size, preserving all keys
function sortByCount($nARRAY){
	// make an array that holds (key of 1st array to sort) => (count of sub-array)
	$nTempARRAY = array();
	foreach($nARRAY as $nKey => $nSubARRAY){
		$nTempARRAY["$nKey"] = count($nSubARRAY);
	}
	array_multisort($nTempARRAY,SORT_DESC,$nARRAY);
	return $nARRAY;
}

function nGetPageName($nPageID){
	global $DBName,$Link;
	if(!$nPageID){ return; }
	$nNavTitle = "";
	$nSQL = "SELECT nNavTitle FROM nPage WHERE nID=$nPageID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nNavTitle = $Row["nNavTitle"];
	}
	return $nNavTitle;
}

function nGetSectionIDByName($nName){
	global $DBName,$Link;
	if(!$nName){ return; }
	$nID = "";
	$nName = addslashes(stripslashes($nName));
	$nSQL = "SELECT nID FROM nSection WHERE nName='$nName' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"];
	}
	return $nID;
}

function nGetImageIDARRAY($nLibraryID){
	global $DBName,$Link;
	if(!$nLibraryID){ return; }
	$nFldIDARRAY = explode("-",$nLibraryID);
	$nLibrary = $nFldIDARRAY[1];
	if(!$nLibrary){ return; }
	$nDataARRAY = array();
	$nSQL = "SELECT nID FROM nImage WHERE nType='$nLibrary' ORDER BY nOrderID ASC";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while ($Row = mysql_fetch_array($Result)) {
		$nImageID = $Row["nID"];
		$nImgPath = nGetImagePathFromID($nImageID);
		$nDataARRAY[$nImageID] = $nImgPath;
	}
	return $nDataARRAY;
}

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

function nGetPageIDByName($nName){
	global $DBName,$Link;
	if(!$nName){ return; }
	$nID = "";
	$nSQL = "SELECT nID FROM nPage WHERE nNavTitle='$nName' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"];
	}
	return $nID;
}

function isExternalLink($nLink){
	global $nFullSitePath;
	if(!$nLink){ return; }
	$nSitePathARRAY = parse_url($nFullSitePath);
	$nLinkARRAY = parse_url($nLink);
	// if "http" exists, now search deeper
	if(isset($nLinkARRAY["scheme"])){
		$nSitePathHost = str_replace("www.","",$nSitePathARRAY["host"]);
		$nLinkHost = str_replace("www.","",$nLinkARRAY["host"]);
		// if link host name is not the same as the site's host name, this is an external link
		if($nSitePathHost!=$nLinkHost){ return true; }
	}
	return false;
}

function nGetTmplOverridePath($nTemplateFile,$nTranslateLang=""){
	global $nSiteRootPath,$nCompPath,$nUserCompPath,$nSFLang,$nTranslateLang,$nDefaultLang;
	if(!$nTemplateFile){ return; }
	
	$nSiteTmplPath = tmplGetPath("siteTmplPath",array("ABS=0","SSL=0"));
	
	// Prepare paths
	$nCompPathFinal = str_replace("../","",$nCompPath);
	$nUserCompPathFinal = str_replace("../","",$nUserCompPath);
	// Get language
	$nLangPath = "";
	if(!$nSFLang){ $nSFLang=$nTranslateLang; }
	if(!$nSFLang){ $nSFLang=$nDefaultLang; } // for back-end
	if($nSFLang){ $nLangPath = "$nSFLang/"; }
	
	// Get default template code
	$nTemplateOverridePath = "";
	// First try default path to template (in main components folder, e.g. comp/)
	$nTrialTmplPath = "$nSiteRootPath$nCompPathFinal$nTemplateFile";
	if(file_exists($nTrialTmplPath)){ $nTemplateOverridePath = $nTrialTmplPath; }
	// Override with external template, if exists (in main components language folder, e.g. comp/en/)
	$nTrialTmplPath = "$nSiteRootPath$nCompPathFinal$nLangPath$nTemplateFile";
	if(file_exists($nTrialTmplPath)){ $nTemplateOverridePath = $nTrialTmplPath; }
	// Override with external template, if exists (in template components folder, e.g. tmpl/comp/)
	$nTrialTmplPath = "$nSiteRootPath$nSiteTmplPath$nUserCompPathFinal$nTemplateFile";
	if(file_exists($nTrialTmplPath)){ $nTemplateOverridePath = $nTrialTmplPath; }
	// Override with external template, if exists (in template components language folder, e.g. tmpl/comp/en/)
	$nTrialTmplPath = "$nSiteRootPath$nSiteTmplPath$nUserCompPathFinal$nLangPath$nTemplateFile";
	if(file_exists($nTrialTmplPath)){ $nTemplateOverridePath = $nTrialTmplPath; }
	
	if(!$nTemplateOverridePath){ return; } // No template found
	return $nTemplateOverridePath;
}

// return array of tags in code (e.g. $nTagARRAY["text"] = array("NUM=1","BEFORE=<h3>","AFTER=</h3>")
function nGetTagArray($nTemplateCode){
	global $nOpenerTag,$nCloserTag,$nTagParamDelim;
	$nTagARRAY = array();
	// Parse template
	do{
		$nOpenerPos = strpos($nTemplateCode,$nOpenerTag);
		$nCloserPos = strpos($nTemplateCode,$nCloserTag,$nOpenerPos);
		if($nOpenerPos!==false && $nCloserPos!==false){
			$nInnerTag = substr($nTemplateCode,($nOpenerPos+strlen($nOpenerTag)),($nCloserPos-strlen($nCloserTag)-$nOpenerPos));
			$nReplacement = "";
			$nInnerTagARRAY = explode($nTagParamDelim,$nInnerTag);
			$nTemplateItem = $nInnerTagARRAY[0];
			unset($nInnerTagARRAY[0]);
			$nTagARRAY["$nTemplateItem"]["params"] = $nInnerTagARRAY;
			$nTagARRAY["$nTemplateItem"]["tag"] = "$nOpenerTag$nInnerTag$nCloserTag";
			$nTemplateCode = str_replace(($nOpenerTag.$nInnerTag.$nCloserTag),$nReplacement,$nTemplateCode);
		}
	} while($nOpenerPos!==false);
	return $nTagARRAY;
}
?>
