<?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
*/

// Next line to start calc of page load time
$nPLTStart = microtime(); $nPLTStartARRAY = explode(" ", $nPLTStart); $nPLTStart = $nPLTStartARRAY[1] + $nPLTStartARRAY[0];
require("inc/stop_cache.php");
$nAdminOnlyPg = 0;
require("inc/secure_page.php");
// connect to mysql
require("../inc/dbconnect.php");
require("../inc/config.php");
require("inc/lang.php");
require("../inc/tracker.php");
include("inc/paginator.php");
include("inc/pageutil.php");
include("inc/calendar.php");
require("inc/imgedit_gd.php");

// Allow large files to be uploaded
ini_set('memory_limit','-1');
ini_set('upload_max_filesize','50');

$nShowPerPg = 999;

// Get passed-in vars
if(isset($_GET["pg"])){ $nPage = $_GET["pg"]; } else { $nPage = ""; }
if(!$nPage && isset($_POST["pg"])){ $nPage = $_POST["pg"]; }
if(isset($_GET["srt"])){ $nSort = $_GET["srt"]; } else { $nSort = ""; }
if(isset($_GET["ord"])){ $nSortOrder = $_GET["ord"]; } else { $nSortOrder = ""; }
if(isset($_GET["spp"])){ $nShowPerPgOverride = $_GET["spp"]; } else { $nShowPerPgOverride = ""; }
if($nShowPerPgOverride){ $nShowPerPg = $nShowPerPgOverride; }

if(isset($_GET["t"])){ $nType = $_GET["t"]; } else { $nType = ""; }
if(!$nType){ $nType = "Content"; }
if(isset($_GET["mode"])){ $nMode = $_GET["mode"]; } else { $nMode = ""; }
if(!$nMode && isset($_POST["mode"])){ $nMode = $_POST["mode"]; }
if(!$nMode){ $nMode = "e"; } // e = edit images, c = choose image
if(isset($_GET["fld"])){ $nFieldToUpdate = $_GET["fld"]; } else { $nFieldToUpdate = ""; }

// For passing via JQuery
if($nType){ $nTypeAsGET = str_replace(" ","%20",$nType); }

if(isset($_POST["nPostProcess"])){ $nPostProcess = $_POST["nPostProcess"]; } else { $nPostProcess = ""; }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WPM :: <?php echo $nSiteName;?></title>
<link rel="stylesheet" type="text/css" href="css/meta-admin.css" />
<link rel="stylesheet" type="text/css" href="css/blue-theme.css" />
<!--[if lte IE 6]><link media="screen" rel="stylesheet" type="text/css" href="css/ie.css" /><![endif]-->
<link href="css/colorbox.css" rel="stylesheet" type="text/css">
<link href="css/form.css" rel="stylesheet" type="text/css">
<link href="css/drag_drop.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/css.js"></script>
<script type="text/javascript" src="js/behaviour.js"></script>
<script type="text/javascript" src="js/refresh.js"></script>
<script src="js/utility.js" type="text/javascript"></script>
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="js/jquery.colorbox-min.js" type="text/javascript"></script>
<script src="js/jquery_processor.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.17.custom.min.js" type="text/javascript"></script>
<script>
$(function() {
	// load page content modules
	loadContent('ajaxImages','list/images.php?t=<?php echo $nTypeAsGET;?>&mode=<?php echo $nMode;?>&fld=<?php echo $nFieldToUpdate;?>');
	
	// test
	//alert(window.parent.document);
	//$('#nImgID_1', window.parent.document).hide();
	//alert('hidden');
	//$(window.parent.document).find("#nImgID_1").hide();
	//alert('hidden again');
});
</script>
<script>
function gotoHref(theSelect) {
	if(theSelect.value != "") {
		thehref = theSelect.options[theSelect.selectedIndex].value;
		window.location.href = thehref;
	}
}
</script>
</head>

<body onLoad="MM_preloadImages('img/load.gif');" style="padding:10px;">

<!--[if !IE]>start info<![endif]-->
<div id="info">
	
	<!--[if !IE]>start section<![endif]-->
	<div class="section">
	<div class="title_wrapper">
		
		<?php if($nMode=="c"){ ?>
			<div style="position:absolute; top:5px; left: 240px;">
				<?php echo _("Image Libary"); ?>: <select name="t" onChange="gotoHref(this);"><?php echo nGetLibraryDD("image",$nType);?></select>
			</div>
		<?php } else { ?>
			<div style="position:absolute; top:5px; left: 170px;">
				<select name="t" onChange="gotoHref(this);"><?php echo nGetLibraryDD("image",$nType);?></select>
			</div>
		<?php } ?>
		<h2><?php if($nMode=="c"){ echo _("Choose an image").": "; } else { echo _("Image Library").": "; } ?></h2>
		<div id="product_list_menu">
			<a href="javascript:;" title="<?php echo _("Add New Image"); ?>" onClick="$('#imgFormDiv').slideDown('slow');" class="update"><span><span><em><?php echo _("Add New"); ?></em><strong></strong></span></span></a>
		</div>
	</div>
	<div id="imgFormDiv" style="border:1px solid #CCC;padding:14px;display:none;">
<?php
include("inc/form_class.php");

$nFormName = "FormImageAdd";
$nForm1 = new Form();
$nForm1->Name = $nFormName;
$nForm1->Action = $_SERVER['PHP_SELF']."?t=".$nType."&e=".$nMode."&fld=".$nFieldToUpdate;
$nForm1->SubmitText = _("Add New Image");
$nForm1->CancelText = _("Cancel");
$nForm1->CancelRedirect = "$('#imgFormDiv').slideUp('slow');";
$nForm1->CancelRedirectIsJS = true;
$nForm1->AddToDBTable = "nImage";
$nForm1->Encoding = "multipart/form-data";
$nForm1->DontProcess = "nPostProcess,nRolloverText,nCustomWidth,mode";

$nForm1->DBLink = $Link;
$nForm1->nUseADODB = false;

// Create groups
$nFormGroup1 = new FormGroup();
$nFormGroup2 = new FormGroup();
$nFormGroup2->Class = "customGrp";
if($nPostProcess!="custom"){ $nFormGroup2->Style = "display:none;"; }

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

if($nType){
	$nFormField = new FormField("hidden","nType");
	$nFormField->Value = $nType;
	$nFormGroup1->AddField($nFormField);
}
if($nMode){
	$nFormField = new FormField("hidden","mode");
	$nFormField->Value = $nMode;
	$nFormGroup1->AddField($nFormField);
}

$nFormField = new FormField("file","nImage",_("Upload a new image to library")." $nType:");
$nFormField->Caption = _("(JPG, GIF and PNG formats accepted, file must be below 50Mb)");
//$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormField->RowSize = "Half";
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("select","nPostProcess",_("Resize image on upload to:"));
$nFormField->onBlur = "nShowCustomWidth(this.value);";
$nFormField->DataARRAY = nGetImageSizingOptionsARRAY();
if($nPostProcess){ $nFormField->SelectedARRAY = array("$nPostProcess" => "selected"); }
$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormField->RowStyle = "clear:both;float:none;";
$nFormGroup1->AddField($nFormField);

/*
switch($nType){
	case "Thumb":
	case "Content":
	case "Home":
		$nFormField = new FormField("text","nRolloverText",_("Add a rollover effect text:"));
		$nFormField->Caption = _("(type in a short message to show when a mouse rolls over image)");
		$nFormField->RowStyle = "clear:both;float:none;";
		$nFormField->Value = $nNavTitle;
		$nFormField = $nForm1->AddValidation("maxlength",$nFormField,100);
		$nFormField->RowSize = "Half";
		$nFormGroup1->AddField($nFormField);
		break;
}
*/

$nFormField = new FormField("text","nCustomWidth",_("Resize image to width (pixels):"));
$nFormField->Caption = _("(e.g. 500)");
$nFormField->Style = "width:80px;";
$nFormField->RowStyle = "clear:both;float:none;";
$nFormField = $nForm1->AddValidation("maxlength",$nFormField,4);
$nFormField = $nForm1->AddValidation("numeric",$nFormField);
$nFormField->RowSize = "Half";
$nFormGroup2->AddField($nFormField);

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

// AJAX redirect if form submitted w/o error, otherwise display form (again, if necessary)
$nImgError = "";
if($nForm1->HasProcessed){
	//echo "<strong>Image has been succesfully uploaded!</strong><BR><BR>";
	$nImgID = $_POST['nID'];
	$nPostProcess = $_POST['nPostProcess'];
	$nBaseImgPath = "../usr/img/";
	$nDBImgPath = "usr/img/";
	// Get uploaded image
	if(isset($_FILES['nImage'])){
		$nUpImage = $_FILES['nImage'];
		if ($nUpImage){
			$nUpImageFilename = $nUpImage['name'];
			$nUpImageTMPFile = $nUpImage['tmp_name'];
		}
		// Copy file to public folder and save to db
		$nNewFilename = nSanitizeImgFilename($nUpImageFilename);
		$nImgExtension = nImg_GetExtension($nUpImageFilename);
		if($nImgExtension!="jpg" && $nImgExtension!="gif" && $nImgExtension!="png") { $nImgError.=_("Filetype not supported")." ($nImgExtension).  "._("Please use a JPG, GIF or PNG image only.")."<BR>"; }
	} else { $nImgError = "No image uploaded."; }
	if(!$nImgError){
		if($nImgExtension=="gif"){ $nNewFilename = str_replace(".gif",".jpg",$nNewFilename); $nConvertGIF2JPG=1; } else { $nConvertGIF2JPG=0; }
		// fix filename for duplicates
		$nNum = 1;
		while(file_exists($nBaseImgPath.$nNewFilename)){
			$nNewFilename = str_replace("_$nNum.$nImgExtension",".$nImgExtension",$nNewFilename); // get rid of old num
			$nNum++;
			$nNewFilename = str_replace(".$nImgExtension","_$nNum.$nImgExtension",$nNewFilename); // add new num
		}
		copy($nUpImageTMPFile,$nBaseImgPath.$nNewFilename);
		if($nConvertGIF2JPG){ nImg_ConvertGIF2JPG($nBaseImgPath.$nNewFilename); }
		// Save to db
		$Query = "UPDATE nImage SET nPath='$nDBImgPath$nNewFilename' WHERE nID=$nImgID LIMIT 1";
		mysql_select_db($DBName);
		mysql_query($Query, $Link);
		// Post-processing
		$nImgPath = $nBaseImgPath.$nNewFilename;
		if($nPostProcess && $nPostProcess!="none"){
			if($nPostProcess=="custom"){
				// setup vars for image processing
				$nCustomWidth = nSanitizeNumeric($_POST['nCustomWidth']);
				//$nCustomCropWidth = nSanitizeNumeric($_POST['nCustomCropWidth']);
				if(isset($_POST['nCustomHeight'])){ $nCustomHeight = nSanitizeNumeric($_POST['nCustomHeight']); } else { $nCustomHeight = ""; }
				//$nCustomCropHeight = nSanitizeNumeric($_POST['nCustomCropHeight']);
				// save custom width for future use, if not already existing
				$nAlreadyExists = false;
				//$nSQL = "SELECT nID FROM nImageSizingOptions WHERE nName='$nType' AND nWidth='$nCustomWidth' AND nCropWidth='$nCustomCropWidth' AND nHeight='$nCustomHeight' AND nCropHeight='$nCustomCropHeight' LIMIT 1";
				$nSQL = "SELECT nID FROM nImageSizingOptions WHERE nName='$nType' AND nWidth='$nCustomWidth' AND nHeight='$nCustomHeight' LIMIT 1";
				mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
				if($Row = mysql_fetch_array($Result)){
					$nAlreadyExists = true;
				}
				if(!$nAlreadyExists){
					// $Query = "INSERT INTO nImageSizingOptions (nID,nName,nWidth,nCropWidth,nHeight,nCropHeight) VALUES ('','$nType','$nCustomWidth','$nCustomCropWidth','$nCustomHeight','$nCustomCropHeight')";
					$Query = "INSERT INTO nImageSizingOptions (nID,nName,nWidth,nCropWidth,nHeight,nCropHeight) VALUES ('','$nType','$nCustomWidth','','$nCustomHeight','')";
					mysql_select_db($DBName);
					mysql_query($Query, $Link);
				}
			} else {
				// get resize details
				$nImageProcessingARRAY = nGetImageProcessingARRAY($nPostProcess);
				// setup vars for image processing
				if(is_array($nImageProcessingARRAY) && $nImageProcessingARRAY["nName"]){
					$nCustomWidth = nSanitizeNumeric($nImageProcessingARRAY["nWidth"]);
					$nCustomCropWidth = nSanitizeNumeric($nImageProcessingARRAY["nCropWidth"]);
					$nCustomHeight = nSanitizeNumeric($nImageProcessingARRAY["nHeight"]);
					$nCustomCropHeight = nSanitizeNumeric($nImageProcessingARRAY["nCropHeight"]);
				}
			}
			// process image (NOTE: needs to be udpated at a future date for additional height and cropping processing)
			if(!$nCustomWidth){ $nCustomWidth = 1024; } // force all images to max 1024 pixel width
			if($nImgPath && $nCustomWidth && is_numeric($nCustomWidth)){
				nResizeImage($nImgPath, $nImgPath, $nCustomWidth);
			}
		}
	}
	echo $nFormToDisplay;
	
} else {
	echo $nFormToDisplay;
}
?>
<script>
nShowCustomWidth = function(fldValue){
	if(fldValue=="custom"){
		$('.customGrp').show();
		//$.colorbox.resize();
	} else {
		$('.customGrp').hide();
		//$.colorbox.resize();
	}
}
</script>
	</div>
	<?php echo $nImgError;?>
	<div id="ajaxImages"></div><BR>
	
</div>

<!-- <a href="javascript:;" onClick="window.opener.FormCompEdit.nProcess=0; if(window.opener.FormCompEdit.onsubmit()){ window.opener.FormCompEdit.submit(); }">test parent link</a> //-->

<div id="status" style="display:none;"><table><tr><td class="padRight"><img src="img/load.gif" alt="" width="16" height="16" border="0"></td><td><div align="center"><?php echo _("Loading...<BR>Please wait"); ?><BR></div></td></tr></table></div>
	
</body>
</html>
<?php
function nGetImageSizingOptionsARRAY(){
	global $DBName,$Link;
	$nDataARRAY = array();
	// Defaults
	$nDataARRAY["none"] = "- "._("No resize")." -";
	$nDataARRAY["custom"] = _("Custom width (manual)");
	$nSQL = "SELECT * FROM nImageSizingOptions ORDER BY nWidth,nHeight";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nOptionID = $Row["nID"];
		$nOptionName = $Row["nName"];
		$nOptionWidth = $Row["nWidth"];
		$nOptionHeight = $Row["nHeight"];
		$nOptionCropWidth = $Row["nCropWidth"];
		$nOptionCropHeight = $Row["nCropHeight"];
		$nOptionTextARRAY = array();
		if($nOptionWidth){ $nOptionTextARRAY[] = _("width").":{$nOptionWidth}px"; }
		if($nOptionHeight){ $nOptionTextARRAY[] = _("height").":{$nOptionHeight}px"; }
		if($nOptionCropWidth){ $nOptionTextARRAY[] = _("crop to width:")."{$nOptionCropWidth}px"; }
		if($nOptionCropHeight){ $nOptionTextARRAY[] = _("crop to height:")."{$nOptionCropHeight}px"; }
		$nOptionText = implode(", ",$nOptionTextARRAY);
		if($nOptionText){ $nDataARRAY["$nOptionID"] = "$nOptionName "._("image")." ($nOptionText)"; }
	}
	return $nDataARRAY;
}
function nGetLibraryDD($nType="",$nSelectedItem=""){
	global $DBName, $Link, $nMode, $nFieldToUpdate;
	if($nType){ $nWhereClause = "WHERE nType='$nType'"; }
	$nLibDD = "";
	$Query = "SELECT nID,nName FROM nLibrary $nWhereClause";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	while ($Row = mysql_fetch_array($Result)){
		$nLibraryID = $Row["nID"];
		$nName = $Row["nName"];
		if($nSelectedItem==$nName){ $nSelected="selected"; } else { $nSelected=""; }
		$nLibDD.="<option value=\"?t=$nName&mode=$nMode&fld=$nFieldToUpdate\" $nSelected>$nName</option>";
	}
	return $nLibDD;
}
function nGetNextImageNum(){
	global $DBName,$Link;
	$nSQL = "SELECT Max(nID) AS nID FROM nImage";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"] + 1;
	}
	return $nID;
}
function nSanitizeNumeric($nNumber){
	$nNumber = preg_replace("/[^0-9]/", "", $nNumber);
	return $nNumber;
}
?>
<?php require("../inc/db_close.php"); ?>


