<?php
/*=======================================================================
 *
 * metafield_special.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");

$httpVars = array("f_act", "statusMessage", "deactivateMenu", "generatePDF", "category", "objId", 
                  "cascadingObjType", "specialPageTitle", "hideButtons", "editMode", "f_uploadImgFile", 
                  "callObjId", "presetFields");

getSecHttpVars("1", $httpVars);                         

getLanguage(__FILE__);

if ($specialPageTitle == "") : $specialPageTitle = getLngt("KONTAKT"); endif;

$pageTitel = getLngt($specialPageTitle);
if ($generatePDF != "1") :
   include_once ("../geo/geocode.inc.php");
endif;
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");

// "$objId" and "$category" (and additional "$cascadingObjType") have to be defined HERE !!!
include_once ("../include/inc_metafield.inc.php");

getCurrentScript(__FILE__);

// Check for authentication access and granted rights
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
if (!(authCheckEmployeeRights($emp_id, "0") || authCheckEmployeeRights($emp_id, "1") || authCheckEmployeeRights($emp_id, "14"))) :
   gotoReferer("1");
endif;

// Formular enabled for entering data or display printable view
if ($editMode == "") : $editMode = "1"; endif;   // Default edit mode is enabled

// Init
$f_secretFileName = "";
$f_extension = "";
$javaScriptOut = "";


// ***************************************
// * Operations for the metafield object *   
// ***************************************

// Save object data
if ($f_act == "saveObjectData" && $editMode == "1") :
   saveObjectData();
endif;


// Upload image (photo, etc.)
if ($f_act == "uploadImgFile") :   
   $importPath = "../documents/images/";
   $tempPath = "../temp/download/";
   $pathSeparator = "/";
   if ($_FILES['f_uploadImgFile']['size'] <= 300000) :
      if (!move_uploaded_file($_FILES['f_uploadImgFile']['tmp_name'], $importPath . $_FILES['f_uploadImgFile']['name'])) :
         $statusMessage = "Die Bilddatei wurde leider nicht hochgeladen!";
      endif;
   else :
      $statusMessage = "Die Bilddatei ist für den Upload zu groß! Derzeit ist eine Beschränkung auf 300K eingestellt!";
      // Delete real file if does exist
      $retVal = removeFile($_FILES['f_uploadImgFile']['name'], $importPath, $pathSeparator); 
   endif;
   // Delete temp file if does exist
   // $retVal = removeFile($_FILES['f_uploadImgFile']['tmp_name'], $tempPath, $pathSeparator);
endif;


// Get current template stored in metafieldcategory for output
$currTemplateId = getFieldValueFromId("metafieldcategory","mtfc_id",$category,"mtft_id");
$atLeastOneImageDoesExistInForm = false;   // Init according to image file upload

// Generate output
// getDBData("tour", $objId);  // Get associative array for tour data of ALL stations. Has to be called here BEFORE calling function "outputMetaFieldSpecial()" !!!!
$outputMetaFieldsHtml = outputMetaFieldSpecial($currTemplateId, $editMode);
$outputMetaFieldsHtmlPHP = $outputMetaFieldsHtml[0];
$outputMetaFieldsHtmlJS = $outputMetaFieldsHtml[1];

// Parse template
$jsFormularFinishPageFunc = "finishPage();";
if ($currTemplateId != "" && $currTemplateId != "0") :
   $contentOfCurrTemplate = getFieldValueFromId("metafieldtemplate","mtft_id",$currTemplateId,"mtft_content");
   if (!(strpos($contentOfCurrTemplate, "formularFinishPage") === FALSE)) :
      $jsFormularFinishPageFunc = "formularFinishPage();";
   endif;
endif;

// ******************************************************************************************************************   


// Output to PDF
if ($generatePDF == "1" && $companyId != "") :
   $includePDFGeneric = "1";
   $f_act = "generatePDFMetafield";
   include_once ("../admin/pdf_generic.php");
   die();
endif;


// Output to EMAIL
$mailHtmlOut = "";
$sendMail = "0";
if ($editMode == "3") :

   $mailHtmlOut .= "<html>\n";
   $mailHtmlOut .= "  <head>\n";
   $mailHtmlOut .= "    <title>" . $pageTitel . "</title>\n";
   $mailHtmlOut .= "    <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/phoenix.css\">\n";
   $mailHtmlOut .= "    <script type=\"text/javascript\">\n";
   $mailHtmlOut .=        $outputMetaFieldsHtmlJS;
   $mailHtmlOut .= "    </script>\n";
   $mailHtmlOut .= "  </head>\n";
   $mailHtmlOut .= "  <body>\n";
   // $mailHtmlOut .= "    <div>\n";
   // $mailHtmlOut .= "      <div>\n";
   $mailHtmlOut .= $outputMetaFieldsHtmlPHP;
   // $mailHtmlOut .= "      </div>\n";
   // $mailHtmlOut .= "    </div>\n";
   $mailHtmlOut .= "  </body>\n";
   $mailHtmlOut .= "</html>\n";
   
   // $mailHtmlOut = urlencode(my_str_check_http($mailHtmlOut));

   $f_secretFileName = "news_" . md5($emp_id);
   $f_extension = "htm";
   
   // Remove old file(s)
   foreach (glob("../temp/download/" . $f_secretFileName . "." . $f_extension) as $fileNameToBoRemoved) {
     if (file_exists($fileNameToBoRemoved)) :
        unlink($fileNameToBoRemoved);
     endif;
   }
   // Write new file according to the current employee
   writeToFile("../temp/download/" . $f_secretFileName . "." . $f_extension, $mailHtmlOut);   // write attachement data into file
   
   $sendMail = "1";
endif;

// Output to PDF
$outPdf = "0";
if ($editMode == "4") :
   $outPdf = "1";
endif;

$headlineObjectOut = "";
if ($mtfcMnemonic == "cs" || $mtfcMnemonic == "cr") :
   $headlineObjectOut = $mtfObjDataArr["comp"] . ($mtfObjDataArr["comp2"] != "" ? " :: " . $mtfObjDataArr["comp2"] : "");
elseif ($mtfcMnemonic == "crvh") :
   $headlineObjectOut = $mtfObjDataArr["crvh_sid"] . ($mtfObjDataArr["crvh_vh_sign"] != "" ? " :: " . $mtfObjDataArr["crvh_vh_sign"] : "");
endif;
$pageHeadline = "<span class=\"f12bp1_blue\">" . strtoupper($mtfcDescription) . "</span>" . " &nbsp;&nbsp;&nbsp;&nbsp;" . $headlineObjectOut;
?>


<html>

<head>
<title><?php echo $pageTitel ?></title>

<style type="text/css">
  <?php include_once ("../css/phoenix.css.php"); ?>
  <?php include_once ("../css/navigation.css.php"); ?>
  <?php include_once ("../css/mc.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script src="../include/checkFormTags.js" type="text/javascript"></script>
<script src="../include/searchLists.js" type="text/javascript"></script>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

// JQuery.Request
function mtfAjaxRequestSync(url, data) {
  $.ajax({
     type: "GET",
     url: url,
     data: data,
     async: false,
     success: function(msg){eval(msg);}
  });
}

function clearAllFields() {
  document.location.href = "metafield_special.php?deactivateMenu=1&category=<?php echo ec($category) ?>";
};

function reloadPage() {
  document.forms[0].submit();
};

<?php echo $outputMetaFieldsHtmlJS ?>

function openGroups(customerId) {
  var widthPopupWin = 800;
  var heightPopupWin = 700;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/groupmembers.php?itemType=cs&itemId=" + customerId,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function switchEditMode(mode) {
	document.forms[0].editMode.value = mode;
	if (mode == '0') {
		 document.forms[0].hideButtons.value = '1';
  }
  finishPage();
}

function check4print() {
	<?php if ($editMode == "0") : ?>
    window.print();
  <?php endif; ?>
}

function sendPerMail() {
	sendMail = '<?php echo $sendMail; ?>';
	if (sendMail == '1') {
     var widthPopupWin = 1000;
     var heightPopupWin = 800;
     var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
     var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
     var popupWin;
     popupWin = window.open("../include/email_send.php?f_act=_nop_&f_content=_file_&f_mimetype=text/html&f_contentFileName=<?php echo $f_secretFileName ?>&f_contentFileExtension=<?php echo $f_extension ?>" ,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
  }
};

function generatePDF() {
	pdfOut = '<?php echo $outPdf; ?>';
	if (pdfOut == '1') {
     var widthPopupWin = 1000;
     var heightPopupWin = 800;
     var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
     var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
     var popupWin;
     popupWin = window.open("../admin/metafield_special_cron.php?category=<?php echo ec($category) ?>&objId=<?php echo ec($objId) ?>&cascadingObjType=<?php echo $cascadingObjType ?>&sendToClientFileDownload=1" ,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
  }
};

<?php if ($atLeastOneImageDoesExistInForm) : ?>
function finishPageUpload(f_act_value) {  
  document.forms[1].f_act.value=f_act_value;
  document.forms[1].submit();
};
<?php endif; ?>

// This function acts with the preset fields got by post
function presetFields() {
<?php 
  if ($category != "" && $callObjId != "" && $presetFields != "") :
     $remObjId = $objId;
     $objId = $callObjId;
     $presetFields = urldecode($presetFields);
     $presetFieldsArray = getKeyValueArrayFromString($presetFields);
     $tmpKeys = array_keys($presetFieldsArray);
     $tmpKeysLen = count($tmpKeys);
     for ($i = 0; $i < $tmpKeysLen; $i++) :
         echo "if (document.forms[0].f_mtfv_" . $category . "_" . $tmpKeys[$i] . ") {\n";
         echo "   document.forms[0].f_mtfv_" . $category . "_" . $tmpKeys[$i] . ".value='" . getFieldValueBySpecialCall($presetFieldsArray[$tmpKeys[$i]]) . "';\n";
         echo "};\n";
     endfor;
     $presetFields = "";
     $presetFieldsArray = "";
     $objId = $remObjId;
  endif; 
?>
}

// This function acts according to the actions (e.g. buttons [e.g. new association regarding "co2cs"]) of the page by itself.
function presetFieldsByAction() {
	var elemMtfv = eval('document.forms[0].f_mtfv_' + document.forms[0].doPresetFieldsPerAction.value);
  var elemPresetFields = eval('document.forms[0].f_presetFields_' + document.forms[0].doPresetFieldsPerAction.value);
  var elemPresetFt = eval('document.forms[0].f_presetFt_' + document.forms[0].doPresetFieldsPerAction.value);
  var elemPresetCategory = eval('document.forms[0].f_presetCategory_' + document.forms[0].doPresetFieldsPerAction.value);

  mtfAjaxRequestSync('../groupware/ajaxReqGroup.php', 'ft=' + elemPresetFt.value + '&presetFields=' + elemPresetFields.value + '&searchValue=' + elemMtfv.value + '&category=' + elemPresetCategory.value);

  document.forms[0].doPresetFieldsPerAction.value = '';  // Reset value !!!
}
-->
</script>

</head>


<body class="menu_bgcol" onLoad="<?php echo $phpCurrentNavigationOnLoad ?><?php echo $javaScriptOut ?>displayStatusMessage();presetFields();check4print();sendPerMail();generatePDF();">

<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="mc_page-header">
  <?php echo $pageHeadline ?>
</div>

  <?php if ($hideButtons == "") : ?>
    <div>
      <?php echo defineButtonType08(getLngt("Speichern"), "action_save", $jsFormularFinishPageFunc, "90", "left", "3"); ?>
      <?php 
        if ($editMode != "0" && $editMode != "3" && $editMode != "4") :
           echo defineButtonType08(getLngt("Drucken"), "action_print", "switchEditMode(0);", "90", "left", "3");
           echo defineButtonType08(getLngt("PDF"), "action_pdf", "switchEditMode(4);", "90", "left", "3");
           echo defineButtonType08(getLngt("Email"), "action_email", "switchEditMode(3);", "90", "left", "3");
        endif;
       ?>
      <?php echo defineButtonType08(getLngt("Zurücksetzen"), "action_reset", "clearAllFields();", "90", "left", "3"); ?>
      <?php echo defineButtonType08(getLngt("Schließen"), "action_close", "window.close();", "90", "left", "3"); ?>
    </div>
  <?php endif; ?>
  
  <?php if ($hideButtons != "") : ?>
    <div>
      <?php 
        if ($editMode == "1") :
           echo defineButtonType08(getLngt("Speichern"), "action_save", $jsFormularFinishPageFunc, "90", "left", "3");
           echo defineButtonType08(getLngt("Drucken"), "action_print", "switchEditMode(0);", "90", "left", "3");
           echo defineButtonType08(getLngt("PDF"), "action_pdf", "switchEditMode(4);", "90", "left", "3");
           echo defineButtonType08(getLngt("Email"), "action_email", "switchEditMode(3);", "90", "left", "3");
        elseif ($editMode == "2") :
           echo defineButtonType08(getLngt("Schließen"), "action_close", "window.close();", "90", "left", "3");
        endif;
       ?>
    </div>
  <?php endif; ?>

  <?php if (!(($editMode == "0" || $editMode == "4") && $hideButtons == "1")) : echo htmlDivLineSpacer("20px", "", "left"); endif; ?>

<div class="maincontent2 mc_elem" name="maincontent" id="maincontent">

<form name="metafield_special" action="../admin/metafield_special.php" method="post">
  <input type="hidden" name="f_act" value="">

  <input type="hidden" name="category" value="<?php echo $category ?>">
  <input type="hidden" name="objId" value="<?php echo $objId ?>">
  <input type="hidden" name="cascadingObjType" value="<?php echo $cascadingObjType ?>">
  <input type="hidden" name="specialPageTitle" value="<?php echo $specialPageTitle ?>">
  <input type="hidden" name="editMode" value="<?php echo $editMode ?>">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">  
  <input type="hidden" name="hideButtons" value="<?php echo $hideButtons ?>">
  <input type="hidden" name="doPresetFieldsPerAction" value="">

  <?php if (!(($editMode == "0" || $editMode == "4") && $hideButtons == "1")) : echo htmlDivLineSpacer("10px"); endif; ?>
  
  <div>
    <?php echo $outputMetaFieldsHtmlPHP; ?>
  </div>
  <?php if (!(($editMode == "0" || $editMode == "4") && $hideButtons == "1")) : echo htmlDivLineSpacer("5px", "", "left"); endif; ?>

</form>

<?php if ($atLeastOneImageDoesExistInForm && $editMode == "1") : ?>
  <form name="upload_file" action="../admin/metafield_special.php" enctype="multipart/form-data" method="post">
  	<input type="hidden" name="f_act" value="">
  	
    <input type="hidden" name="category" value="<?php echo $category ?>">
    <input type="hidden" name="objId" value="<?php echo $objId ?>">
    <input type="hidden" name="cascadingObjType" value="<?php echo $cascadingObjType ?>">
    <input type="hidden" name="specialPageTitle" value="<?php echo $specialPageTitle ?>">
    <input type="hidden" name="editMode" value="<?php echo $editMode ?>">
    <?php echo $phpCurrentNavigationInputHidden ?>
    <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
    <input type="hidden" name="hideButtons" value="<?php echo $hideButtons ?>">

    <?php echo getLngt("Hier können Sie eine Bilddatei (Foto) zum Hochladen auswählen:") ?>&nbsp;
    <input type="hidden" name="MAX_FILE_SIZE" value="300000">
    <input name="f_uploadImgFile" type="file" size="50" accept="image/*">
    <input type="button" value="Upload" onClick="finishPageUpload('uploadImgFile');">
  </form>
<?php endif; ?>


</div>
</body>

</html>
