<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*****************************************************************************
 * The contents of this file are subject to the RECIPROCAL PUBLIC LICENSE
 * Version 1.1 ("License"); You may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://opensource.org/licenses/rpl.php. Software distributed under the
 * License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied.
 *
 * You may:
 * a) Use and distribute this code exactly as you received without payment or
 *    a royalty or other fee.
 * b) Create extensions for this code, provided that you make the extensions
 *    publicly available and document your modifications clearly.
 * c) Charge for a fee for warranty or support or for accepting liability
 *    obligations for your customers.
 *
 * You may NOT:
 * a) Charge for the use of the original code or extensions, including in
 *    electronic distribution models, such as ASP (Application Service
 *    Provider).
 * b) Charge for the original source code or your extensions other than a
 *    nominal fee to cover distribution costs where such distribution
 *    involves PHYSICAL media.
 * c) Modify or delete any pre-existing copyright notices, change notices,
 *    or License text in the Licensed Software
 * d) Assert any patent claims against the Licensor or Contributors, or
 *    which would in any way restrict the ability of any third party to use the
 *    Licensed Software.
 *
 * You must:
 * a) Document any modifications you make to this code including the nature of
 *    the change, the authors of the change, and the date of the change.
 * b) Make the source code for any extensions you deploy available via an
 *    Electronic Distribution Mechanism such as FTP or HTTP download.
 * c) Notify the licensor of the availability of source code to your extensions
 *    and include instructions on how to acquire the source code and updates.
 * d) Grant Licensor a world-wide, non-exclusive, royalty-free license to use,
 *    reproduce, perform, modify, sublicense, and distribute your extensions.
 *
 * The Original Code is: CommuniCore
 *                       Olavo Farias
 *                       2006-04-7 olavo.farias@gmail.com
 *
 * The Initial Developer of the Original Code is CommuniCore.
 * Portions created by CommuniCore are Copyright (C) 2005 CommuniCore Ltda
 * All Rights Reserved.
 ********************************************************************************/
include("modules/EcmStocks/moduleMenu.php");

// INCLUDE SUPPPORT MODULES
   require_once('XTemplate/xtpl.php');
   require_once('data/Tracker.php');

// INCLUDE MODULE OBJECT AND FORMS
   require_once('modules/EcmStocks/EcmStock.php');
   require_once('modules/EcmStocks/Forms.php');
   
   global $app_strings;
   global $mod_strings;
   global $mod_strings;
   global $current_user;
   global $sugar_version, $sugar_config;
   
// INSTANTIATES THE MODULE CLASSES  
   $focus       = new EcmStock();
   
// IF PROCESSING AN EXISTING RECORD, RETRIEVE IT  
   if(isset($_REQUEST['record'])) {
    $focus->retrieve($_REQUEST['record']);
    $focus->unformat_all_fields();
   }
   if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
   	$focus->id             = "";
   	$focus->simplemodule_number = "";
   }
   
   $prefillArray = array(
          'priority'	    => 'priority',
   					  'name'     	 	 => 'name',
   					  'description'  => 'description',
   					  'status' 	 	   => 'status',
   					  'type' 	 	     => 'type',
    					);
   
   foreach($prefillArray as $requestKey => $focusVar) {
    if (isset($_REQUEST[$requestKey]) && is_null($focus->$focusVar)) {
     $focus->$focusVar = urldecode($_REQUEST[$requestKey]);
    }
   }
   
// BUILD MODULE TITLE LINE  
   echo "\n<p>\n";
   echo get_module_title($mod_strings['LBL_MODULE_ID'], $mod_strings['LBL_MODULE_NAME'].": ".$focus->name, true);
   echo "\n</p>\n";

   global $theme;
   $theme_path = "themes/".$theme."/";
   $image_path = $theme_path."images/";
   require_once ($theme_path.'layout_utils.php');
   
   $GLOBALS['log']->info("EcmStocks detail view");
   
   $default_bank = "<select id='default_bank_id' name='default_bank_id'>";
	$EcmSysInfo = new EcmSysInfo();
	$default_bank .= "<option value='' ></option>";
	echo $focus->default_bank_id;
   foreach($EcmSysInfo->getBanks() as $k => $v){
	   $selected = "";
	   if($focus->default_bank_id == $v['ID']){
		   $selected = " selected ";
	   }
	   $default_bank .= "<option value='" . $v['ID'] ."' " . $selected.">\"" . $v['NAMESHORT'] . "\" ". $v['NAME'] . ": " . $v['NUMBER'] ."</option>";
   }
   
   $default_bank .= "</select>";
   $xtpl = new XTemplate ('modules/EcmStocks/EditView.html');
   $xtpl->assign("default_bank", $default_bank);
   

// FILL XTEMPLATE MODULE & APPLICATION LANGUAGE STRINGS
   $xtpl->assign("MOD",                  $mod_strings);
   $xtpl->assign("APP",                  $app_strings);
   $xtpl->assign("CALENDAR_DATEFORMAT",  $timedate->get_cal_date_format());
   
   if (isset($_REQUEST['return_module'])) $xtpl->assign("RETURN_MODULE", $_REQUEST['return_module']);
   if (isset($_REQUEST['return_action'])) $xtpl->assign("RETURN_ACTION", $_REQUEST['return_action']);
   if (isset($_REQUEST['return_id']))     $xtpl->assign("RETURN_ID",     $_REQUEST['return_id']);
   
   if (empty($_REQUEST['return_id'])) {
   	$xtpl->assign("RETURN_ACTION", 'index');
   }
   
///////////////////////////////////////
// SETUP POPUPS START
// Users Popup
   $json               = getJSONobj();
   $popup_request_data = array(
   	'call_back_function'  => 'set_return',
   	'form_name'           => 'EditView',
   	'field_to_name_array' => array(
   		'id'        => 'assigned_user_id',
   		'user_name' => 'assigned_user_name',
   		),
   	);
   $xtpl->assign('encoded_users_popup_request_data', $json->encode($popup_request_data));
//
////////////////////////////////////////////////////////////////////////////////
   
   
// ACCOUNT_ID WILL BE SET WHEN USER CHOOSES TO CREATE A NEW SIMPLEMODULE FROM ACCOUNT DETAIL VIEW.
   if (isset($_REQUEST['account_id'])) $xtpl->assign("ACCOUNT_ID", $_REQUEST['account_id']);
   if (isset($_REQUEST['contact_id'])) $xtpl->assign("CONTACT_ID", $_REQUEST['contact_id']);
   
// SET THE CASE_ID, IF SET.
// WITH NEW CONCEPT OF SUBPANELS IT, 
// WHEN THE SUBPANEL IS DISPLAYED IT PULLS FROM THE CLASS NAME WHICH IN THE SITUATION OF CASES IS ACASE SO THE FORM IS GENERATED
// WITH ACASE_ID INSTEAD OF CASE_ID, SO I HAVE DONE THE MAPPING HERE
   if (isset($_REQUEST['acase_id']))    $xtpl->assign("CASE_ID",$_REQUEST['acase_id']);
   else if(isset($_REQUEST['case_id'])) $xtpl->assign("CASE_ID",$_REQUEST['case_id']);

////////////////////////////////////////////////////////////////////////////////
// QUICK SEARCH SETUP
   require_once('include/QuickSearchDefaults.php');
   $qsd = new QuickSearchDefaults();
   $sqs_objects = array(
   	'assigned_user_name' => $qsd->getQSUser(),
/*
//BUILDER:START Pro only 
   	'team_name'          => $qsd->getQSTeam()
//BUILDER:END Pro only 
*/
   );
   $quicksearch_js  = $qsd->getQSScripts();
   $quicksearch_js .= '<script type="text/javascript" language="javascript">sqs_objects = ' . $json->encode($sqs_objects) . '</script>';
// QUICK SEARCH SETUP
////////////////////////////////////////////////////////////////////////////////
   
////////////////////////////////////////////////////////////////////////////////
// ASSIGN GLOBAL VARIABLES
   $xtpl->assign("THEME",               $theme);
   $xtpl->assign("IMAGE_PATH",          $image_path);$xtpl->assign("PRINT_URL", "index.php?".$GLOBALS['request_string']);
   $xtpl->assign("JAVASCRIPT",          get_set_focus_js().get_validate_record_js(). $quicksearch_js);
   $xtpl->assign("USER_DATEFORMAT", '('. $timedate->get_user_date_format().')');
   $xtpl->assign("CALENDAR_DATEFORMAT",  $timedate->get_cal_date_format());
// ASSIGN GLOBAL VARIABLES
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// ASSIGN MODULE DEFAULT VARIABLES
   $xtpl->assign("ID",                $focus->id);
   if (!empty($focus->name)) 
        $xtpl->assign("NAME",         $focus->name);
   else $xtpl->assign("NAME",         "");
   $xtpl->assign("DATE_ENTERED",      $focus->date_entered);
   $xtpl->assign("DATE_MODIFIED",     $focus->date_modified);
   $xtpl->assign("CREATED_BY",        $focus->created_by_name);
   $xtpl->assign("MODIFIED_BY",       $focus->modified_by_name);

   if (empty($focus->assigned_user_id) && empty($focus->id))  $focus->assigned_user_id   = $current_user->id;
   if (empty($focus->assigned_name)    && empty($focus->id))  $focus->assigned_user_name = $current_user->user_name;
   $xtpl->assign("ASSIGNED_USER_OPTIONS",    get_select_options_with_id(get_user_array(TRUE, "Active", $focus->assigned_user_id), $focus->assigned_user_id));
   $xtpl->assign("ASSIGNED_USER_NAME",       $focus->assigned_user_name);
   $xtpl->assign("ASSIGNED_USER_ID",         $focus->assigned_user_id );
   
// ASSIGN MODULE SPECIFIC VARIABLES 


	if($focus->main)$xtpl->assign("CHECKED_MAIN"," checked");
    $xtpl->assign("DESCRIPTION",   $focus->description);
    $xtpl->assign("DIR",   $focus->dir);
    $xtpl->assign("NO",   $focus->no);
 
// ASSIGN MODULE DROPDOWNS WITH DEFAULT KEY
   
// ASSIGN MODULE VARIABLES AFFECTED BY DUPLICATE ACTION   
   if(!isset($_REQUEST['isDuplicate'])) {
    $focus->id = "";
   }


// ASSIGN MODULE DROPDOWNS WITHOUT DEFAULT KEY

//BUILDER:END of xtpl

// ADD CUSTOM FIELDS
   require_once('modules/DynamicFields/templates/Files/EditView.php');

////////////////////////////////////////////////////////////////////////////////
// USER ASSIGNMENT
   global $current_user;
   if(is_admin($current_user) && $_REQUEST['module'] != 'DynamicLayout' && !empty($_SESSION['editinplace'])){
   	$record = '';
// USER ASSIGNMENT
////////////////////////////////////////////////////////////////////////////////

   	if(!empty($_REQUEST['record'])){
   		$record = 	$_REQUEST['record'];
   	}
   	$xtpl->assign("ADMIN_EDIT","<a href='index.php?action=index&module=DynamicLayout&from_action=".$_REQUEST['action'] ."&from_module=".$_REQUEST['module'] ."&record=".$record. "'>".get_image($image_path."EditLayout","border='0' alt='Edit Layout' align='bottom'")."</a>");
   }

   
   
   $xtpl->parse("main");
   $xtpl->out("main");
   require_once('include/javascript/javascript.php');
   $javascript = new javascript();
   $javascript->setFormName('EditView');
   $javascript->setSugarBean($focus);
   $javascript->addAllFields('');

//BUILDER:START Pro only 
//   $javascript->addFieldGeneric(              'team_name',          'varchar', $app_strings['LBL_TEAM'] ,'true');
//   $javascript->addToValidateBinaryDependency('team_name',          'alpha',   $app_strings['ERR_SQS_NO_MATCH_FIELD'] . $app_strings['LBL_TEAM'],        'false', '', 'team_id');
//BUILDER:END Pro only 

   $javascript->addToValidateBinaryDependency('assigned_user_name', 'alpha',   $app_strings['ERR_SQS_NO_MATCH_FIELD'] . $app_strings['LBL_ASSIGNED_TO'], 'false', '', 'assigned_user_id');
   
   echo $javascript->getScript();
   
////////////////////////////////////////////////////////////////////////////////
/// SELECT CHANGES TEXT INPUT FIELD
/*
    $prob_array = $json->encode($app_list_strings['sales_probability_dom']);
    $prePopProb = '';
    if(empty($focus->id)) $prePopProb = 'document.getElementsByName(\'sales_stage\')[0].onchange();';
    echo <<<EOQ
    	<script>
    	prob_array = $prob_array;
    	document.getElementsByName('sales_stage')[0].onchange = function() {
    			if(typeof(document.getElementsByName('sales_stage')[0].value) != "undefined" && prob_array[document.getElementsByName('sales_stage')[0].value]) {
    				document.getElementsByName('probability')[0].value = prob_array[document.getElementsByName('sales_stage')[0].value];
    			} 
    		};
    	$prePopProb
    	</script>
EOQ;
*/
//
/// SELECT CHANGES TEXT INPUT FIELD
////////////////////////////////////////////////////////////////////////////////
   require_once('modules/SavedSearch/SavedSearch.php');
   $savedSearch        = new SavedSearch();
   $json               = getJSONobj();
   $savedSearchSelects = $json->encode(array($GLOBALS['app_strings']['LBL_SAVED_SEARCH_SHORTCUT'] . '<br>' . $savedSearch->getSelect('EcmStocks')));
   $str = "<script>
   YAHOO.util.Event.addListener(window, 'load', SUGAR.util.fillShortcuts, $savedSearchSelects);
   </script>";
   echo $str;

?>