<?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.

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

  

  require_once('data/SugarBean.php');

  require_once('include/utils.php');

  

  class EcmInsideOrder extends SugarBean {

    

    var $field_name_map = array();

    

    // STANDARD FIELDS

    var $id;

    var $date_entered;

    var $date_modified;

    var $modified_user_id;

    var $assigned_user_id;

    var $name;

    var $description;

    

    //TABLE COLUMNS 

	var $currency_id;
    var $number;
    var $document_no;
    var $parent_type;
    var $parent_name;
    var $parent_id;
    var $type;
    var $status;
    var $register_date;
    var $end_date;
    var $parent_address_street;
    var $parent_address_city;
    var $parent_address_postalcode;
    var $parent_address_country;
    var $subtotal;
    var $total;
    var $discount;
    var $to_vatid;
	var $ecmlanguage;
    var $to_is_vat_free;
    var $header_text;
    var $footer_text;
    var $ads_text;    
    var $template_id;
    var $template_name;   
    var $email_id; 

    var $parent_name_copy;
    var $parent_contact_name;
    var $parent_contact_title;	
	
	var $ecmpaymentcondition_id;
	var $ecmpaymentcondition_name;
	var $ecmpaymentcondition_text;
	var $ecmdeliverycondition_id;
	var $ecmdeliverycondition_name;
	var $ecmdeliverycondition_text;
	var $validtill_date;
	var $order_origin;
	
	var $contact_id;
	var $contact_name;

    var $currency_symbol;
    

    var $template;

    var $pdf;

    var $position_list;

    var $parser;

    var $account;

    var $contact;

    var $ecmvendor;

    var $user;

    var $mfp;
	
	var $delivery_date;
	
	var $tracking_no;
	
	var $pw_stock_id;
	var $rw_stock_id;
	
	var $employers=array();

    

    

    // RELATED FIELDS

    var $created_by;

    var $created_by_name;

    var $modified_by_name;

    var $assigned_user_name;

    

    // SUBPANELS RELATED

    

    // MODULE OBJECT DETAILS 

    var $module_dir        = "EcmInsideOrders";

    var $table_name        = "ecminsideorders";

    var $object_name       = "EcmInsideOrder";

     

    //RELATED TABLE NAMES

    

  

    // USED TO RETRIEVE RELATED FIELDS FROM FORM POSTS.

    var $additional_column_fields = Array (

      'assigned_user_name', 

      'assigned_user_id', 

      'modified_user_id',

      'created_by',

    );

    

  

    //RELATIONSHIP FIELDS 

    var $relationship_fields = Array (

      'note_id' => 'notes',

      'email_id' => 'emails'

//      'account_id' => 'account', 

//      'contact_id' => 'contact',

    );

  

    function EcmInsideOrder() {

      parent::SugarBean();

      $this->setupCustomFields('EcmInsideOrders');

      foreach($this->field_defs as $field) {

        $this->field_name_map[$field['name']] = $field;

      }

    }

    

    var $new_schema = true;

    

    function get_summary_text(){

      return "$this->name";

    }

    

    function create_list_query($order_by, $where, $show_deleted = 0) {

      

      // Fill in the assigned_user_name

      $custom_join = $this->custom_fields->getJOIN();

      $query   = "SELECT ";

      $query  .= "ecminsideorders.*

                  ,users.user_name as assigned_user_name";

      if($custom_join) {

        $query .= $custom_join['select'];

      }

      $query   .= " FROM ecminsideorders 

                   LEFT JOIN users

                   ON ecminsideorders.assigned_user_id=users.id";

      $query   .= "  ";

      if($custom_join) {

        $query .= $custom_join['join'];

      }

      $where_auto = '1=1';

      if($show_deleted == 0) {

        $where_auto = " $this->table_name.deleted=0 ";

      } else if($show_deleted == 1) {

        $where_auto = " $this->table_name.deleted=1 "; 

      }

      

      if($where != "")

        $query .= "where $where AND ".$where_auto;

      else

        $query .= "where ".$where_auto;

      if(substr_count($order_by, '.') > 0) {

        $query .= " ORDER BY $order_by";

      }

      else if($order_by != "")

        $query .= " ORDER BY $order_by";

      else

        $query .= " ORDER BY ecminsideorders.name";

      

      return $query;

    }

  

    function create_export_query($order_by, $where) {

      

      $custom_join = $this->custom_fields->getJOIN();

      $query       = "SELECT

                      ecminsideorders.*,

                      users.user_name assigned_user_name";

      if($custom_join) {

        $query .=  $custom_join['select'];

      }

      $query   .= " FROM ecminsideorders ";

      $query   .= " LEFT JOIN users

                  ON ecminsideorders.assigned_user_id=users.id";

      if($custom_join) {

        $query .=  $custom_join['join'];

      }

      $query   .= "";

      $where_auto = " ecminsideorders.deleted=0 

                    ";

      if($where != "")

        $query .= " where $where AND ".$where_auto;

      else

        $query .= " where ".$where_auto;  

      if($order_by != "")

        $query .= " ORDER BY $order_by";

      else

        $query .= " ORDER BY ecminsideorders.name";

    

      return $query;

    }

  

    function fill_in_additional_list_fields(){

 

    }

  

    function fill_in_additional_detail_fields(){

      //FILL IN THE ASSIGNED_USER_NAME

      $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);

      $this->created_by_name    = get_assigned_user_name($this->created_by);

      $this->modified_by_name   = get_assigned_user_name($this->modified_user_id);

      $result = $this->db->query("SELECT status FROM ecminsideorders WHERE id='$this->id'");

      if($result) $row = $this->db->fetchByAssoc($result);
      if(is_resource($result)) {
      	$row = $this->db->fetchByAssoc($result);
      	if($row) {
      		$this->status = $row['status'];
      	}
      }

/*
      $query = "select `number`, `template_id` from `ecminsideorders` where `id`='$this->id' limit 1";

      $r = $this->db->query($query);

      if($r) {

        $r = $this->db->fetchByAssoc($r);

        $this->template_id = $r['template_id'];

        $this->number = $r['number'];

        $this->setTemplate();

        $this->document_no = $this->formatNumber();      

      }
*/
    }

  

    function get_list_view_data(){

      global $current_language;

      $this->fill_in_additional_detail_fields();

      $app_list_strings = return_app_list_strings_language($current_language);

      $mod_strings      = return_module_language($current_language, 'EcmInsideOrders');

      $the_array        = parent::get_list_view_data();

      // THE NEW LISTVIEW CODE ONLY FETCHES COLUMNS THAT WE'RE DISPLAYING AND NOT ALL

      // THE COLUMNS SO WE NEED THESE CHECKS. 

      $the_array['NAME'] = (($this->name == "") ? "<em>blank</em>" : $this->name);

//      $the_array['NUMBER'] =  $this->document_no;
      $the_array['TOTAL'] = format_number($this->total);
	  $the_array['PDF_URL'] = '';
	  $this->retrieve($this->id);
	  $r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name from accounts where id='".$this->parent_id."'"));
	  $the_array['PARENT_NAME']=$r['name'];
	  $the_array['PARENT_ID']=$this->parent_id;

	  $r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name from ecmstocks where id='".$this->pw_stock_id."'"));
	  $the_array['PW_STOCK_NAME']=$r['name'];

	  $r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name from ecmstocks where id='".$this->rw_stock_id."'"));
	  $the_array['RW_STOCK_NAME']=$r['name'];

	  $the_array['OPTIONS'] = $this->ListIconsView();
	  $the_array['STATUS'] = EcmInsideOrder::CreateImgStatus($this->id,$this->status);
      return  $the_array;

    }

	function getStatusMenuInfo($inJSON = true) {
		global $app_list_strings;
		$arr = array();
		foreach($app_list_strings['ecminsideorders_status_dom'] as $key => $value) {
			$arr[$key] = array (
				'enabled' => '<div><img src="modules/EcmInsideOrders/images/'.$key.'.gif" />'.$value.'</div>',
				'disabled' => '<div><img src="modules/EcmInsideOrders/images/'.$key.'.gif" />'.$value.'</div>', 
			);
		}
		$json = getJSONobj();
		if($inJSON)
			return str_replace('&quot;', '\"', $json->encode($arr));
		else
			return $arr;
	}

	function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean, $singleSelect = false) {

		echo '<script type="text/javascript" src="include/ECM/EcmPreviewPDF/EcmPreviewPDF.js"></script>';
		echo '<script type="text/javascript" src="modules/EcmInsideOrders/ListView.js"></script>';
		echo '<link rel="stylesheet" type="text/css" href="modules/EcmInsideOrders/ListView.css" />';
		echo '<script language="javascript"> var EcmInsideOrdersStatusMenu = '.$this->getStatusMenuInfo().'; </script>';
		
		
		return parent::create_new_list_query($order_by, $where, $filter, $params, $show_deleted, $join_type, $return_array, $parentbean, $singleSelect);
	}

	static function CreateImgStatus($id, $status) {
		global $app_list_strings;
//		return '<span id="statusListEcmInsideOrder_'.$id.'" onClick="list_showStatusMenu(\''.$id.'\');"><img src="modules/EcmInsideOrders/images/'.$status.'.gif" title="'.$app_list_strings['ecminsideorders_status_dom'][$status].'" /></span>';
//		return '<span id="statusListEcmInsideOrder_'.$id.'" onClick="list_showStatusMenu(\''.$id.'\');"><img src="modules/EcmInsideOrders/images/'.$status.'.gif" title="'.$app_list_strings['ecminsideorders_status_dom'][$status].'" /></span>';
		$sta=$status;
		if($status=="Delivered" or $status=="Approved")$status="accepted";
		if($status=="Created" or $status=="Approved")$status="registered";
		return '<span id="statusListEcmInsideOrder_'.$id.'"><img src="modules/EcmInsideOrders/images/'.$status.'.gif" title="'.$app_list_strings['ecminsideorders_status_dom'][$sta].'" /></span>';

	}

	function generateOptions($icon,$module='',$action='') {
	
		global $app_strings;
		
		$tmp  = '';
		
			$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select o.pw_id from ecminsideorders as o where o.id='".$this->id."'"));
			$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select count(*) as c from ecmstockdocinsideins where id='".$r['pw_id']."'"));

		
		if($icon == "confirming") {
			if($this->ACLAccess('import')) {	
			$tmp .= '<span id="confirmingListEcmInsideOrder_'.$this->id.'" style="display:'.($this->ACLAccess('confirming')?'':'none').';"><img border="0" src="modules/EcmInsideOrders/images/accept_enabled.gif" title="'.translate('LBL_LIST_ACCEPT','EcmInsideOrders').'" onClick="list_setQuoteStatus(\''.$this->id.'\',\'s30\');" style="cursor:pointer;" />&nbsp;';	
			$tmp .= '<img border="0" src="modules/EcmInsideOrders/images/reject_enabled.gif" title="'.translate('LBL_LIST_REJECT','EcmInsideOrders').'" onClick="list_setQuoteStatus(\''.$this->id.'\',\'s40\');" style="cursor:pointer;" />&nbsp;&nbsp;&nbsp;|</span>';	
			}
		} else 
		if($icon == 'send_to_confirm') {
		
			//send to confirm
			if($this->ACLAccess('send_to_confirm'))
				$tmp = '<img border="0" id="send_to_confirm_'.$this->id.'" src="modules/EcmInsideOrders/images/sendtoconfirm_enabled.gif" title="'.translate('LBL_LIST_SEND_TO_CONFIRM','EcmInsideOrders').'" style="cursor:pointer;" onClick="list_setQuoteStatus(\''.$this->id.'\',\'s20\');" />';
			else
				$tmp = '<img border="0" id="send_to_confirm_'.$this->id.'" src="modules/EcmInsideOrders/images/sendtoconfirm_disabled.gif" title="'.translate('LBL_LIST_SEND_TO_CONFIRM','EcmInsideOrders').'" />';
			
		} else 
		if($icon == "convert_to_invoice") {
		
//convert to invoice
			if($this->ACLAccess('quote_to_invoice'))
				$tmp = '<img border="0" id="convert_to_invoice_'.$this->id.'" src="modules/EcmInsideOrders/images/convert_enabled.gif" title="'.translate('LBL_LIST_TO_INVOICE','EcmInsideOrders').'" onClick="javascript:window.location=\'index.php?module=EcmInvoiceOuts&action=EditView&out_id='.$this->id.'&out_module=EcmInsideOrders&return_module=EcmInsideOrders&return_action=index\';" style="cursor:pointer;" />';
			else
				$tmp = '<img border="0" id="convert_to_invoice_'.$this->id.'" src="modules/EcmInsideOrders/images/convert_disabled.gif" title="'.translate('LBL_LIST_TO_INVOICE','EcmInsideOrders').'" />';
		
		} else 
		if($icon == 'convert_to_sale') {
			if($this->ACLAccess('quote_to_sale')) 
				$tmp = '<img border="0" id="convert_to_sale_'.$this->id.'" src="modules/EcmInsideOrders/images/create_sales_enabled.gif" title="'.translate('LBL_LIST_TO_SALE','EcmInsideOrders').'" onClick="javascript:window.location=\'index.php?module=EcmSales&action=EditView&out_id='.$this->id.'&out_module=EcmInsideOrders&return_module=EcmInsideOrders&return_action=index\';" style="cursor:pointer;" />';
			else
				$tmp = '<img border="0" id="convert_to_sale_'.$this->id.'" src="modules/EcmInsideOrders/images/create_sales_disabled.gif" title="'.translate('LBL_LIST_TO_SALE','EcmInsideOrders').'" />';
		} else
		if($icon == 'pdf') {
				
			//pdf
			if($this->ACLAccess('pdf_toolbar')) {
			$tmp = '<img border="0" src="modules/EcmInsideOrders/images/pdf.gif" title="'.translate('LBL_LIST_PREVIEW_PDF','EcmInsideOrders').'" onClick="EcmPreviewPDF(\'index.php?module=EcmInsideOrders&action=previewPDF&method=I&record='.$this->id.'&to_pdf=1\',{zoom:75,toolbar:1});" style="cursor:pointer" />';			
			} else {
			$tmp = '<img border="0" src="modules/EcmInsideOrders/images/pdf.gif" title="'.translate('LBL_LIST_PREVIEW_PDF','EcmInsideOrders').'" onClick="EcmPreviewPDF(\'index.php?module=EcmInsideOrders&action=previewPDF&method=I&record='.$this->id.'&to_pdf=1\',{zoom:75,toolbar:0});" style="cursor:pointer" />';			
			}
		
		} else 
		if($icon == 'download') {
				
			//download
			if($this->ACLAccess('pdf_toolbar')) {
			$tmp = '<img border="0" src="modules/EcmInsideOrders/images/download_enabled.gif" title="'.translate('LBL_LIST_DOWNLOAD_PDF','EcmInsideOrders').'" onClick="window.location=\'index.php?module=EcmInsideOrders&action=previewPDF&method=D&record='.$this->id.'&to_pdf=1\';" style="cursor:pointer"/>';			
			} else {
			$tmp = '<img border="0" src="modules/EcmInsideOrders/images/download_disabled.gif" title="'.translate('LBL_LIST_DOWNLOAD_PDF','EcmInsideOrders').'"/>';			
			}
		
		} else		
		
		if($icon == 'duplicate') {
		
			//duplicate
			$tmp = '<a href="index.php?module=EcmInsideOrders&action=EditView&record='.$this->id.'&isDuplicate=true"><img border="0" src="modules/EcmInsideOrders/images/duplicate.jpg" title="'.translate('LBL_LIST_DUPLICATE','EcmInsideOrders').'" /></a>';
		
		} else 
		if($icon == 'edit') {
  
   			//edit
   			if($r['c']==0) 
    			$tmp = '<img border="0" id="edit_'.$this->id.'" src="modules/EcmInsideOrders/images/edit_inline_enabled.gif" title="'.$app_strings['LBL_EDIT_BUTTON'].'" onClick="javascript:window.location=\'index.php?module=EcmInsideOrders&action=EditView&record='.$this->id.'&return_module='.$_REQUEST['module'].'&return_action='.$_REQUEST['action'].'&return_id='.$_REQUEST['record'].'\';" style="cursor:pointer;" />';
   			else
    			$tmp = '<img border="0" id="edit_'.$this->id.'" src="modules/EcmInsideOrders/images/edit_inline_disabled.gif" title="'.$app_strings['LBL_EDIT_BUTTON'].'" style="cursor:pointer;" />'; 
  
		} else
		if($icon == 'send_email') {
		
			//send_email
			if($r['c']>0) 
				$tmp = '<img border="0" id="sendemail_'.$this->id.'" src="modules/EcmInsideOrders/images/send_email_enabled.gif" title="'.translate('LBL_SENDEMAIL_BUTTON','EcmInsideOrders').'" onClick="javascript:window.location=\'index.php?module=EcmInsideOrders&action=DetailView&send_email=1&record='.$this->id.'\'" style="cursor:pointer;" />';
			else
				$tmp = '<img border="0" id="sendemail_'.$this->id.'" src="modules/EcmInsideOrders/images/send_email_disabled.gif" title="'.translate('LBL_SENDEMAIL_BUTTON','EcmInsideOrders').'" style="cursor:pointer;" />';	
		
		} else
		if($icon == 'create_production') {

			
			//create_pz
			if($r['c']==0) 
				$tmp = '<img border="0" id="create_production_'.$this->id.'" src="modules/EcmInsideOrders/images/create_pz_enabled.gif" title="Create Production" onClick="javascript:window.location=\'index.php?module=EcmInsideOrders&action=makeProduction&record='.$this->id.'\'" style="cursor:pointer;" />';
			else
				$tmp = '<img border="0" id="create_production_'.$this->id.'" src="modules/EcmInsideOrders/images/create_pz_disabled.gif" title="Create Production" style="cursor:pointer;" />';
		}
				
		return $tmp;
	}


	function ListIconsView() {

		if(isset($_REQUEST['module']) && $_REQUEST['module'] != '' && isset($_REQUEST['action'])) {
			$module = $_REQUEST['module'];
			$action = $_REQUEST['action'];
			
			$glue = "&nbsp;";
			$viewIcons = array();
			if($module == $this->module_dir) {//This module, action ListView or index
				//$viewIcons = array( 'confirming', 'send_to_confirm', 'convert_to_sale', 'convert_to_invoice', 'send_email', 'download', 'pdf', 'duplicate', 'edit' );
				if($this->status=="registered" || $this->status=="Created")$viewIcons = array('send_email', 'create_production','download', 'pdf', 'duplicate', 'edit' );
				elseif($this->status=="accepted" || $this->status=="Delivered" || $this->status=="Approved")$viewIcons = array('send_email', 'create_production', 'download', 'pdf', 'duplicate', 'edit' );
			}
			else
			if($module == "Home") { //This is for a Home module for Dashlets
				$glue = "&nbsp;";
				//$viewIcons = array( 'confirming', 'convert_to_invoice', 'download', 'pdf', 'duplicate', 'edit' );
				if($this->status=="registered" || $this->status=="Created")$viewIcons = array('send_email', 'create_production','download', 'pdf', 'duplicate', 'edit' );
				elseif($this->status=="accepted" || $this->status=="Delivered" || $this->status=="Approved")$viewIcons = array('send_email', 'create_production', 'download', 'pdf', 'duplicate', 'edit' );
			} else { //this is for subpanels, popups
				$glue = "&nbsp;";
				if($this->status=="registered" || $this->status=="Created")$viewIcons = array('send_email', 'create_production','download', 'pdf', 'duplicate', 'edit' );
				elseif($this->status=="accepted" || $this->status=="Delivered" || $this->status=="Approved")$viewIcons = array('send_email', 'create_production', 'download', 'pdf', 'duplicate', 'edit' );
			}
			
			$arr = array();
			foreach($viewIcons as $value) {
				$tmp = $this->generateOptions($value);
				if($tmp != '') $arr[] = $tmp;
			}
			
			return '<span id="optionsListEcmInsideOrder_'.$this->id.'">'.implode($glue,$arr).'<script language="javascript">var ListQuotesModule="'.$module.'"; var ListQuotesAction="'.$action.'";</script></span>';
		}
		return '';
	}

    function createPdfFileName($format=true) {
	  global $mod_strings;
      
	  $arr1 = Array('\\', '/', ':', '*', '?' , '"',  '<', '>', '|', ' ');

      $arr2 = Array('',  '', '',  '',  '',   '\'', '[', ']', '', '_');

      $tmp = $this->document_no;

      if($format) 

        $tmp = str_replace($arr1, $arr2, $mod_strings['LBL_PDF_FILENAME'].$tmp.'.pdf');

      else

        $tmp = $mod_strings['LBL_PDF_FILENAME'].$tmp.'.pdf';

      //$mod = return_module_language($current_language, 'EcmInvoiceOuts'); 

      //return urlencode(

//      return $mod['LBL_PDF_INVOICE_FILE_NAME'].$tmp.'.pdf';//);

      return $tmp; //);

    }

  

    /**

    BUILDS A GENERIC SEARCH BASED ON THE QUERY STRING USING OR.

    DO NOT INCLUDE ANY $THIS-> BECAUSE THIS IS CALLED ON WITHOUT HAVING THE CLASS INSTANTIATED.

    */

    function build_generic_where_clause ($the_query_string) {

      $where_clauses = Array();

      $the_query_string = PearDatabase::quote(from_html($the_query_string));

      array_push($where_clauses, "ecminsideorders.name like '$the_query_string%'");

      $the_where = "";

      foreach($where_clauses as $clause) {

        if($the_where != "") $the_where .= " or ";

        $the_where .= $clause;

      }

      return $the_where;

    }

  

    function set_notification_body($xtpl, $simplemodule)  {

      global $mod_strings, $app_list_strings;    

      $xtpl->assign("NAME", $simplemodule->name);

      $xtpl->assign("DESCRIPTION", $simplemodule->description);

      return $xtpl;

    }

  

    function bean_implements($interface)  {

      switch($interface)  {

        case 'ACL':return true;

      }

      return false;

    }



    function save($check_notify = FALSE)  {
      
      global $current_user;
      if(($this->fetched_row && $this->fetched_row['template_id'] != $this->template_id) || (empty($this->id) || $this->id == '')) {
	  	$this->number = $this->generateNumber(); 
      	$this->document_no = $this->formatNumber();
	  }

      $return_id = parent::save($check_notify);

	  EcmInsideOrder::setStatus($return_id,$this->status);

      if(count($this->position_list) > 0) $this->deleteAssignedPositions($return_id);

      

      $pl = $this->position_list;

	  $total=0;
      for($i=0; $i<count($pl); $i++) {   

        require_once('modules/EcmInsideOrders/EcmProductsEcmInsideOrdersRelation.php'); 

        $ep = new EcmProductsEcmInsideOrdersRelation();   

        if($pl[$i]['name'] == '') continue;
        
        $ep->product_position = $i;
        $ep->date_entered = $this->date_entered;
        $ep->date_modified = $this->date_modified;
        $ep->modified_user_id = $this->modified_user_id;
        $ep->assigned_user_id = $this->assigned_user_id;
        $ep->created_by = $this->created_by;
        $ep->ecminsideorder_id = $return_id;
        $ep->ecmproduct_id = $pl[$i]['id'];
        $ep->product_code = $pl[$i]['code'];
        $ep->product_name = $pl[$i]['name'];
        $ep->product_quantity = $pl[$i]['quantity'];
        $ep->product_prod_quantity = $pl[$i]['prod_quantity'];
        $ep->product_price = $pl[$i]['price'];
        $ep->product_total = $pl[$i]['total'];  
        $ep->product_component = $pl[$i]['component'];
        $ep->product_component_quantity = $pl[$i]['component_quantity'];
        $ep->product_product_id = $pl[$i]['product_id'];
        $ep->product_guid = $pl[$i]['guid'];
        $ep->product_position = $i;
        $ep->unformated_numbers = true;
	 $total+=$ep->product_total;
        $eid=$ep->save();

      }

      $GLOBALS['db']->query("update ecminsideorders set total='".$total."' where id='".$return_id."'");
	
      return $return_id;

    }

    static function getTranslation($module,$id,$language) {
		if(isset($id) && $id != '' && isset($module) && $module != '') {
			global $beanList, $beanFiles;
			$file = $beanFiles[$beanList[$module]];
			if(file_exists($file)) {
				require_once($file);
				$bean = new $beanList[$module]();
				$bean->retrieve($id);
				if(isset($bean->id) && $bean->id != '') {
				  if(isset($bean->translations[$language]) && $bean->translations[$language] != '') return $bean->translations[$language];
				}
			}
		}
		return null;
	}


    function getTemplateList() {

      $query = "select `id`,`name` from `ecmdocumenttemplates` where `deleted`='0' order by `name`";

      $result = $GLOBALS['db']->query($query);

      $arr = array();

      if($result)

        while($row = mysql_fetch_assoc($result))

          $arr[$row['id']] = $row['name'];

      return $arr;

    } 

    

    function setTemplate() {

      if(!isset($this->template_id) || $this->template_id == '') return null;

      if(isset($this->template)) return $this->template;

      

      require_once('modules/EcmDocumentTemplates/EcmDocumentTemplate.php');

      $this->template = new EcmDocumentTemplate();

      //$this->template->retrieve($this->template_id);
	  $this->template->retrieve($this->template_id, true, false);


      if(isset($this->template->id) && $this->template->id != '') {

        $this->template->format_all_fields();

      } 

      else

        $this->template = null;

        

      return $this->template;

    }

    

    function generateNumber() {
	  $this->setTemplate();
      $this->number = isset($this->template) ? $this->template->generateNumber($this->table_name) : '';
      return $this->number;
    }  

    function formatNumber() {
      $this->setTemplate();
      $this->document_no = isset($this->template) ? $this->template->formatNumber($this->number, $this->module_dir) : ''; 
      return $this->document_no;
    }   

    function formatDocumentNumber($documentNumber = '', $code = '') {
      return isset($this->template) ? $this->template->formatDocumentNumber($documentNumber, $code) : ''; 
    }

    

    function getPosition($id) {

      if(!isset($id) || $id == '') return '';

      require_once('modules/EcmInsideOrders/EcmProductsEcmInsideOrdersRelation.php');

      $ep = new EcmProductsEcmInsideOrdersRelation();

      $ep->retrieve($id);

      $return_array = array();

      if(isset($ep->id) && $ep->id != '') {
        $return_array['id'] = $ep->ecmproduct_id;
        $return_array['code'] = $ep->product_code;
        $return_array['name'] = $ep->product_name;
        $return_array['quantity'] = $ep->product_quantity;
        $return_array['prod_quantity'] = $ep->product_prod_quantity;
        $return_array['price'] = $ep->product_price;
        $return_array['total'] = $ep->product_total;
        $return_array['component'] = $ep->product_component;
        $return_array['component_quantity'] = $ep->product_component_quantity;
        $return_array['product_id'] = $ep->product_product_id;
        $return_array['guid'] = $ep->product_guid;

        return $return_array;

      }

      return '';

    }



    function getPositionList($array = false) {
      if(isset($this->id) && $this->id != '') {
        $query = "SELECT `id` FROM `ecmproducts_ecminsideorders` WHERE `ecminsideorder_id`='".$this->id."' AND`deleted`='0' order by product_guid asc,product_component asc";
        $r = $this->db->query($query);
        $return_array = array();
        if($r) {
          while($w = $this->db->fetchByAssoc($r)) {
            $return_array [] = $this->getPosition($w['id']);
          }
          $json = getJSONobj();
          return $array ? $return_array : $json->encode($return_array);
        }
      }
      return $array ? false : '[]';
    }
    function deleteAssignedPositions() {
      if(isset($this->id) && $this->id != '') {
        $query = "DELETE FROM `ecmproducts_ecminsideorders` WHERE `ecminsideorder_id`='".$this->id."'";
        $r = $this->db->query($query);
        if($r) return true;
      }
      return false;          
    }
    function DrawPositions($pdf = null) {
	  global $mod_strings;
      if(!isset($this->position_list) || !is_array($this->position_list))
        $this->position_list = $this->getPositionList(true);
      $calc = $this->calculate($this->position_list,true);
      $this->position_list = $this->formatPositions($this->position_list);
      
      $calc['total'] .= ' '.$this->currency_symbol;
      $calc['subtotal'] .= ' '.$this->currency_symbol;
      if($calc['discount']) {
        $calc['total2'] .= ' '.$this->currency_symbol;
        $calc['discount']['value'] .= ' '.$this->currency_symbol;
      }

      $name_w = 29;
      $table = array(); 
      $table [0]['position'] = array('width' => 5, 'value' => $mod_strings['LBL_PDF_LIST_POSITION'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b');
      $table [0]['code'] = array('width' => 12, 'value' => $mod_strings['LBL_PDF_LIST_CODE'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b');
      $table [0]['description'] = array('width' => $name_w, 'value' => $mod_strings['LBL_PDF_LIST_DESCRIPTION'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b');
      $table [0]['quantity'] = array('width' => 12, 'value' => $mod_strings['LBL_PDF_LIST_QUANTITY'],'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b');
      $table [0]['prod_quantity'] = array('width' => 12, 'value' => "Il. prod.",'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b');
      $table [0]['unit_price'] = array('width' => 14, 'value' => $mod_strings['LBL_PDF_LIST_PRICE'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b');
      $table [0]['total'] = array('width' => 16, 'value' => $mod_strings['LBL_PDF_LIST_TOTAL'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b');

      $i = 1;
      if($this->position_list != '')
      foreach($this->position_list as $p) {
	  	$no++;
	    if($p['component']!=1)$n=$no;
		else $n="";
		if($p['prod_quantity']==0)$pq="";
		else $pq=$p['prod_quantity'];
        $table [$i]['position'] = array('width' => 5, 'value' => $n, 'border' => 0, 'align' => 'R', );
        $table [$i]['code'] = array('width' => 12, 'value' => $p['code'], 'border' => 0, 'align' => 'L', );
        $table [$i]['description'] = array('width' => $name_w, 'value' => htmlspecialchars_decode($p['name']), 'border' => 0, 'align' => 'L', );
        $table [$i]['quantity'] = array('width' => 12, 'value' => $p['quantity'], 'border' => 0, 'align' => 'C', );
        $table [$i]['prod_quantity'] = array('width' => 12, 'value' => $pq, 'border' => 0, 'align' => 'C', );
        if($p['component']!=1){
			$table [$i]['price'] = array('width' => 14, 'value' => $p['price'], 'border' => 0, 'align' => 'R', );
        	$table [$i]['total'] = array('width' => 16, 'value' => $p['total'], 'border' => 0, 'align' => 'R', );
		}
		$i++;
      }

      $pdf->DrawTable($table,array(0));
      //total, vat, subtotal

      $pdf->Ln(4);
      $pr = ($pdf->fw-$pdf->lMargin-$pdf->rMargin)/100;
      //$pdf->SetX($pdf->fw-$pdf->rMargin-$pr*34);
      $table = array();    

      $table [] = array(
        'total1' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_END_TOTAL'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 9, 'font-style' => 'b'),
        'total2' => array('width' => 34, 'value' => $calc['total'], 'border' => 0, 'background' => array(233,233,233), 'overflow' => 1, 'align' => 'R' , 'font-size' => 9, 'font-style' => 'b'), );
      
      $pdf->DrawTable($table);
    }  


    function DrawMainPDF($pdf) {


	  global $mod_strings;
	  
	  $arr = $this->template->getTemplateFile($_REQUEST['module'], $this->invoice_type);
    	$pdf->setAutoPageBreak(false, 40);
	  //if(!$arr[0])
	  $arr[0]="EcmInsideOrders";
	  //if(!$arr[1])
	  $arr[1]="e5";
	  include_once("modules/EcmDocumentTemplates/templates/".$arr[0]."/".$arr[1]."/subheader.php");
	  //$this->DrawPositions($pdf);
	  include_once("modules/EcmDocumentTemplates/templates/".$arr[0]."/".$arr[1]."/subfooter.php");

    }

    function getPDF($id = null,$method = 'I',$name = null) {
      global $sugar_config;
      if($id != null) {
        $this->retrieve($id);
        if($this->id == '') return;
      }

      global $mod_strings;
	  require_once('modules/EcmTexts/EcmText.php');
	  if(isset($this->ecmlanguage) && $this->ecmlanguage != '') {
		  $data = EcmText::LoadText(null,null,"EcmInsideOrders",$this->ecmlanguage);
		  if(isset($data[0]) && isset($data[0]['data']) && isset($data[0]['data']['labels'])) {
			$data = $data[0]['data']['labels'];
			foreach($data as $key => $value) {
				$mod_strings[$value['label']] = $value['translation'];
			}
		  }
	  }

      $this->format_all_fields();
      $this->setTemplate();

      if(isset($this->template->id) && $this->template->id != '') {
        $this->template->setPDF($this->template_id);
        $this->DrawMainPDF($this->template->pdf);
        $this->template->outputPDF((($name) ? $name : $this->createPdfFileName()),$method);
      }
    }     
    function calculate($position_list, $format = false) {

      if(!is_array($position_list)) return false;

      $result = Array('total' => 0.0, 'vats' => false, 'subtotal' => 0.0, 'draw_vat' => false, 'draw_discount' => false);

      $vats = Array();

      

      foreach($position_list as $p) {

        if(!isset($vats[$p['vat_id']])) $vats[$p['vat_id']] = 0;

        $vats[$p['vat_id']] += floatval($p['total']);

        $result['subtotal'] += floatval($p['total']);

        if(!$result['draw_discount'] && floatval($p['discount']) > 0) $result['draw_discount'] = true;

      }

      

      $result['total'] = $result['subtotal'];

  

      if(!$this->to_is_vat_free) {

        $vats2 = Array();

        foreach($vats as $key => $value) {
		  $r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select value from ecmvats where id='".$key."'"));
		  $vva=$r['value'];

          if(!$format) $vats2[$key] = $value*(floatval($vva)/100); 
		  else $vats2[$key] = format_number($value*(floatval($vva)/100));        

          $result['total'] += $value*(floatval($vva)/100);

        }

        asort($vats2,SORT_NUMERIC);

        $result['vats'] = $vats2;

        if(count($result['vats'])>1) $result['draw_vat'] = true;

      }
      
      $discount = $this->discount;
      if(!is_float($discount)) $discount = unformat_number($discount);

      if(isset($discount) && $discount != 0 && $discount != '') {
        $result['discount'] = array (
          'procent' => format_number(floatval($discount)).'%',
          'value' => $result['subtotal']*$discount/100,
        );
        $result['total2'] = $result['total'];
        $result['total'] = $result['total']-$result['discount']['value']; 
      }

      if($format) {
      
        if(isset($result['discount']) && isset($result['discount']['value']) && $result['discount']['value'] != '' && $result['discount']['value'] != 0) {
          $result['discount']['value'] = format_number($result['discount']['value']);
          $result['total2'] = format_number($result['total2']);
        }
      
        $result['total'] = format_number($result['total']); 

        $result['subtotal'] = format_number($result['subtotal']);

      }

      

      return $result;

    }



    function formatPositions($position_list) {

      if(!is_array($position_list) || count($position_list) == 0) return false;

      global $app_list_strings;


      require_once('modules/Currencies/Currency.php');
      foreach($position_list as $key => $value) {  

        //$position_list[$key]['unit_id'] = $app_list_strings['ecmproducts_unit_dom'][$value['unit_id']];

        $position_list[$key]['category_id'] = $app_list_strings['ecmproducts_category_dom'][$value['category_id']];

        $position_list[$key]['vat_id'] = format_number($value['vat_id']).'%';

        $position_list[$key]['discount'] = format_number($value['discount']).'%';

        if(isset($currency) && ($currency->id == $this->currency_id)) {}
        else {
		      $currency = new Currency();
		      $currency->retrieve($this->currency_id);
		    }
        $position_list[$key]['price'] = format_number($value['price']).' '.$currency->iso4217;

        $position_list[$key]['total'] = format_number($value['total']).' '.$currency->iso4217;

        $this->currency_symbol = $currency->iso4217;
      }
      return $position_list;

    }



    function loadParser() {
      $this->template->mfp->clear();
      $this->template->mfp->add("EcmInsideOrders","purchase_",$this);
      $this->template->mfp->add("Users","user_",$this->setUser());
      if($this->setAccount() != null)
        $this->template->mfp->add("Accounts",'account_',$this->account);
      if($this->setContact() != null)
        $this->template->mfp->add("Contacts",'contact_',$this->contact);      
      if($this->setEcmVendor() != null)
	    $this->template->mfp->add("EcmVendors",'ecmvendor_',$this->ecmvendor);
		
      $this->template->mfp->add("EcmDocumentTemplates","documenttemplate_",$this->template);
    }
    
    function loadParserArray($name = '') {
      require_once('modules/EcmDocumentTemplates/ModuleFieldsParser/ModuleFieldsParser.php');
      $mfp = new ModuleFieldsParser();
      $mfp->clear();

      global $app_list_strings;

      $mfp->add("EcmInsideOrders","purchase_",'',$app_list_strings['moduleList']['EcmInsideOrders']);
      $mfp->add("Users","user_",'',$app_list_strings['moduleList']['Users']);
      $mfp->add("Accounts",'account_','',$app_list_strings['moduleList']['Accounts']);
      $mfp->add("Contacts",'contact_','',$app_list_strings['moduleList']['Contacts']);
      $mfp->add("EcmVendors",'ecmvendor_','',$app_list_strings['moduleList']['EcmVendors']);
      $mfp->add("EcmDocumentTemplates","documenttemplate_",'',$app_list_strings['moduleList']['EcmDocumentTemplates']);
      
      if($name == '') {
        $mfp_arr = array(
          'header' => $mfp->getFormHTML(false, 'header'),
          'footer' => $mfp->getFormHTML(false, 'footer'),
          'ads' => $mfp->getFormHTML(false, 'ads'),
        );
      } else $mfp_arr = $mfp->getFormHTML(false,$name);
      return $mfp_arr;
    }

    

    function setAccount() {
        require_once('modules/Accounts/Account.php');
        $this->account = new Account();
        $this->account->retrieve($this->parent_id);
        return $this->account;
    }
    function setContact() {
      require_once('modules/Contacts/Contact.php');
      $us = new Contact();
      $us->retrieve($this->contact_id);
      $this->contact = $us;
      return $this->contact;
    }
	function setEcmVendor() {
      require_once('modules/EcmVendors/EcmVendor.php');
      $ev = new EcmVendor();
      $ev->retrieve($this->parent_id);
      $this->ecmvendor = $ev;
      return $this->ecmvendor;
    }


    function setUser() {
      if(is_object($this->user)) return $this->user;
      require_once('modules/Users/User.php');
      $us = new User();
      global $current_user;
      $us->retrieve(($this->assigned_user_id)?$this->assigned_user_id:$current_user->id);
      if(isset($us->id) && $us->id != '') {
        $this->user = $us;
      } 
      else
        $this->user = null;
      return $this->user;
    }

    function doNotAccepted() {
      global $current_user;
      $cq = $current_user->getPreference('confirm_quotes');
      if(isset($cq) && $cq) {
        $query = "UPDATE `ecminsideorders` SET `status` = 'not_accepted',`accepted` = '0' WHERE CONVERT( `id` USING utf8 ) = '".$this->id."' LIMIT 1 ;";
        $result = $this->db->query($query);
        if($result) {
          $this->status = 'not_accepted';
          $this->accepted = 0;
        }
      }  
    }

    function ACLAccess($view,$is_owner='not_set')
    {
    	global $current_user;
		$file = 'modules/EcmGroupSales/EcmGroupSale.php';
		if(file_exists($file)) {
			require_once($file);
			$cc = EcmGroupSale::loadSettings(true);
		} else return true;
		
		if(is_admin($current_user)) {
			switch ($view)
			{
				case 'confirming':
					return ($this->status == "s20");
				case 'send_to_confirm':
					return ($this->status == "s10");
				case 'pdf_toolbar':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
			}		
			return true;
		}

    	if($is_owner == 'not_set')
    	{
    		$is_owner = $this->isOwner($current_user->id);
    	}
		
		//if we don't implent acls return true
    	if(!$this->bean_implements('ACL'))
    	return true;
		$view = strtolower($view);

		if($cc['user_manager_role']) { //Manager
			switch ($view)
			{
				case 'list':
				case 'index':
				case 'listview':
					return ACLController::checkAccess($this->module_dir,'list', true);
				case 'edit':
				case 'save':
				case 'popupeditview':
				case 'editview':
					return (ACLController::checkAccess($this->module_dir,'edit', $is_owner));
				case 'view':
				case 'detail':
				case 'detailview':
					return ACLController::checkAccess($this->module_dir,'view', $is_owner);
				case 'delete':
					return ACLController::checkAccess($this->module_dir,'delete', $is_owner);
				case 'export':
					return ACLController::checkAccess($this->module_dir,'export', $is_owner);
				case 'import':
					return ACLController::checkAccess($this->module_dir,'import', true);
				case 'send_to_confirm':
					return ($this->status == "s10");
				case 'can_commit':
					return true;
				case 'confirming':
					return ($this->status == "s20");
				case 'auto_commiting':
					return true;
				case 'pdf_toolbar':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
			}
			
		
		} else
		if($cc['user_representative_extra_role']) { //Representative Extra
		
			switch ($view)
			{
				case 'list':
				case 'index':
				case 'listview':
					return ACLController::checkAccess($this->module_dir,'list', true);
				case 'edit':
					return (ACLController::checkAccess($this->module_dir,'edit', $is_owner) && ($this->status == "s10" || $this->status == "s40"));
				case 'save':
				case 'popupeditview':
				case 'editview':
					return (ACLController::checkAccess($this->module_dir,'edit', $is_owner));
				case 'view':
				case 'detail':
				case 'detailview':
					return ACLController::checkAccess($this->module_dir,'view', $is_owner);
				case 'delete':
					return (ACLController::checkAccess($this->module_dir,'delete', $is_owner) && $this->status == "s10");
				case 'export':
					return ACLController::checkAccess($this->module_dir,'export', $is_owner);
				case 'import':
					return ACLController::checkAccess($this->module_dir,'import', true);
				case 'quote_to_sale':
				case 'quote_to_invoice':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60");
				case 'send_to_confirm':
					return ($this->status == "s10");
				case 'send_email':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
				case 'can_commit':
					return true;
				case 'confirming':
					return false;
				case 'auto_commiting':
					return true;
				case 'pdf_toolbar':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
			}
		} else
		if($cc['user_representative_role']) { //Representative
		
			switch ($view)
			{
				case 'list':
				case 'index':
				case 'listview':
					return ACLController::checkAccess($this->module_dir,'list', true);
				case 'edit':
					return (ACLController::checkAccess($this->module_dir,'edit', $is_owner) && ($this->status == "s10" || $this->status == "s40"));
				case 'save':
				case 'popupeditview':
				case 'editview':
					return (ACLController::checkAccess($this->module_dir,'edit', $is_owner));
				case 'view':
				case 'detail':
				case 'detailview':
					return ACLController::checkAccess($this->module_dir,'view', $is_owner);
				case 'delete':
					return (ACLController::checkAccess($this->module_dir,'delete', $is_owner) && $this->status == "s10");
				case 'export':
					return ACLController::checkAccess($this->module_dir,'export', $is_owner);
				case 'import':
					return ACLController::checkAccess($this->module_dir,'import', true);
				case 'quote_to_sale':
				case 'quote_to_invoice':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60");
				case 'send_to_confirm':
					return ($this->status == "s10");
				case 'send_email':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
				case 'can_commit':
					return false;
				case 'confirming':
					return false;
				case 'auto_commiting':
					return false;
				case 'pdf_toolbar':
					return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
			}
		}
    	//if it is not one of the above views then it should be implemented on the page level
    	return true;
    }

	function getUserSatusAccess() {
		global $current_user;
		require_once('modules/EcmInsideOrders/StatusAccess.php');		
		
		$file = 'modules/EcmGroupSales/EcmGroupSale.php';
		if(file_exists($file)) {
			require_once($file);
			$cc = EcmGroupSale::loadSettings(true);
		}

		

	}

	static function setStatus($record,$status) {
	
		global $app_list_strings, $mod_strings;
		$arr = array ();
		
		require_once('modules/EcmInsideOrders/EcmInsideOrder.php');
		$focus = new EcmInsideOrder();
		
		if($focus->ACLAccess('auto_commiting') && $status == "s20") $status = "s30"; 
			
		$query = "UPDATE ecminsideorders SET status='$status' WHERE id='$record' AND deleted='0'";
		$result = $GLOBALS['db']->query($query);
		
		if(!$result) {
			$arr['message'] = $mod_strings["LBL_STATUS_".$status."_FAIL_MESSAGE"];
		} else {
			$arr['record']  = $record;
			$arr['status']  = array( 'text' => $app_list_strings['ecminsideorders_status_dom'][$status], 'code' => $status, 'image' => EcmInsideOrder::CreateImgStatus($record,$status) );
			$arr['message'] = $mod_strings["LBL_STATUS_".$status."_SET_MESSAGE"];
			if(isset($_REQUEST['ListQuotesModule']) && $_REQUEST['ListQuotesModule'] != '' && isset($_REQUEST['ListQuotesAction']) && $_REQUEST['ListQuotesAction'] != '') {
				
				$m_old = $_REQUEST['module']; $a_old = $_REQUEST['action'];
				$_REQUEST['module'] = $_REQUEST['ListQuotesModule']; $_REQUEST['action'] = $_REQUEST['ListQuotesAction'];
				
				$focus->id = $record;
				$focus->status = $status;
				$arr['list_images'] = $focus->ListIconsView();
				
				$_REQUEST['module'] = $m_old; $_REQUEST['action'] = $a_old;

			}
		}

		if(isset($status)) {
			$file = 'modules/EcmGroupSales/EcmGroupSale.php';
			$cc = array();
			if(file_exists($file)) {
				require_once($file);
				$cc = EcmGroupSale::loadSettings(true);	
			}
			
			if($status == 's20') 
				if(isset($cc['default_manager_role_id']) && $cc['default_manager_role_id'] != '')
					foreach($cc['default_manager_role_id'] as $key => $manager_role_id) {
						EcmInsideOrder::SetReminder($record, 'EcmInsideOrders', $arr['status']['image'].' '.$arr['status']['text'], $manager_role_id);
					}

			if(($status == 's30' || $status == 's40')) { // && !$focus->ACLAccess('auto_commiting')
				EcmInsideOrder::SetReminder($record, 'EcmInsideOrders', $arr['status']['image'].' '.$arr['status']['text']);
			}
			if($status == 's10') {
				//deleting before reminders 
				$query = "DELETE FROM `ecmreminders` WHERE `parent_id`='$record'";
				$GLOBALS['db']->query($query);				
			}
			
		}
		return $arr;
	}
	
	static function SetReminder($parent_id, $parent_name, $status, $role_id = '') {
		$file = 'modules/EcmReminders/EcmReminder.php';

		if(file_exists($file)) {
			
			$name = 'EcmInsideOrders - Status Change';
			$query = "SELECT name, assigned_user_id FROM ecminsideorders WHERE id='$parent_id' LIMIT 1";
			$result = $GLOBALS['db']->query($query);
			if($result) {
				$row = $GLOBALS['db']->fetchByAssoc($result);
				if($row && isset($row['name'])) $name = $row['name'];
				if($row && isset($row['assigned_user_id']) && $row['assigned_user_id'] != '') $assigned_user_id = $row['assigned_user_id'];
			}
			
			if(!isset($assigned_user_id) || $assigned_user_id == '') {
				global $current_user;
				$assigned_user_id = $current_user->id;
			}
			
			//deleting before reminders 
			$query = "DELETE FROM `ecmreminders` WHERE `parent_id`='$parent_id'";
			if(isset($role_id) && $role_id != '') $query .= " AND `role_id`='$role_id'"; else $query .= " AND `role_id` IS NULL";
			$GLOBALS['db']->query($query);

			require_once($file);
			$reminder = new EcmReminder();
			$reminder->assigned_user_id = $assigned_user_id;
			$reminder->name = $name;
			$reminder->reminder_time = 0;
			$reminder->parent_id = $parent_id;
			$reminder->parent_name = $parent_name;
			$reminder->role_id = $role_id;
			$reminder->status = $status;
			global $timedate;		
			$reminder->date_start = $timedate->to_display_date_time(gmdate('Y-m-d H:i:s'));
			$reminder->save(FALSE);
		}		
	}


  }

?>