HEX
Server: Apache/2.2.15 (CentOS)
System: Linux ip-10-0-2-146.eu-west-1.compute.internal 2.6.32-754.35.1.el6.centos.plus.x86_64 #1 SMP Sat Nov 7 11:33:42 UTC 2020 x86_64
User: root (0)
PHP: 5.6.40
Disabled: NONE
Upload Files
File: /www/exchange2/exchange/classes/Model/Validation/FormValidation.php
<?php
class Model_Validation_FormValidation extends Lib_Validation_Handler
{
	var $nullmessage;
	var $urlmessage;
	var $emailmessage;
	var $spcharmessage;
	var $imagemessage;
	var $numbermessage;
	var $limitmessage;
	var $doctypemessage;
	var $docsizemessage;
    var $checkpaymentdiscountogui;
    var $uniquepomessage;
    var $allowedoetrmessage;
    var $allowedoetrfordetrmessage;
    var $oEtrLimitError;
    var $passwordlengthmessage;
    var $samepasswordmessage;
    var $existpomessage;
    var $requireddocumentmessage;
    var $invaliddatemessage;
	var $formatmessage;
	var $maxpercentvaluemessage;
	var $minpercentvaluemessage;

    function Model_Validation_FormValidation($form, $values = array())
	{
		$this->nullmessage = "Mandatory field";
		$this->urlmessage = "Invalid website address";
		$this->emailmessage = "Invalid Email Address!";
		$this->spcharmessage = "No special characters.";
		$this->imagemessage = "Invalid Image";
		$this->numbermessage = "Only numbers are permitted";
		$this->stringmessage = "Strings Not allowed";
		$this->limitmessage = "Exceeds the limit ";
		$this->charmessage = "No Numbers Allowed";
		$this->txtonlymessage = "Character Only Allowed";
		$this->phonemessage = "Use numbers only. No spaces permitted";
		$this->doctypemessage = "Upload Account Document only in the format PDF";
		$this->docsizemessage = "Account Document  size should be less than 4MB";
		$this->checkpaymentdiscountogui = "The entered value is too large. Please enter a maximum of XX.XX %";
		$this->uniquepomessage = "PO number must be unique";
		$this->allowedoetrmessage = "You can not use this o-ETR";
		$this->allowedoetrfordetrmessage = "PO balance for this PO is exceeded";
        $this->oEtrLimitError = 'Limit of this o-ETR is exceeded. Please select Unscheduled c-ETR checkbox if you want use this o-ETR';
        $this->samepasswordmessage = 'The user should not be able to set the same password again';
        $this->passwordlengthmessage = "Password must contain 8 or more characters";
        $this->existpomessage = 'This PO number has already been used. Enter another PO number.';
        $this->requireddocumentmessage = 'The list of documents does not match the required';
        $this->invaliddatemessage = 'Invalid date';
		$this->formatmessage="Invalid Format!";
		$this->maxpercentvaluemessage="The Value must be between 0 and 100 (%)!";
		$this->minpercentvaluemessage="The Value cannot be less than ";

		($form == 'registerdebtor') ? $this->registrationDebtorValidate() : '';
		($form == 'savetrader') ? $this->savetraderValidate() : '';
		($form == 'saveDraftTrade') ? $this->saveDraftTrade() : '';
		($form == 'valrevolvingtrade') ? $this->validateRevolvingTrade() : '';


		($form == 'openbidnow') ? $this->openbidnow() : '';
		($form == 'updatebidnow') ? $this->updatebidnow() : '';
		($form == "valApplicationUpload") ? $this->validateApplicationUpload() : "";
		($form == "valApplicationOne") ? $this->validateApplicationOne() : "";
		($form == "valApplicationTwo") ? $this->validateApplicationTwo() : "";
		($form == "valApplicationThree") ? $this->validateApplicationThree() : "";
		($form == "valApplicationFour") ? $this->validateApplicationFour() : "";
		($form == "valApplicationFive") ? $this->validateApplicationFive() : "";
		($form == "valApplicationFive_Two") ? $this->validateApplicationFive_Two() : "";
		($form == "valApplicationSix") ? $this->validateApplicationSix() : "";
		($form == "valApplicationSixCEtr") ? $this->validateApplicationSixCEtr() : "";
		($form == "valApplicationSeven") ? $this->validateApplicationSeven() : "";


		($form == "saveMyTrade") ? $this->saveMyTrade() : "";
		($form == "saveMyTradePassword") ? $this->saveMyTradePassword() : "";
		($form == "saveMyTradeQuestion") ? $this->saveMyTradeQuestion() : "";
		($form == "saveMyProfile") ? $this->saveMyProfile() : "";
		($form == "saveMyInvPassword") ? $this->saveMyInvPassword() : "";
		($form == "saveMyInvQuestion") ? $this->saveMyInvQuestion() : "";


		($form == "checklogin") ? $this->loginValidate() : "";
		($form == "addinvestorone") ? $this->validateAddInvestor() : "";
		($form == "addinvestortwo") ? $this->validateAddInvestorTwo() : "";

		($form == "investorcompose") ? $this->investorCompose() : "";
		($form == "tradercompose") ? $this->traderCompose() : "";

		($form == "validatePayment") ? $this->validatePayment() : "";

		($form == "updateDebtorApplications") ? $this->updateDebtorApplication() : "";
		($form == "updateDebtorHistory") ? $this->updateDebtorHistory() : "";

		($form == "valbranchapplication") ? $this->valBranchApplication() : "";

		($form == "valaddinvestor") ? $this->valAddInvestor() : "";

		($form == "valIntermedProfile") ? $this->valIntermedProfile() : "";
		($form == "valIntermedPassword") ? $this->valIntermedPassword() : "";
		($form == "valIntermedQuestion") ? $this->valIntermedQuestion() : "";

		($form == "addintermediaryone") ? $this->validateIntermediaryOne() : "";
		($form == "addintermediarytwo") ? $this->validateIntermediaryTwo() : "";

		($form == "addintrminvestorone") ? $this->validateAddIntrmInvestor() : "";
		($form == "addintrminvestortwo") ? $this->validateAddIntrmInvestorTwo() : "";

		($form == "valApplicationBegin") ? $this->validateApplicationBegin() : "";

		($form == "valeditOrganisation") ? $this->valeditOrganisation() : "";

		($form == "valeditAddress") ? $this->valeditAddress() : "";

		($form == "valEditBankAddress") ? $this->valEditBankAddress() : "";

		($form == "valEditBankContact") ? $this->valEditBankContact() : "";

		($form == "valEditBankAccount") ? $this->valEditBankAccount() : "";

		($form == "valEditContactDetails") ? $this->valEditContactDetails() : "";

		($form == "valEditOwnerDetails") ? $this->valEditOwnerDetails() : "";

		($form == "valEditTradeAccount") ? $this->valEditTradeAccount() : "";

		($form == "valEditTradeSub") ? $this->valEditTradeSub() : "";

		($form == "valEditTradeDoc") ? $this->valEditTradeDoc() : "";

		($form == "valEditAudit") ? $this->valEditAudit() : "";

		($form == "valEditAuditProfit") ? $this->valEditAuditProfit() : "";



		($form == "valretailinvreg") ? $this->valRetailInvestorReg() : "";



		($form == "valRetailProfile") ? $this->valRetailProfile() : "";
		($form == "retailercompose") ? $this->retailerCompose() : "";
		($form == "saveMyRetPassword") ? $this->saveMyRetPassword() : "";
		($form == "saveMyRetQuestion") ? $this->saveMyRetQuestion() : "";

		($form == "saveNewUser") ? $this->saveNewUser() : "";
		($form == "checkdetails") ? $this->checkDetails() : "";

		($form == "chkoriginatorcurrency") ? $this->chkOriginatorCurrency() : "";

		($form == "saveNewInvUser") ? $this->saveNewInvUser() : "";
		($form == "saveNewIntermedUser") ? $this->saveNewIntermedUser() : "";
		($form == "saveNewRetailerUser") ? $this->saveNewRetailerUser() : "";

		($form == "saveTransactionUpdate") ? $this->saveTransactionUpdate() : "";

		($form == 'saveinstalmentETR') ? $this->saveinstalmentETR() : '';

		($form == "saveManualTrans") ? $this->saveManualTransactions() : "";
        ($form == "valreplacedebdoc") ? $this->validateReplaceDebtorDoc() : "";

        ($form == "valPensionProfile") ? $this->valPensionProfile() : "";

		($form == "validateDebtorContactCreate") ? $this->validateDebtorContactCreate(): "";
		($form == "validateDebtorContactUpdate") ? $this->validateDebtorContactUpdate(): "";

		($form == "save_orpa") ? $this->saveOrpaValidate(): "";
		($form == "save_upload_orpa") ? $this->saveUploadOrpaValidate(): "";
		($form == "save_revolving_orpa") ? $this->saveRevolvingOrpaValidate(): "";
		($form == "validate_post_trade_documents") ? $this->validatePostTradeDocuments($values): "";
	}


    function valPensionProfile(){

        $this->Assign("email", $_POST["email"],"noempty",
                        "".$this->nullmessage);

        $this->Assign("f_name", $_POST["f_name"],"noempty",$this->nullmessage);

        $this->Assign("l_name", $_POST["l_name"],"noempty",$this->nullmessage);

        $this->Assign("job", $_POST["job"],"noempty",$this->nullmessage);

        $this->Assign("org_name", $_POST["org_name"],"noempty",$this->nullmessage);

        $this->Assign("org_addr", $_POST["org_addr"],"noempty",$this->nullmessage);

//         $this->Assign("org_addr1", $_POST["org_addr1"],"noempty/nostring/nospecial' '",
//                                 "".$this->nullmessage.
//                                 "/".$this->numbermessage.
//                                 "/".$this->spcharmessage);

        $this->Assign("org_code", $_POST["org_code"],"noempty/nostring/nospecial' '",
                                "".$this->nullmessage.
                                "/".$this->numbermessage.
                                "/".$this->spcharmessage);
        $this->Assign("org_state", $_POST["org_state"],"nospecial' '",
                                "".$this->spcharmessage);
        $this->Assign("org_country", $_POST["org_country"],"noempty/nostring/nospecial' '",
                                "".$this->nullmessage.
                                "/".$this->numbermessage.
                                "/".$this->spcharmessage);
        $this->Assign("org_ph_country", $_POST["org_ph_country"],"noempty/nostring/nospecial' '",
                                "".$this->nullmessage.
                                "/".$this->numbermessage.
                                "/".$this->spcharmessage);
        $this->Assign("org_ph_area", $_POST["org_ph_area"],"noempty/nostring/nospecial' '",
                                "".$this->nullmessage.
                                "/".$this->numbermessage.
                                "/".$this->spcharmessage);
        $this->Assign("org_ph_phone", $_POST["org_ph_phone"],"noempty/nostring/nospecial' '",
                                "".$this->nullmessage.
                                "/".$this->numbermessage.
                                "/".$this->spcharmessage);
        $this->Assign("org_m_country", $_POST["org_m_country"],"nostring/nospecial' '",
                                "".$this->numbermessage.
                                "/".$this->spcharmessage);
        $this->Assign("org_m_area", $_POST["org_m_area"],"nostring/nospecial' '",
                                "".$this->numbermessage.
                                "/".$this->spcharmessage);
        $this->Assign("org_m_phone", $_POST["org_m_phone"],"nostring/nospecial' '",
                                "".$this->numbermessage.
                                "/".$this->spcharmessage);


        $this->PerformValidation('index.php?do=editpensionprofile');
    }


	function saveManualTransactions()
    {
	   $this->Assign("transaction_type", $_POST['transaction_type'],"noempty","".$this->nullmessage);
	   if(in_array($_POST['transaction_type'], array(
	   		TRANSFER_OF_PAYMENT_BY_ORIGINATOR,
	   		ORIGINATOR_PAYMENT_ON_ACCOUNT,
	   		INBOUND_CREDITOR_PAYMENT,
	   		ORIGINATOR_DEPOSIT,
	   	))){
	   		$this->Assign("transaction_type", null, "noempty", "Creating this type of transaction is prohibited");
	   }

		$this->Assign("trans_date",$_POST['trans_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("trans_date",$_POST['trans_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("trans_date",$_POST['trans_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		if($_POST['trans_date']!='' && $_POST['trans_month']!='' && $_POST['trans_year']!='')
        {
			if(!checkdate($_POST['trans_month'],$_POST['trans_date'],$_POST['trans_year']))
            {
				$this->Assign("trans_date",'',"noempty","Enter a valid date");
			}
		}

		$trans_date= $_POST['trans_year']."-".$_POST['trans_month']."-".$_POST['trans_date'];
		$query			= new Bin_Query();
		$sql 			= " SELECT DATEDIFF('".$trans_date."',NOW()) as day ";
		$query->executeQuery($sql);
		$payment_today 		= $query->records;


		if($_POST['trans_year']!='' && $_POST['trans_month']!='' && $_POST['trans_date']!='' AND $payment_today[0]['day'] > 0)
		{
			$this->Assign("trans_date","","noempty","Date should be today's date or an earlier date only");
		}
        
        if (strtotime($trans_date)<strtotime(FIRST_TRADE_DATE))
        {
            $this->Assign("trans_date","","noempty","Date should be greater than '".FIRST_TRADE_DATE."'");
        }
        
        
		if( $_POST['transaction_type']!=ORIGINATOR_PAYMENT_ON_ACCOUNT and $_POST['transaction_type']!= ORIGINATOR_DEPOSIT and  $_POST['transaction_type']!= DEPOSIT_TO_OCPA )
        {
			$this->Assign("debtor_id", $_POST['debtor_id'],"noempty","".$this->nullmessage);
		}

	    if( $_POST['transaction_type'] == ORIGINATOR_DEPOSIT  )
	    {
		    $this->Assign("orpa_id", $_POST['orpa_id'],"noempty","".$this->nullmessage);
	    }

		if(in_array($_POST['transaction_type'],array(INBOUND_DEBTOR_PAYMENT,TRANSFER_OF_PAYMENT_BY_ORIGINATOR,RECONCILE_DEBTOR_ACCOUNT,INBOUND_CREDITOR_PAYMENT,RECONCILE_CREDITOR_ACCOUNT)))
        {
            $_POST['reference_to']=array_filter($_POST['reference_to']);

            if(isset($_POST['trade_select']) && empty($_POST['reference_to']))
            {
                $this->Assign("reference_to","","noempty","".$this->nullmessage);
			}
            elseif(in_array($_POST['transaction_type'],array(RECONCILE_DEBTOR_ACCOUNT,RECONCILE_CREDITOR_ACCOUNT)) && $_POST['reconcile_payment']!='0' && empty($_POST['reference_to']))
            {
                $this->Assign("reference_to","","noempty","".$this->nullmessage);
			}
		}

		if(in_array($_POST['transaction_type'],array(RECONCILE_DEBTOR_ACCOUNT,RECONCILE_CREDITOR_ACCOUNT)))
        {
            $this->Assign("reconcile_payment", $_POST['reconcile_payment'],"noempty","".$this->nullmessage);
			$query->executeQuery("SELECT count(manual_transaction_id) as reconcile 
                                  FROM manual_transactions 
                                  WHERE manual_transaction_id='".$_POST['reconcile_payment']."' AND reconcile_ref<>'0' ");

            if($query->records[0]['reconcile']>0)
            {
                $this->Assign("reconcile_payment", "","noempty","This transaction is processed in Reconcile payment. You cannot process again.");
            }
		}

        if (in_array($_POST['transaction_type'],array(RECONCILE_DEBTOR_ACCOUNT,RECONCILE_CREDITOR_ACCOUNT)))
        {
            $field=($_POST['transaction_type']==DATED_RESERVE_PAYMENT)?'paying_reserve':'reference_to';

            if (count($_POST[$field])>0)
            {
                $invoices=$transactions=array();
                foreach(array_filter($_POST[$field]) as $item)
                {
                    $credit_notes = explode('_',$item);
                    $credit_count = count($credit_notes);

                    if(count($credit_notes)==1)
                    {
                        $query->executeQuery('SELECT manual_transaction_id
                                              FROM manual_transactions
                                              WHERE  transaction_type='.$_POST['transaction_type'].' AND debtor_id='.$_POST['debtor_id'].' AND FIND_IN_SET('.$item.',reference_to)>0');
                        if (count($query->records)>0)
                        {
                             $this->Assign($field,"","noempty","Some of invoices already in use");
                             break;
                        }
                        
                        $invoices[]=$item;
                    }
                    else
                    {
                        $query->executeQuery('SELECT manual_transaction_id
                                              FROM manual_transactions
                                              WHERE  transaction_type='.$_POST['transaction_type'].' AND debtor_id='.$_POST['debtor_id'].' AND FIND_IN_SET('.$credit_notes[0].',transref_list)>0');
                        if (count($query->records)>0)
                        {
                             $this->Assign($field,"","noempty","Some of CN,TB,SD already in use");
                             break;
                        }
                        
                        $transactions[]=$credit_notes[0];
                    }
                }
                
                if (count($invoices)>0)
                {
                    $query->executeQuery('SELECT COUNT(invoice_master.invoice_id) as invoices
                                          FROM invoice_master
                                          LEFT JOIN debtors_detail ON debtors_detail.debtor_id = invoice_master.debtor_id
                                          WHERE invoice_master.invoice_id IN ('.implode(',',$invoices).') AND invoice_master.debtor_id='.$_POST['debtor_id'].'  AND debtors_detail.`type`="'.($_POST['transaction_type']==RECONCILE_CREDITOR_ACCOUNT?'creditor':'debtor').'" AND invoice_master.root_invoice_id>0');
                    
                    if (count($invoices)<>$query->records[0]['invoices'])
                    {
                        $this->Assign($field,"","noempty","Some of invoices belong to another debtor");
                    }
                }
                $invoices=array();
                
                if (count($transactions)>0)
                {
                   $query->executeQuery('SELECT COUNT(manual_transactions.manual_transaction_id) as transactions
                                         FROM manual_transactions
                                         WHERE manual_transactions.manual_transaction_id IN ('.implode(',',$transactions).') AND manual_transactions.`status`=1 AND manual_transactions.debtor_id='.$_POST['debtor_id']);
                   
                   if (count($transactions)<>$query->records[0]['transactions'])
                   {
                       $this->Assign($field,"","noempty","Some of transactions belong to another debtor");
                   }
                }
                $transactions=array();
            }
        }

		if(in_array($_POST['transaction_type'],array(INBOUND_DEBTOR_PAYMENT,TRANSFER_OF_PAYMENT_BY_ORIGINATOR,CREDIT_NOTE,ORIGINATOR_PAYMENT_ON_ACCOUNT, ORIGINATOR_DEPOSIT, DEPOSIT_TO_OCPA, NOTICE_OF_DEBTOR_REMITTANCE,BANK_TRANSMISSION_RECEIPT,INBOUND_CREDITOR_PAYMENT)) || (in_array($_POST['transaction_type'],array(RECONCILE_DEBTOR_ACCOUNT,RECONCILE_CREDITOR_ACCOUNT)) && $_POST['reconcile_payment']!='0'))
        {
            $_POST['amount']=empty($_POST['amount'])?NULL:round($_POST['amount'],2);
            $_POST['amountval']=empty($_POST['amountval'])?0:round($_POST['amountval'],2);

			if(is_null($_POST['amount']))
            {
				$this->Assign("amount", $_POST['amount'],"noempty/nostring' '","".$this->nullmessage."/".$this->numbermessage);
			}
			elseif($_POST['amount']<=0)
            {
				$this->Assign("amount", "","noempty","Enter Value greater than 0 ");
			}
            elseif($_POST['amount']!=0)
            {
                if(($_POST['amount']!=$_POST['amountval']) && (isset($_POST['trade_select']) OR in_array($_POST['transaction_type'],array(RECONCILE_DEBTOR_ACCOUNT,RECONCILE_CREDITOR_ACCOUNT))) && $_POST['reference_to'][0]!='')
                {
                    if(isset($_POST['check_trailing']) || isset($_POST['check_deductible']))
                    {
                        $balance_amt = round(($_POST['amount']-$_POST['trailing_balance_amt']+$_POST['balance_deductible']) - $_POST['amountval'],2);
                    }
                    else
                    {
                        $balance_amt = round($_POST['amount'] - $_POST['amountval'],2);
                    }

					$ins_flag=0;
					$qry 	= new Bin_Query();
					for($t=0;$t<count($_POST['reference_to']);$t++)
                    {
						$qry->executeQuery("SELECT per_instalment_amt,instalment,sales_type 
                                            FROM invoice_master 
                                            WHERE invoice_id='".$_POST['reference_to'][$t]."' && instalment='1' 
                                            LIMIT 1 ");
						$instalment = $qry->records[0];

						if(count($instalment)>0)
                        {
							$ins_flag=1;
                            if($instalment['sales_type']=='5' && $_POST['amount']!=$instalment['per_instalment_amt'])
                            {
                                $this->Assign("amount", "","noempty","The selected instalment invoice should have ".$instalment['per_instalment_amt']." value in the Amount field.");
                            }
						}
					}

					if(in_array($_POST['transaction_type'],array(INBOUND_DEBTOR_PAYMENT,TRANSFER_OF_PAYMENT_BY_ORIGINATOR,RECONCILE_DEBTOR_ACCOUNT,INBOUND_CREDITOR_PAYMENT,RECONCILE_CREDITOR_ACCOUNT)) && $ins_flag!=1 && ($balance_amt !=0 ))
                    {
                        $field=(in_array($_POST['transaction_type'],array(RECONCILE_DEBTOR_ACCOUNT,RECONCILE_CREDITOR_ACCOUNT)))?'reconcile_payment':'amount';

                        $this->Assign($field, "" ,"noempty","The invoices selected do not add up to the value in the Amount field. Select the correct invoice(s) and Submit again ");
                    }
                    elseif( ( $_POST['transaction_type']==ORIGINATOR_PAYMENT_ON_ACCOUNT or $_POST['transaction_type']== DEPOSIT_TO_OCPA ) && $ins_flag!=1)
                    {
						$this->Assign("amount", "" ,"noempty","The invoices selected do not add up to the value in the Amount field. Select the correct invoice(s) and Submit again");
					}
				}
                elseif(in_array($_POST['transaction_type'],array(RECONCILE_DEBTOR_ACCOUNT,RECONCILE_CREDITOR_ACCOUNT)) && ($_POST['amount']!=$_POST['amountval']))
                {
					$this->Assign("reconcile_payment", "" ,"noempty","The invoices selected do not add up to the value in the Amount field. Select the correct invoice(s) and Submit again");
				}
			}

			if( $_POST['transaction_type']==ORIGINATOR_PAYMENT_ON_ACCOUNT or $_POST['transaction_type']== ORIGINATOR_DEPOSIT )
            {
				$this->Assign("currency_id", $_POST['currency_id'],"noempty","".$this->nullmessage);
			}
		}

		if(in_array($_POST['transaction_type'],array(NOTICE_OF_DEBTOR_REMITTANCE,RECONCILE_DEBTOR_ACCOUNT,BANK_TRANSMISSION_RECEIPT,CREDIT_NOTE,RECONCILE_CREDITOR_ACCOUNT)))
		{
			if($_FILES['transaction_file']['tmp_name'] =='')
            {

			}
            elseif($_POST['transaction_type']!=RECONCILE_DEBTOR_ACCOUNT)
            {
				$type = $_FILES['transaction_file']['type'];
			}
		}

	    if($_POST['transaction_type']==CREDIT_NOTE)
        {
		    if($_FILES['transaction_file']['tmp_name'] =='')
		    {
			    $this->Assign("transaction_file",$_POST['transaction_file'],"noempty","Please attach a Credit Note PDF document!");
		    }
            else
            {
			    $mime = array('application/download','application/pdf', 'application/x-download');

			    if(!in_array($_FILES['transaction_file']['type'], $mime))
			    {
				    $this->Assign('transaction_file','',"noempty","The document must be in PDF format!");
			    }

			    if(defined('MAX_UPLOAD_DOCUMENT_SIZE')){
				    if(MAX_UPLOAD_DOCUMENT_SIZE < $_FILES['transaction_file']['size']){
					    include_once('../MHelpers.php');
					    $this->Assign('transaction_file','',"noempty","The size of the uploaded file is too large! (&gt; ".Model_MHelpers::formatBytes(MAX_UPLOAD_DOCUMENT_SIZE).")");
				    }
			    }


		    }
            $this->Assign('credit_note_no', $_POST['credit_note_no'], 'noempty', $this->nullmessage);
            if (!empty($_POST['credit_note_no'])) {
                $db = Bin_Db::connect();
                $selectCreditNoteNo = "SELECT * FROM manual_transactions
                WHERE credit_note_no = ':credit_note_no' AND debtor_id = ':debtor_id'";
                $creditNoteNoRes = $db->query($selectCreditNoteNo, array(
                    ':credit_note_no' => $_POST['credit_note_no'],
                    ':debtor_id' => $_POST['debtor_id'],
                ))->getNumRows();
                if ($creditNoteNoRes) {
                    $this->Assign('credit_note_no', '', 'noempty', 'Credit Note with this number is already used');
                }
            }
	    }

        if (!empty($_POST['trailing_balance_amt']) AND round($_POST['trailing_balance_amt'],2)<0)
        {
            $this->Assign("trailing_balance_amt", "","noempty","Trailing Balance must be > 0");
        }

        if (!empty($_POST['balance_deductible']) AND round($_POST['balance_deductible'],2)<0)
        {
            $this->Assign("balance_deductible", "","noempty","Specific Deductible must be > 0");
        }


        //Bug #390
        if (in_array($_POST['transaction_type'],array(RECONCILE_CREDITOR_ACCOUNT,RECONCILE_DEBTOR_ACCOUNT)) OR (in_array($_POST['transaction_type'],array(INBOUND_DEBTOR_PAYMENT,TRANSFER_OF_PAYMENT_BY_ORIGINATOR,PAID_DIRECTLY_TO_ORIGINATOR,INBOUND_CREDITOR_PAYMENT)) AND isset($_POST['trade_select']) && !empty($_POST['reference_to'])))
        {
            if (in_array($_POST['transaction_type'],array(RECONCILE_CREDITOR_ACCOUNT,RECONCILE_DEBTOR_ACCOUNT)))
            {
                $query->executeQuery('SELECT transaction_date
                                      FROM manual_transactions
                                      WHERE manual_transaction_id='.$_POST['reconcile_payment']);
                $max_date=$query->records[0]['transaction_date'];
            }
            else
            {
                $max_date=$trans_date;
            }

            include_once('admin/classes/Model/transaction_actions.php');
            list($active_invoices,$active_transactions)=Transaction_actions::getActiveInvoices();

            $active_invoices=array_flip($active_invoices);
            $active_transactions=array_flip($active_transactions);

            $all_items=Transaction_actions::getNonReconciledEntries($_POST['debtor_id'],$_SESSION['user']['userid'],TRUE,$max_date);

            foreach($all_items as $item)
            {
                if ($item['transaction_type']!='' AND isset($active_transactions[$item['manual_transaction_id']]))
                {
                    unset($active_transactions[$item['manual_transaction_id']]);
                }
                elseif($item['transaction_type']=='' AND isset($active_invoices[$item['invoice_id']]))
                {
                    unset($active_invoices[$item['invoice_id']]);
                }
            }

            if (count($active_transactions)>0 OR count($active_invoices)>0)
            {
                $this->Assign("reference_to", "","noempty","Incorrect invoice assignment. Contact Administrator.");
            }
        }

		$this->PerformValidation('index.php?do=addtransaction');
	}

	//Validates Open Trade Form
	function saveinstalmentETR(){

		$this->Assign("sales_type",$_POST['sales_type'],"noempty",
			"".$this->nullmessage);

		$sales_type=$_POST['sales_type'];
		$sales_arr=explode("-",$sales_type);
		$fieldSet=$sales_arr[1];
		$sales_type1= $sales_arr[0];



		if($_POST['discount_price']==''){
			$this->Assign("discount_price",$_POST['discount_price'],"noempty",
			"".$this->nullmessage);
		}elseif($_POST['discount_price']<=0){

			$this->Assign("discount_price",'',"noempty","It Should be greater than 0");
		}


		if($_POST['buyout']=="1")
		{
			if($_POST['buyout_discount_price']==''){
				$this->Assign("buyout_discount_price",$_POST['buyout_discount_price'],"noempty",
				"".$this->nullmessage);
			}elseif($_POST['buyout_discount_price']<=0){

				$this->Assign("buyout_discount_price",'',"noempty","It Should be greater than 0");
			}
		}

		if($sales_type=="5-model3")
		{

			if($_POST['etr_face_value']==''){
				$this->Assign("etr_face_value",$_POST['etr_face_value'],"noempty/nostring",
				"".$this->nullmessage."/".$this->numbermessage);
			}elseif($_POST['etr_face_value']<=0){

				$this->Assign("etr_face_value",'',"noempty","It Should be greater than 0");

			}else{

				if(!$this->validateSpecialChar($_POST['etr_face_value'])){
					$this->Assign("etr_face_value",'',"noempty",$this->spcharmessage);
				}
			}


			$qry 	= new Bin_Query();
			$sql 	= "SELECT type_id FROM `sales_types` WHERE status='1' AND (type_id='2' OR type_id='3') ORDER BY type_id ASC ";
			$qry->executeQuery($sql);

			if($qry->totrows>0){
			$this->Assign("etr_type",$_POST['etr_type'],"noempty/nostring",
			"".$this->nullmessage."/".$this->numbermessage);
			}


			if($_POST['etr_no']==''){
				$this->Assign("etr_no",$_POST['etr_no'],"noempty",
				"".$this->nullmessage);
			}elseif($_POST['etr_no']<=0){

				$this->Assign("etr_no",'',"noempty","It Should be greater than 0");
			}


			if($_POST['no_of_instalments']==''){
				$this->Assign("no_of_instalments",$_POST['no_of_instalments'],"noempty",
								"".$this->nullmessage);
			}elseif($_POST['no_of_instalments']<=0){

				$this->Assign("no_of_instalments",'',"noempty","It Should be greater than 0");
			}

			if($_POST['payments_remaining']==''){
				$this->Assign("payments_remaining",$_POST['payments_remaining'],"noempty",
								"".$this->nullmessage);
			}elseif($_POST['payments_remaining']<=0){

				$this->Assign("payments_remaining",'',"noempty","It Should be greater than 0");
			}

		}

		$this->Assign("country_id",$_POST['country_id'],"noempty/nostring/nospecial",
			"".$this->nullmessage.
			"/".$this->numbermessage.
			"/".$this->spcharmessage);

		$this->Assign("debtor_id",$_POST['debtor_id'],"noempty/nostring/nospecial",
			"".$this->nullmessage.
			"/".$this->numbermessage.
			"/".$this->spcharmessage);

		$debtor_id = trim($_POST['debtor_id']);



		if($debtor_id !=''){

			$user_id 		= $_SESSION['user']['userid'];
			$query			= new Bin_Query();
			$sql 			= " SELECT dm.*  FROM `debtors_detail` as d, `debtors_master` as dm, `debtor_relation` as r ".
							" WHERE r.trader_id ='".$user_id."' && r.debtor_id = '".$debtor_id."' && (r.status ='1' || r.status ='5' || r.status ='6' || r.status ='7' || r.status='8')".
							" && d.debtor_id = r.debtor_id && d.parent_id != 0 ".
							" && dm.debtor_master_id = d.parent_id  limit 1 ";
			$query->executeQuery($sql);
			$debtor 		= $query->records;


			$qry 			= new Bin_Query();
			$sql 			= "SELECT agreed_rate FROM `organisation_details` WHERE user_id='".$user_id."' ";
			$qry->executeQuery($sql);
			$agreed_rate 	= $qry->records[0]['agreed_rate'];


			if(count($debtor) > 0){

				if($fieldSet=="model1")
				{

					if($_POST['purchase_price']!=''){

						if($_POST['purchase_price'] < $agreed_rate){

						$this->Assign("purchase_price",$_POST['purchase_price'],"nonumber","The Outright Purchase price you are offering is lower than agreed rate. Increase it please");
						}

						// if($_POST['purchase_price'] < $debtor[0]['debtor_min_offers']){

						// $this->Assign("purchase_price",$_POST['purchase_price'],"nonumber","The Outright Purchase price you are offering is lower than minimum offer price. Increase it please");
						// }
					}

					if($_POST['purchase_price'] !=''  && $_POST['face_value'] != ''){

						$offer = ($debtor[0]['debtor_min_offers'] / 100 ) * $_POST['face_value'];


						if($_POST['purchase_price'] < $offer ){

							$this->Assign("purchase_price",$_POST['purchase_price'],"nonumber","The Outright Purchase price you are offering is too low. Increase it please");
						}
					}



					if($_POST['buyout_price'] != ''){

						if($_POST['buyout_price'] < $agreed_rate)

						$this->Assign("buyout_price",$_POST['buyout_price'],"nonumber","The Outright Purchase price you are offering is lower than agreed rate. Increase it please");
					}

					if($_POST['buyout_price'] !=''   && $_POST['face_value'] != ''){

						$offer = ($debtor[0]['debtor_min_offers'] / 100 ) * $_POST['face_value'];

						if($_POST['buyout_price'] < $offer ){

							$this->Assign("buyout_price",$_POST['buyout_price'],"nonumber","The Outright Purchase price you are offering is too low. Increase it please");
						}
					}

				}else if($fieldSet=="model2"){

						if(isset($_POST['buyout'])){


						if($_POST['discount_price']<=0){


							$this->Assign("discount_price",'',"noempty","It Should be greater than 0");
						}

						if($_POST['discount_price'] !='' && $_POST['discount_price'] < $agreed_rate ){

							$this->Assign("discount_price",$_POST['discount_price'],"nonumber","The Minimum Agreed Rate ".
														" permitted is currently ".$agreed_rate."% ".
														" (where ".$agreed_rate." is the Minimum Offer percentage".
														")");

						}

						if($_POST['discount_price'] !='' && $_POST['discount_price'] < $debtor[0]['debtor_min_offers'] ){

							$this->Assign("discount_price",$_POST['discount_price'],"nonumber","The Minimum Discount Percentage ".
														" permitted is currently ".$debtor[0]['debtor_min_offers']."% ".
														" (where ".$debtor[0]['debtor_min_offers']." is the Minimum Offer percentage".
														" figure for the specific Master Debtor)");

						}

						if($_POST['buyout_discount_price']<=0){

							$this->Assign("buyout_discount_price",'',"noempty","It Should be greater than 0");
						}

						if($_POST['buyout_discount_price'] !='' && $_POST['buyout_discount_price'] < $agreed_rate ){

							$this->Assign("buyout_discount_price",$_POST['buyout_discount_price'],"nonumber","The Minimum Agreed Rate ".
														" permitted is currently ".$agreed_rate."% ".
														" (where ".$agreed_rate." is the Minimum Offer percentage".
														")");

						}

						if($_POST['buyout_discount_price'] !='' && $_POST['buyout_discount_price'] < $debtor[0]['debtor_min_offers'] ){
							$this->Assign("buyout_discount_price",$_POST['buyout_discount_price'],"nonumber","The Minimum Discount".
														" Percentage permitted is currently ".$debtor[0]['debtor_min_offers']."% ".
														" (where ".$debtor[0]['debtor_min_offers']." is the Minimum Offer ".
														" Percentage figure for the specific Master Debtor)");
						}
					}
				}

			}
            else
            {
				$this->Assign("debtor_id",$_POST['debtor_id'],"nonumber","Debtor is Not Available");
			}
		}



		//$this->Assign("face_value",$_POST['face_value'],"noempty","Face Value -".$this->nullmessage);



		$mime = array('application/force-download','application/msexcel','application/x-ms-download','application/vnd.ms-excel','application/octet-stream','application/excel','application/x-excel','application/x-msexcel','application/vnd.ms-excel.sheet.macroEnabled.12','application/vnd.ms-excel.template.macroEnabled.12','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/pdf','application/x-pdf',
									'application/x-bzpdf',
									'application/x-gzpdf');



		//UPlaod File Check
		$dcnt =  count($_FILES);
		$tmp = 'file_invoice';
		for($d=1;$d<=$dcnt;$d++)
		{

			if($_FILES[$tmp]['tmp_name'] != "")
			{
// 				$type = explode('/',$_FILES[$tmp]['type']);
// 				$type = $type[1];
				$type = $_FILES[$tmp]['type'];
				if($_FILES[$tmp]['size'] <= 419430400)
				{
					if(!in_array($type, $mime))
					{
						$message = "Only PDF documents can be attached.Please attach a PDF";
						$this->Assign("invoicefile",'',"noempty",''.$message);
					}
				}
				else
				{
					$size_mes = "PDF Documents size should be less than 4MB";
					$this->Assign("invoicefile","","noempty",''.$size_mes);
				}
			}
			if($d==1)$tmp = 'file_support'; if($d==2)$tmp = 'file_po';
		}


		$uploadfile 			= array('file_invoice','file_support','file_po');

			foreach($uploadfile as $key){

				//Upload PDF FIle
				$file = $key;
				if($_FILES[$key]['tmp_name'] !=''){

					if($file=='file_invoice'){
						$upload_file = 'invoicefile';
					}elseif($file=='file_po'){
						$upload_file = 'pofile';
					}elseif($file=='file_support'){
						$upload_file = 'supportfile';
					}

					$exp 		= explode('_',$key);
					$name 		= $user_id;
					$dir 		= "../documents/debtor/".$name; //Creating Folder W.r.t Debtor Name and Trader Id

					if(!is_dir($dir)){
						mkdir($dir, 0777);//Folder Path assigning
					}

					$type 		= $_FILES[$file]['type'];

					chmod($dir, 0777);  //Folder Permission assigning

					//File Path assigning
					$path 		= pathinfo($_FILES[$file]["name"]);
					$file_name 	= $user_id.'_'.$key."_".time().".".$path['extension'];
					$dir_path 	= $dir."/".$file_name;

					$ext = pathinfo($_FILES[$file]['name'], PATHINFO_EXTENSION);

					if($_FILES[$tmp]['size'] <= 419430400)
					{
						if(!in_array($type, $mime))
						{

							$this->Assign($upload_file,'',"noempty","Only PDF documents can be attached.  Please attach a PDF");

						}elseif($ext =='pdf' || $ext =='PDF'){


							include_once('../include/pdf_parser_check.php');


							$ob = new pdf_parsers($_FILES[$file]['tmp_name']);


							if($ob->error !='1'){


								$this->Assign($upload_file,'',"noempty","This document probably uses a compression technique which is not supported");

							}else{

								// IT is Good to GO
								move_uploaded_file($_FILES[$file]["tmp_name"],$dir_path);
								chmod($dir."/".$file_name, 0777); //File Permission assigning

								$_SESSION[$upload_file] = $name."/".$file_name;
								// echo $name."/".$file_name;
								// exit;
							}

						}elseif(!empty($_FILES[$file]["tmp_name"])){


								move_uploaded_file($_FILES[$file]["tmp_name"],$dir_path);
								chmod($dir."/".$file_name, 0777); //File Permission assigning

								$_SESSION[$upload_file] = $name."/".$file_name;
								// echo $name."/".$file_name;
								// exit;

						}else{

							$this->Assign($upload_file,'',"noempty","This document probably uses a compression technique which is not supported");
						}
					}
					else{

						$this->Assign($upload_file,'',"noempty","File Upload Error, Please Try Again");

					}
				}
			}






		$query=new Bin_Query();
		$sql 				= " SELECT r.notify FROM `debtor_relation` as r where r.trader_id ='".$_SESSION['user']['userid']."' ".
							"  && r.debtor_id = '".$_POST['debtor_id']."'  limit 1 ";
		$query->executeQuery($sql);
		$debtors 			= $query->records;



		// if($debtors[0]['notify'] != '3'){
		// 	$this->Assign("ack_notice",$_POST['ack_notice'],"noempty","0");

		// }

		// $this->Assign("closing",$_POST['closing'],"noempty",
		// 	"".$this->nullmessage);

		if($_REQUEST['do']=='saveinstalmentdraft'){
			$this->PerformValidation('index.php?do=editinstalmentdraft&id='.$_REQUEST['id']);
		}else{
			$this->PerformValidation('index.php?do=instalment_etr');
		}


	}

	function saveTransactionUpdate(){

		$this->Assign("transaction_type", $_POST['transaction_type'],"noempty","".$this->nullmessage);


		$this->Assign("trans_date",$_POST['trans_date'],"noempty/nostring/nospecial","".$this->nullmessage.
										  "/".$this->numbermessage."/".$this->spcharmessage);

		$this->Assign("trans_date",$_POST['trans_month'],"noempty/nostring/nospecial","".$this->nullmessage.
										   "/".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("trans_date",$_POST['trans_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".
										  $this->numbermessage."/".$this->spcharmessage);

		if($_POST['trans_date']!='' && $_POST['trans_month']!='' && $_POST['trans_year']!=''){

			if(!checkdate($_POST['trans_month'],$_POST['trans_date'],$_POST['trans_year'])){

				$this->Assign("trans_date",'',"noempty","Enter a valid date");
			}
		}


		if($_POST['transaction_type']==TRANSFER_OF_PAYMENT_BY_ORIGINATOR || $_POST['transaction_type']==CREDIT_NOTE )
        {
			$this->Assign("debtor_id", $_POST['debtor_id'],"noempty","".$this->nullmessage);
		}

		if($_POST['transaction_type']==TRANSFER_OF_PAYMENT_BY_ORIGINATOR){

			if(count($_POST['debtor_id'])>1 && ($_POST['reference_to'][0]=='' || !isset($_POST['reference_to']))){


				$this->Assign("reference_to", '',"noempty","".$this->nullmessage);
			}elseif(isset($_POST['trade_select']) && !isset($_POST['reference_to'])){

				$this->Assign("reference_to", '',"noempty","".$this->nullmessage);

			}
		}

		if($_POST['transaction_type']==TRANSFER_OF_PAYMENT_BY_ORIGINATOR){

			for($j=0;$j<count($_POST['reference_to']);$j++){

					if(isset($_POST['trade_select']) && ($_POST['reference_to'][$j]=='' || !isset($_POST['reference_to']))){

						$this->Assign("reference_to", $_POST['reference_to'][$j],"noempty","".$this->nullmessage);
					}
			}
		}

		if($_POST['transaction_type']==TRANSFER_OF_PAYMENT_BY_ORIGINATOR || $_POST['transaction_type']==CREDIT_NOTE
			|| $_POST['transaction_type']==ORIGINATOR_PAYMENT_ON_ACCOUNT || $_POST['transaction_type']==ORIGINATOR_DEPOSIT){

			if($_POST['amount']==''){

				$this->Assign("amount", $_POST['amount'],"noempty/nostring' '",
								"".$this->nullmessage.
								"/".$this->numbermessage);
			}elseif($_POST['amount']==0){

				$this->Assign("amount", "","noempty",
								"Enter Value greater than 0 ");
			}elseif(($_POST['amount']!=$_POST['amountval']) && isset($_POST['trade_select']) && $_POST['reference_to'][0]!=''){

				$balance_amt = $_POST['amount'] - $_POST['amountval'];

				if($_POST['transaction_type']==TRANSFER_OF_PAYMENT_BY_ORIGINATOR && ($balance_amt < -1 || $balance_amt > 10 )){

					$this->Assign("notification", "" ,"noempty","The invoices selected do not add up to the value in the Amount field. Select the correct invoice(s) and Submit again");
				}elseif($_POST['transaction_type']==ORIGINATOR_PAYMENT_ON_ACCOUNT or $_POST['transaction_type']==ORIGINATOR_DEPOSIT)
				{

					$this->Assign("notification", "" ,"noempty","The invoices selected do not add up to the value in the Amount field. Select the correct invoice(s) and Submit again");
				}
			}


			if($_POST['transaction_type']==ORIGINATOR_PAYMENT_ON_ACCOUNT or $_POST['transaction_type']==ORIGINATOR_DEPOSIT ){

				$this->Assign("currency_id", $_POST['currency_id'],"noempty","".$this->nullmessage);
			}
		}



		if($_POST['transaction_type']==NOTICE_OF_DEBTOR_REMITTANCE || $_POST['transaction_type']==RECONCILE_DEBTOR_ACCOUNT || $_POST['transaction_type']==BANK_TRANSMISSION_RECEIPT)
		{

			if($_FILES['transaction_file']['tmp_name'] ==''){

				//$this->Assign("transaction_file",$_POST['transaction_file'],"noempty","Transaction File -".$this->nullmessage);
			}elseif($_POST['transaction_type']!=RECONCILE_DEBTOR_ACCOUNT){

				$type = $_FILES['transaction_file']['type'];

				/*$mime = array('application/force-download','application/msexcel','application/x-ms-download','application/vnd.ms-excel','application/octet-stream','application/excel','application/x-excel','application/x-msexcel','application/vnd.ms-excel.sheet.macroEnabled.12','application/vnd.ms-excel.template.macroEnabled.12','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

				if(in_array($type, $mime))
				{

					$this->Assign("transaction_file",$_POST['transaction_file'],"noempty","Transaction File - You cannot upload xls files for this transaction type");

				}*/

			}
		}

		// $this->Assign("notes", $_POST["notes"],"noempty","".$this->nullmessage);


		$this->PerformValidation('index.php?do=transupdate');
	}

	function saveNewRetailerUser(){
		$this->Assign("first_name", $_POST["first_name"],"noempty","".$this->nullmessage);
		$this->Assign("last_name", $_POST["last_name"],"noempty","".$this->nullmessage);

		$this->Assign("organisation_name", $_POST["organisation_name"],"noempty","".$this->nullmessage);

		// $this->Assign("country_id", $_POST['country_id'],"noempty",
		// 					"".$this->nullmessage);

		if($_POST['email']==''){
		$this->Assign("email", $_POST['email'],"noempty",
							"".$this->nullmessage);
		}else{
			if(!$this->isValidEmail($_POST['email'])){
				$this->Assign("email", "" ,"noempty",
							"Enter a valid email Address");
			}
		}

		$this->PerformValidation('index.php?do=addnewretailuser');
	}

	function saveNewIntermedUser(){
		$this->Assign("first_name", $_POST["first_name"],"noempty","".$this->nullmessage);
		$this->Assign("last_name", $_POST["last_name"],"noempty","".$this->nullmessage);

		$this->Assign("organisation_name", $_POST["organisation_name"],"noempty","".$this->nullmessage);

		// $this->Assign("country_id", $_POST['country_id'],"noempty",
		// 					"".$this->nullmessage);

		if($_POST['email']==''){
		$this->Assign("email", $_POST['email'],"noempty",
							"".$this->nullmessage);
		}else{
			if(!$this->isValidEmail($_POST['email'])){
				$this->Assign("email", "" ,"noempty",
							"Enter a valid email Address");
			}
		}

		$this->PerformValidation('index.php?do=addnewintuser');
	}


	function saveNewInvUser(){
		$this->Assign("first_name", $_POST["first_name"],"noempty","".$this->nullmessage);
		$this->Assign("last_name", $_POST["last_name"],"noempty","".$this->nullmessage);

		$this->Assign("organisation_name", $_POST["organisation_name"],"noempty","".$this->nullmessage);

		// $this->Assign("country_id", $_POST['country_id'],"noempty",
		// 					"".$this->nullmessage);

		if($_POST['email']==''){
		$this->Assign("email", $_POST['email'],"noempty",
							"".$this->nullmessage);
		}else{
			if(!$this->isValidEmail($_POST['email'])){
				$this->Assign("email", "" ,"noempty",
							"Enter a valid email Address");
			}
		}

		$this->PerformValidation('index.php?do=addnewinvuser');
	}


	function chkOriginatorCurrency()
    {
		$this->Assign("currency_id", $_POST["currency_id"],"noempty","".$this->nullmessage);

		if($_POST['bank_account']=='2')
        {
			$query16 			= new Bin_Query();
			$sql16				="SELECT orgbank.* , b.bank_name, b.bank_country, c.last_name, c.first_name, c.work_address_id, c.contact_id,org.user_id  FROM `organisation_bank_details` orgbank, `bank_details` as b, contact_details as c,organisation_details org WHERE org.user_id='".$_SESSION['user']['userid']."' AND org.organisation_id=orgbank.organisation_id && c.contact_id = orgbank.contact_id && c.position = '1'  && b.bank_id = orgbank.bank_id  order by orgbank.organisation_bank_id ASC limit 1";
			$query16->executeQuery($sql16);
			$branch_one 				= $query16->records[0];

				if(($branch_one['bank_id']==$_POST['bank_name']) && ($branch_one['bank_country'] == $_POST["country_id"])){

					$this->Assign("bank_name", "","noempty",
								"Please Select Use Existing Bank Account Option - Yes ");
				}else{
					$this->Assign("bank_name", $_POST['bank_name'],"noempty",
							"".$this->nullmessage);
				}

			$this->Assign("bank_orgcaddr1", $_POST['bank_orgcaddr1'],"noempty",
								"".$this->nullmessage);

			$this->Assign("bank_orgc_city", $_POST['bank_orgc_city'],"noempty",
								"".$this->nullmessage);

			$this->Assign("bank_orgc_country", $_POST['bank_orgc_country'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("bank_orgc_pc", $_POST['bank_orgc_pc'],"noempty/nospecial' '",
								"".$this->nullmessage."/".$this->spcharmessage);


			$this->Assign("bank_orgc_ph_country", $_POST['bank_orgc_ph_country'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("bank_orgc_ph_area", $_POST['bank_orgc_ph_area'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("bank_orgc_ph_pn", $_POST['bank_orgc_ph_pn'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("bank_orgc_fn_country", $_POST['bank_orgc_fn_country'],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("bank_orgc_fn_area", $_POST['bank_orgc_fn_area'],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("bank_orgc_fn_pn", $_POST['bank_orgc_fn_pn'],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);

			if($_POST['bank_orgc_email'] !='')	{
				if(!$this->isValidEmail($_POST['bank_orgc_email']))
				$this->Assign("bank_orgc_email", "","noempty",
									"".$this->emailmessage);
			}

			if($_POST['bank_c_email'] !='')	{

			if(!$this->isValidEmail($_POST['bank_c_email']))
			$this->Assign("bank_c_email", "","noempty",
								"".$this->emailmessage);
			}


			$this->Assign("account_name", $_POST['account_name'],"noempty",
								"".$this->nullmessage);

			$this->Assign("account_no", $_POST['account_no'],"noempty",
								"".$this->nullmessage);

			$this->Assign("sort_code", $_POST['sort_code'],"noempty",
								"".$this->nullmessage);

		}

		if(isset($_REQUEST['flg']))
			$this->PerformValidation('index.php?do=addoriginatorcurrency&flg='.$_REQUEST['flg']);
		else
			$this->PerformValidation('index.php?do=addoriginatorcurrency');
	}

	function checkDetails(){

		if($_POST['forgot_email']==''){
		$this->Assign("forgot_email", $_POST['forgot_email'],"noempty",
							"".$this->nullmessage);
		}else{

				if(!$this->isValidEmail($_POST['forgot_email'])){
					$this->Assign("forgot_email", "" ,"noempty",
							"Enter a valid email Address");
				}else{
                    require_once ROOT_FOLDER.'/classes/Model/MUser.php';
                    $userModel = new Model_MUser();

                    if(!$userModel->isUserExists($_POST['forgot_email'])){
						$this->Assign("forgot_email", "" ,"noempty",
								"Unable to find account associated with the provided email address. Please contact Support for further assistance.");
					}
				}
		}

		$this->PerformValidation('index.php?do=login');
	}


	function saveNewUser(){
		$this->Assign("first_name", $_POST["first_name"],"noempty","".$this->nullmessage);
		$this->Assign("last_name", $_POST["last_name"],"noempty","".$this->nullmessage);

		$this->Assign("organisation_name", $_POST["organisation_name"],"noempty","".$this->nullmessage);

		// $this->Assign("country_id", $_POST['country_id'],"noempty",
		// 					"".$this->nullmessage);

		if($_POST['email']==''){
		$this->Assign("email", $_POST['email'],"noempty",
							"".$this->nullmessage);
		}else{
			if(!$this->isValidEmail($_POST['email'])){
				$this->Assign("email", "" ,"noempty",
							"Enter a valid email Address");
			}
		}

		$this->PerformValidation('index.php?do=addnewuser');
	}

	function saveMyRetQuestion(){

		$this->Assign("secret_quest", $_POST["secret_quest"],"noempty","".$this->nullmessage);
		$this->Assign("secret_answer", $_POST["secret_answer"],"noempty","".$this->nullmessage);

		$this->PerformValidation('index.php?do=reteditdetails');
	}

	function saveMyRetPassword(){
		$user_id = $_SESSION['user']['userid'];

		$this->Assign("oldpasswd", $_POST["oldpasswd"],"noempty","".$this->nullmessage);
		$this->Assign("passwd", $_POST["passwd"],"noempty","".$this->nullmessage);
		$this->Assign("retype", $_POST["retype"],"noempty","".$this->nullmessage);

		if($_POST["oldpasswd"] !='')
		{
			$query = new Bin_Query();
			$sql_user = "SELECT * FROM temp_registration WHERE user_id = '".$user_id."'
				AND password = '" . Bin_Security::hashPassword($_POST["oldpasswd"]) . "'";
			$query->executeQuery($sql_user);
			$profile = $query->records;

			if(count($profile) == 0)
			{
				$message="Incorrect current password";
				$this->Assign("oldpasswd",'',"noempty",$message);
			}
		}


		if($_POST["passwd"] !='' && $_POST["retype"] !='')
		{
			if($_POST["passwd"] != $_POST["retype"])
			{
				$message="Incorrect password confirmation";
				$this->Assign("retype",'',"noempty",$message);
				$_POST["retype"]='';
			}
		}

        if (Bin_Security::hashPassword($_POST['oldpasswd']) === Bin_Security::hashPassword($_POST['passwd'])) {
            $this->Assign("passwd", '', "noempty", "" . $this->samepasswordmessage);
        }
        if(mb_strlen($_POST['passwd'])<8)
        {
            $this->Assign("passwd", '', "noempty", '' . $this->passwordlengthmessage);
        }

		$this->PerformValidation('index.php?do=reteditdetails');

	}

	// function saveMyRetPassword(){

	// 	$user_id = $_SESSION['user']['userid'];

	// 	$this->Assign("oldpasswd", $_POST["oldpasswd"],"noempty","".$this->nullmessage);
	// 	$this->Assign("passwd", $_POST["passwd"],"noempty","".$this->nullmessage);
	// 	$this->Assign("retype", $_POST["retype"],"noempty","".$this->nullmessage);

	// 	if($_POST["oldpasswd"] !='')
	// 	{
	// 		$query = new Bin_Query();
	// 		$sql_user = "SELECT * FROM user_login WHERE user_id = '".$user_id."'
	// 			AND user_password = '".trim(md5(base64_encode($_POST["oldpasswd"])))."'";
	// 		$query->executeQuery($sql_user);
	// 		$profile = $query->records;

	// 		if(count($profile) == 0)
	// 		{
	// 			$message="your Current doesn't match";
	// 			$this->Assign("oldpasswd",'',"noempty",$message);
	// 		}
	// 	}


	// 	if($_POST["passwd"] !='' && $_POST["retype"] !='')
	// 	{
	// 		if($_POST["passwd"] != $_POST["retype"])
	// 		{
	// 			$message="Retype Password Doesn't match";
	// 			$this->Assign("retype",'',"noempty",$message);
	// 			$_POST["retype"]='';
	// 		}
	// 	}

	// 	$this->PerformValidation('index.php?do=reteditdetails');

	// }

	function retailerCompose()
	{

		if(!$this->isValidEmail($_POST['to_email']))
		{
			$this->Assign("to_email","","noempty",$this->emailmessage);

		}
		else
		{

			$sql="SELECT address_email FROM address_details WHERE address_email='".$_POST["to_email"]."'";
			$query = new Bin_Query();
			$query->executeQuery($sql);
			$cnt=count($query->records);
			if($cnt=='0')
			$this->Assign("to_email","","noempty","MailId is not available");

		}

		$this->Assign("subject",trim($_POST["subject"]),"noempty",$this->nullmessage);
		$this->Assign("message",trim($_POST["message"]),"noempty",$this->nullmessage);
		$this->PerformValidation('index.php?do=retailercompose');

	}

	function valRetailProfile(){

		$this->Assign("email", $_POST["email"],"noempty",
						"".$this->nullmessage);

		$this->Assign("f_name", $_POST["f_name"],"noempty",$this->nullmessage);

		$this->Assign("l_name", $_POST["l_name"],"noempty",$this->nullmessage);

		$this->Assign("job", $_POST["job"],"noempty",$this->nullmessage);

		$this->Assign("org_name", $_POST["org_name"],"noempty",$this->nullmessage);

		$this->Assign("org_addr", $_POST["org_addr"],"noempty",$this->nullmessage);

// 		$this->Assign("org_addr1", $_POST["org_addr1"],"noempty/nostring/nospecial' '",
// 								"".$this->nullmessage.
// 								"/".$this->numbermessage.
// 								"/".$this->spcharmessage);

		$this->Assign("org_code", $_POST["org_code"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_state", $_POST["org_state"],"nospecial' '",
								"".$this->spcharmessage);
		$this->Assign("org_country", $_POST["org_country"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_country", $_POST["org_ph_country"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_area", $_POST["org_ph_area"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_phone", $_POST["org_ph_phone"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_m_country", $_POST["org_m_country"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_m_area", $_POST["org_m_area"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_m_phone", $_POST["org_m_phone"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);


		$this->PerformValidation('index.php?do=editretailprofile');
	}


	function valRetailInvestorReg(){


		if($_POST['username']==''){


				$this->Assign("username", $_POST['username'],"noempty",
									"".$this->nullmessage);
			}else{


				if(strlen($_POST['username'])<8){

						$mes = "Username must contain 8 or more characters";
						$this->Assign("username","","noempty",''.$mes);
				}else
					{
						$check_dupuser_query="select * from user_login where username='".$_POST['username']."'";

						$check_dupuser_result=mysql_query($check_dupuser_query);
						if(mysql_num_rows($check_dupuser_result)!=0)
						{
							 $usernamemsg='Username unavailable. Try inserting additional letters or numbers to this username';

							$this->Assign("username","","noempty",''.$usernamemsg);

						}
					}

			}



			if($_POST['password']==''){

				$this->Assign("password", $_POST['password'],"noempty",
									"".$this->nullmessage);
			}else{


				if(strlen($_POST['password'])<8){

						$mes = "Password must contain 8 or more characters";
						$this->Assign("password","","noempty",''.$mes);
				}
			}

				$this->Assign("cpassword", $_POST['cpassword'],"noempty",
									"".$this->nullmessage);

				if($_POST['password'] != $_POST['cpassword']){

						$mes = "The Password and the Confirm Password do not match";
						$this->Assign("cpassword","","noempty",''.$mes);
				}


				$this->Assign("secret", $_POST['secret'],"noempty",
									"".$this->nullmessage);

				$this->Assign("sanswer", $_POST['sanswer'],"noempty",
									"".$this->nullmessage);


		if($_POST['wemail']==''){
		$this->Assign("wemail", $_POST['wemail'],"noempty",
							"".$this->nullmessage);
		}else{
			if(!$this->isValidEmail($_POST['wemail'])){
				$this->Assign("wemail", "" ,"noempty",
							"Enter a valid email Address");
			}
		}



		$this->Assign("fname", $_POST['fname'],"noempty","".$this->nullmessage);
        $this->Assign("lname", $_POST['lname'],"noempty","".$this->nullmessage);
		$this->Assign("currency_id", $_POST['currency_id'],"noempty","".$this->nullmessage);

		$this->Assign("dob", $_POST['dob'],"noempty",
							"".$this->nullmessage);

		$dobdate=explode('-',$_POST['dob']);

		$_POST['year']=$dobdate[0];
		$_POST['month']=$dobdate[1];
		$_POST['date']=$dobdate[2];


		if($_POST['dob']==''){
				$this->Assign("dob", $_POST['dob'],"noempty",
							"".$this->nullmessage);
		}elseif($_POST['month']=="" || $_POST['date']==""){

			$message = "Enter a date in given format";
			$this->Assign("dob", '',"noempty",''.$message);
		}

		$this->Assign("dob", $_POST['date'],"nostring/nospecial' '",
						"".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("dob", $_POST['month'],"nostring/nospecial' '",
						"".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("dob", $_POST['year'],"nostring/nospecial' '",
						"".$this->numbermessage.
						"/".$this->spcharmessage);
		if($_POST['year']!=''){

			if(strlen($_POST['year'])<4){
				$message = "Enter a date in given format.";
				$this->Assign("dob", '',"noempty",''.$message);
			}
		}


		if(checkdate(intval($_POST['month']),intval($_POST['date']),intval($_POST['year'])))
		{
				$birth = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['date'];
				$age = $this->determine_age($birth);

				if($age < 18){
				$this->Assign("dob", "" ,"noempty","Age should be above 18");
				}
		}

		$this->Assign("addr1", $_POST['addr1'],"noempty",
							"".$this->nullmessage);
		$this->Assign("pcode", $_POST['pcode'],"noempty",
							"".$this->nullmessage);
		$this->Assign("country", $_POST['country'],"noempty",
							"".$this->nullmessage);

		$this->Assign("directdial", $_POST['dc_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);
		$this->Assign("directdial", $_POST['da_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);
		$this->Assign("directdial", $_POST['dph_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("mobile", $_POST['mc_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);
		$this->Assign("mobile", $_POST['ma_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);
		$this->Assign("mobile", $_POST['mph_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);


		if($_POST['dp_type']!='1'){

				$this->Assign("bank_name", $_POST['bank_name'],"noempty",
									"".$this->nullmessage);

				if($_POST['bank_name']=='0' && $_POST['bank_new'] =='')
				{
					$this->Assign("bank_new", $_POST['bank_new'],"noempty",
									"".$this->nullmessage);
				}


				$this->Assign("bank_orgcaddr1", $_POST['bank_orgcaddr1'],"noempty",
									"".$this->nullmessage);

				// $this->Assign("bank_orgcaddr2", $_POST['bank_orgcaddr2'],"noempty",
				// 					"".$this->nullmessage);

				$this->Assign("bank_orgc_pc", $_POST['bank_orgc_pc'],"noempty",
									"".$this->nullmessage);

				// $this->Assign("bank_orgc_city", $_POST['bank_orgc_city'],"noempty",
				// 					"".$this->nullmessage);

				// $this->Assign("bank_orgc_state", $_POST['bank_orgc_state'],"noempty",
				// 					"".$this->nullmessage);


				$this->Assign("bank_orgc_country", $_POST['bank_orgc_country'],"noempty",
									"".$this->nullmessage);

				$this->Assign("account_name", $_POST['account_name'],"noempty",
									"".$this->nullmessage);

				$this->Assign("account_no", $_POST['account_no'],"noempty",
									"".$this->nullmessage);

				$this->Assign("sort_code", $_POST['sort_code'],"noempty",
									"".$this->nullmessage);

				// $this->Assign("iban_code", $_POST['iban_code'],"noempty",
				// 					"".$this->nullmessage);

				// $this->Assign("swift_code", $_POST['swift_code'],"noempty",
				// 					"".$this->nullmessage);

				$this->Assign("bank_c_fname", $_POST['bank_c_fname'],"noempty",
									"".$this->nullmessage);

				$this->Assign("bank_c_lname", $_POST['bank_c_lname'],"noempty",
									"".$this->nullmessage);

				$this->Assign("bankdial", $_POST['bank_c_ph_country'],"noempty/nostring/nospecial' '",
									"".$this->nullmessage.
									"/".$this->numbermessage.
									"/".$this->spcharmessage);

				$this->Assign("bankdial", $_POST['bank_c_ph_area'],"noempty/nostring/nospecial' '",
									"".$this->nullmessage.
									"/".$this->numbermessage.
									"/".$this->spcharmessage);

				$this->Assign("bankdial", $_POST['bank_c_ph_pn'],"noempty/nostring/nospecial' '",
									"".$this->nullmessage.
									"/".$this->numbermessage.
									"/".$this->spcharmessage);
		}

		$this->PerformValidation("index.php?do=retailinvestorreg&id=".$_REQUEST['id']);

	}

	function valEditAuditProfit(){

		if(!checkdate(intval($_POST['fye_month']),intval($_POST['fye_date']),intval($_POST['fye_year'])))
		{
			$this->Assign("fye_year","","noempty","Enter a valid date");

		}
			$this->Assign("fye_year",$_POST['fye_month'],"noempty/nostring/nospecial' '"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("fye_year",$_POST['fye_date'],"noempty/nostring/nospecial' '"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("fye_year",$_POST['fye_year'],"noempty/nostring/nospecial' '"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);

		$this->Assign("turnover",$_POST['turnover'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("costofsale",$_POST['costofsale'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("sales_exp",$_POST['sales_exp'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("general_exp",$_POST['general_exp'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("hire",$_POST['hire'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("rent",$_POST['rent'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("admin_exp",$_POST['admin_exp'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("wages",$_POST['wages'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("social",$_POST['social'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("pension",$_POST['pension'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("depreciation",$_POST['depreciation'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("interest",$_POST['interest'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("ctax",$_POST['ctax'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);

		$this->PerformValidation("index.php?do=editauditprofit&id=".$_REQUEST['id']."&title=".$_REQUEST['title']);
	}


	function valEditAudit(){

		$this->Assign("fye_year1", $_POST["fye_year1"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		if(!checkdate(intval($_POST['fye_month']),intval($_POST['fye_date']),intval($_POST['fye_year'])))
		{
			$this->Assign("fye_year","","noempty","Enter a valid date");
		}

		$this->Assign("tang_assest",$_POST['tang_assest'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("tang_assest1",$_POST['tang_assest1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("debtors",$_POST['debtors'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("debtors1",$_POST['debtors1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("cashatbank",$_POST['cashatbank'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("cashatbank1",$_POST['cashatbank1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("stock",$_POST['stock'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("stock1",$_POST['stock1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("amount_oneyear",$_POST['amount_oneyear'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("amount_oneyear1",$_POST['amount_oneyear1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("amount_moreyear",$_POST['amount_moreyear'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("amount_moreyear1",$_POST['amount_moreyear1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("liabilities",$_POST['liabilities'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("liabilities1",$_POST['liabilities1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("called_up",$_POST['called_up'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("called_up1",$_POST['called_up1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("fixed_assest",$_POST['fixed_assest'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("fixed_assest1",$_POST['fixed_assest1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("turnover",$_POST['turnover'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("turnover1",$_POST['turnover1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("costofsale",$_POST['costofsale'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("costofsale1",$_POST['costofsale1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("sales_exp",$_POST['sales_exp'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("sales_exp1",$_POST['sales_exp1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("general_exp",$_POST['general_exp'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("general_exp1",$_POST['general_exp1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("hire",$_POST['hire'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("hire1",$_POST['hire1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("rent",$_POST['rent'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("rent1",$_POST['rent1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("admin_exp",$_POST['admin_exp'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("admin_exp1",$_POST['admin_exp1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("wages",$_POST['wages'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("wages1",$_POST['wages1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("social",$_POST['social'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("social1",$_POST['social1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("pension",$_POST['pension'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("pension1",$_POST['pension1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("depreciation",$_POST['depreciation'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("depreciation1",$_POST['depreciation1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("interest",$_POST['interest'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("interest1",$_POST['interest1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("ctax",$_POST['ctax'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("ctax1",$_POST['ctax1'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);

		/*$this->Assign("sign",$_FILES['sign']['name'],"noempty",
			$this->nullmessage);*/

		$this->PerformValidation("index.php?do=editaudit&id=".$_REQUEST['id']."&title=".$_REQUEST['title']);
	}

	function valEditTradeDoc(){

		/*if($_FILES['d_pdf']['tmp_name'] =='')
			$this->Assign("d_pdf",$_POST['d_pdf'],"noempty","Debtor Ledger Accounting PDF Document -".$this->nullmessage);

		if($_FILES['d_csv']['tmp_name'] =='')
			$this->Assign("d_csv",$_POST['d_csv'],"noempty","Debtor Ledger Accounting CSV Document -".$this->nullmessage);

		if($_FILES['b_pdf']['tmp_name'] =='')
			$this->Assign("b_pdf",$_POST['b_pdf'],"noempty","Bank Ledger Accounting PDF CSV Document -".$this->nullmessage);

		if($_FILES['b_csv']['tmp_name'] =='')
			$this->Assign("b_csv",$_POST['b_csv'],"noempty","Bank Ledger Accounting CSV Document -".$this->nullmessage);

		if($_FILES['c_pdf']['tmp_name'] =='')
			$this->Assign("c_pdf",$_POST['c_pdf'],"noempty","Creditor Ledger Accounting PDF Document -".$this->nullmessage);

		if($_FILES['c_csv']['tmp_name'] =='')
			$this->Assign("c_csv",$_POST['c_csv'],"noempty","Creditor Ledger Accounting CSV Document -".$this->nullmessage);*/



		//UPlaod File Check
		$dcnt =  count($_FILES);

		//$tmp = 'file_invoice';
		$tmp = array("c_csv","c_pdf","b_csv","b_pdf","d_csv","d_pdf","l_csv","l_pdf","s_csv","s_pdf","v_csv","v_pdf","p_csv","p_pdf");
		$i=0;
		for($d=1;$d<=$dcnt;$d++)
		{
			$mime = array('application/force-download','application/msexcel','application/x-ms-download','application/vnd.ms-excel','application/pdf','application/excel','application/x-excel','application/x-msexcel','application/excel','application/vnd.ms-excel','application/x-excel','application/excel','application/vnd.ms-excel','application/x-excel','application/excel','application/x-excel','application/excel','application/x-excel','application/excel','application/vnd.ms-excel','application/x-excel','application/excel','application/vnd.ms-excel','application/x-excel','application/excel','application/vnd.ms-excel','application/x-excel','application/x-msexcel','application/excel','application/x-excel','application/excel','application/x-excel','application/excel','application/vnd.ms-excel','application/x-excel','application/x-msexcel','application/vnd.ms-excel.sheet.macroEnabled.12','application/vnd.ms-excel.template.macroEnabled.12','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','text/csv','text/tsv');

			if($_FILES[$tmp[$i]]['tmp_name'] != "")
			{
				//$type = explode('/',$_FILES[$tmp[$i]]['type']);
				//$type = $type[1];
				$type = $_FILES[$tmp[$i]]['type'];
				if($_FILES[$tmp[$i]]['size'] <= 419430400)
				{
					//if($type!="csv"&& $type!="pdf")
					if(!in_array($type, $mime))
					{
						$message = "Upload Acount document only in the format PDF,CSV";
						$this->Assign($tmp[$i],'',"noempty",'Acount Document  - '.$message);
					}
				}
				else
				{
					$size_mes = "Acount Document size should be less than 4MB";
					$this->Assign($tmp[$i],"","noempty",'Acount Document  - '.$size_mes);
				}

			}
			$i++;
		}

		$this->PerformValidation("index.php?do=edittradedoc&id=".$_REQUEST['id']."&title=".$_REQUEST['title']);

	}


	function valEditTradeSub(){

		$this->Assign("fname", $_POST["fname"],"noempty",
						"".$this->nullmessage);

		$this->Assign("lname", $_POST["lname"],"noempty",
						"".$this->nullmessage);

		$this->Assign("date", $_POST["date"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("month", $_POST["month"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("year", $_POST["year"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("legal", $_POST["legal"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->PerformValidation("index.php?do=edittradesub&id=".$_REQUEST['id']."&title=".$_REQUEST['title']);

	}

	function valEditTradeAccount(){

		$this->Assign("f_date", $_POST['f_date'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("f_month", $_POST['f_month'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("f_year", $_POST['f_year'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("f_revenue", $_POST['f_revenue'],"noempty",
							"".$this->nullmessage);

		$this->Assign("f_balance", $_POST['f_balance'],"noempty",
							"".$this->nullmessage);

		$this->Assign("f_invoice", $_POST['f_invoice'],"noempty",
							"".$this->nullmessage);

		/*$this->Assign("f_bank", $_POST['f_bank'],"noempty/nospecial' '",
							"".$this->nullmessage.
							"/".$this->spcharmessage);*/

		$this->Assign("f_terms", $_POST['f_terms'],"noempty",
							"".$this->nullmessage);

		$this->Assign("relation", $_POST['relation'],"noempty/nospecial' '",
							"".$this->nullmessage.
							"/".$this->spcharmessage);

		if($_POST['relation'] == 1){
		$this->Assign("f_relation", $_POST['f_relation'],"noempty",
							"".$this->nullmessage);
		}

		$this->Assign("allowance", $_POST['allowance'],"noempty",
							"".$this->nullmessage);

		if($_POST['allowance'] == 1){
		$this->Assign("f_allowance", $_POST['f_allowance'],"noempty",
							"".$this->nullmessage);
		}

		$this->Assign("f_paywork", $_POST['f_paywork'],"noempty",
							"".$this->nullmessage);

		$this->Assign("system", $_POST['system'],"noempty",
							"".$this->nullmessage);

		if($_POST['system'] == 1){
			$this->Assign("f_system", $_POST['f_system'],"noempty",
							"".$this->nullmessage);
		}

		$this->Assign("f_sell", $_POST['f_sell'],"noempty",
							"".$this->nullmessage);

		$this->Assign("f_warranty", $_POST['f_warranty'],"noempty",
							"".$this->nullmessage);

		if($_POST['f_warranty'] ==1){
			$this->Assign("warranty", $_POST['warranty'],"noempty",
							"".$this->nullmessage);
		}

		$this->Assign("f_return", $_POST['f_return'],"noempty",
							"".$this->nullmessage);
		if($_POST['f_return'] == 1){
		$this->Assign("f_details", $_POST['f_details'],"noempty",
							"".$this->nullmessage);
		}



		$this->PerformValidation("index.php?do=edittradeaccount&id=".$_REQUEST['id']."&title=".$_REQUEST['title']);

	}


	function valEditOwnerDetails(){

		$this->Assign("fname", $_POST['fname'],"noempty",
						"".$this->nullmessage);

		$this->Assign("lname", $_POST['lname'],"noempty",
						"".$this->nullmessage);

		$this->Assign("jt", $_POST['jt'],"noempty",
						"".$this->nullmessage);

		$this->Assign("date", $_POST['date'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("month", $_POST['month'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("year", $_POST['year'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("passport", $_POST['passport'],"noempty",
						"".$this->nullmessage);

		/*$this->Assign("participate", $_POST["participate"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);*/

		/*$this->Assign("owner", $_POST["owner"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);*/


		if(in_array(2,$_POST["owner"])){

			$this->Assign("owned", $_POST['owned'],"noempty",
						"".$this->nullmessage);
		}

		$this->Assign("cntry", $_POST['cntry'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("area", $_POST['area'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("pn", $_POST['pn'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

	/*	if(!$this->isValidEmail($_POST['w_email']))
			$this->Assign("w_email", "","noempty",
								"".$this->emailmessage);


		if($_POST['email'] !='')	{
			if(!$this->isValidEmail($_POST['email']))
				$this->Assign("email", "","noempty",
								"".$this->emailmessage);
		}*/


		$this->PerformValidation("index.php?do=editownerdetails&id=".$_REQUEST['id']."&type=".$_REQUEST['type']."&title=".$_REQUEST['title']."");
	}

	function valEditContactDetails(){

		$this->Assign("fname", $_POST['fname'],"noempty",
						"".$this->nullmessage);

		$this->Assign("lname", $_POST['lname'],"noempty",
						"".$this->nullmessage);

		$this->Assign("jt", $_POST['jt'],"noempty",
						"".$this->nullmessage);

		$this->Assign("date", $_POST['date'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("month", $_POST['month'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("year", $_POST['year'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		/*$this->Assign("participate", $_POST["participate"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);*/

		/*$this->Assign("owner", $_POST["owner"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);*/


		if(in_array(2,$_POST["owner"])){

			$this->Assign("owned", $_POST['owned'],"noempty",
						"".$this->nullmessage);
		}

		/*$this->Assign("cntry", $_POST['cntry'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("area", $_POST['area'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("pn", $_POST['pn'],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);*/

		if(!$this->isValidEmail($_POST['w_email']))
			$this->Assign("w_email", "","noempty",
								"".$this->emailmessage);


		if($_POST['email'] !='')	{
			if(!$this->isValidEmail($_POST['email']))
				$this->Assign("email", "","noempty",
								"".$this->emailmessage);
		}


		$this->PerformValidation("index.php?do=editcontactdetails&id=".$_REQUEST['id']."&type=".$_REQUEST['type']."&title=".$_REQUEST['title']."");
	}


	function valEditBankAccount(){


		$this->Assign("account_name", $_POST['account_name'],"noempty",
							"".$this->nullmessage);

		$this->Assign("account_no", $_POST['account_no'],"noempty",
							"".$this->nullmessage);

		$this->Assign("sort_code", $_POST['sort_code'],"noempty",
							"".$this->nullmessage);

		$this->Assign("iban_code", $_POST['iban_code'],"noempty",
							"".$this->nullmessage);

		$this->Assign("swift_code", $_POST['swift_code'],"noempty",
							"".$this->nullmessage);

		$this->PerformValidation("index.php?do=editbankaccount&id=".$_REQUEST['id']."&title=".$_REQUEST['title']."");

	}

	function valEditBankContact(){

		// $this->Assign("bank_c_fname", $_POST['bank_c_fname'],"noempty",
		// 					"".$this->nullmessage);

		// $this->Assign("bank_c_lname", $_POST['bank_c_lname'],"noempty",
		// 					"".$this->nullmessage);

		// $this->Assign("bank_c_ph_country", $_POST['bank_c_ph_country'],"noempty/nostring/nospecial' '",
		// 					"".$this->nullmessage.
		// 					"/".$this->numbermessage.
		// 					"/".$this->spcharmessage);

		// $this->Assign("bank_c_ph_area", $_POST['bank_c_ph_area'],"noempty/nostring/nospecial' '",
		// 					"".$this->nullmessage.
		// 					"/".$this->numbermessage.
		// 					"/".$this->spcharmessage);

		// $this->Assign("bank_c_ph_pn", $_POST['bank_c_ph_pn'],"noempty/nostring/nospecial' '",
		// 					"".$this->nullmessage.
		// 					"/".$this->numbermessage.
		// 					"/".$this->spcharmessage);

		if($_POST['bank_c_email'] !='')	{

			if(!$this->isValidEmail($_POST['bank_c_email']))
			$this->Assign("bank_c_email", "","noempty",
								"".$this->emailmessage);
		}

		$this->PerformValidation("index.php?do=editbankcontact&id=".$_REQUEST['id']."&title=".$_REQUEST['title']."");

	}


	function valEditBankAddress(){

		$this->Assign("bank_name", $_POST['bank_name'],"noempty",
							"".$this->nullmessage);


		$this->Assign("bank_orgcaddr1", $_POST['bank_orgcaddr1'],"noempty",
							"".$this->nullmessage);

// 		$this->Assign("bank_orgc_addr2", $_POST['bank_orgc_addr2'],"nospecial' '",
// 							"".$this->spcharmessage);

		$this->Assign("bank_orgc_city", $_POST['bank_orgc_city'],"noempty",
							"".$this->nullmessage);

		/*$this->Assign("bank_orgc_state", $_POST['bank_orgc_state'],"nospecial' '",
							"".$this->spcharmessage);*/

		$this->Assign("bank_orgc_country", $_POST['bank_orgc_country'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_pc", $_POST['bank_orgc_pc'],"noempty",
							"".$this->nullmessage);


		$this->Assign("bank_orgc_ph_country", $_POST['bank_orgc_ph_country'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_ph_area", $_POST['bank_orgc_ph_area'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_ph_pn", $_POST['bank_orgc_ph_pn'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_fn_country", $_POST['bank_orgc_fn_country'],"nostring/nospecial' '",
							"".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_fn_area", $_POST['bank_orgc_fn_area'],"nostring/nospecial' '",
							"".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_fn_pn", $_POST['bank_orgc_fn_pn'],"nostring/nospecial' '",
							"".$this->numbermessage.
							"/".$this->spcharmessage);


		if($_POST['bank_orgc_email'] !='')	{
			if(!$this->isValidEmail($_POST['bank_orgc_email']))
			$this->Assign("bank_orgc_email", "","noempty",
								"".$this->emailmessage);
		}


		$this->PerformValidation("index.php?do=editbankaddress&id=".$_REQUEST['id']."&bank=".$_REQUEST['bank']."&address=".$_REQUEST['address']."&title=".$_REQUEST['title']."");
	}


	function valeditAddress(){

		$this->Assign("p_orgcaddr1", $_POST['p_orgcaddr1'],"noempty",
							"".$this->nullmessage);

	// 		$this->Assign("p_orgc_addr2", $_POST['p_orgc_addr2'],"nospecial' '",
	// 							"".$this->spcharmessage);

			$this->Assign("p_orgc_city", $_POST['p_orgc_city'],"noempty",
								"".$this->nullmessage);

			/*$this->Assign("p_orgc_state", $_POST['p_orgc_state'],"nospecial' '",
								"".$this->spcharmessage);*/

			$this->Assign("p_orgc_country", $_POST['p_orgc_country'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_pc", $_POST['p_orgc_pc'],"noempty",
								"".$this->nullmessage);

			$this->Assign("p_orgc_ph_country", $_POST['p_orgc_ph_country'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_ph_area", $_POST['p_orgc_ph_area'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_ph_pn", $_POST['p_orgc_ph_pn'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_ph_pn", $_POST['p_orgc_ph_pn'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_fn_area", $_POST['p_orgc_fn_area'],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_fn_pn", $_POST['p_orgc_fn_pn'],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);



			if($_POST['p_orgc_email'] !='')	{
				if(!$this->isValidEmail($_POST['p_orgc_email'])){
					$this->Assign("p_orgc_email", "","noempty",
									"".$this->emailmessage);
				}
			}


			$this->PerformValidation("index.php?do=editorgaddress&id=".$_REQUEST['id']."&address=".$_REQUEST['address']."&title=".$_REQUEST['title']);
	}


	function valeditOrganisation(){

		$this->Assign("org_organisationname",$_POST['org_organisationname'],"noempty",
					"".$this->nullmessage);

		$this->Assign("org_orgtype", $_POST['org_orgtype'],"noempty/nostring/nospecial' '",
					"".$this->nullmessage.
					"/".$this->numbermessage.
					"/".$this->spcharmessage);

		$this->Assign("org_orgoverview", $_POST['org_orgoverview'],"nospecial' '",
					"".$this->spcharmessage);

		$this->Assign("siccat", $_POST['siccat'],"noempty/nostring/nospecial' '",
					"".$this->nullmessage.
					"/".$this->numbermessage.
					"/".$this->spcharmessage);

		$this->Assign("sicgp", $_POST['sicgp'],"noempty/nostring/nospecial' '",
					"".$this->nullmessage.
					"/".$this->numbermessage.
					"/".$this->spcharmessage);

		$this->Assign("org_bentitytype", $_POST['org_bentitytype'],"noempty/nostring/nospecial' '",
					"".$this->nullmessage."/".$this->numbermessage.
					"/".$this->spcharmessage);

		$this->Assign("org_jurorg", $_POST['org_jurorg'],"noempty/nostring/nospecial' '",
					"".$this->nullmessage.
					"/".$this->numbermessage.
					"/".$this->spcharmessage);

		// 12 Wholly Owned,34 Majority Owned,35  Minority Owned,36 Branch Office,39 Authorised Agent

		$orgStatus = $_POST['org_bentitytype'];
		$org_bentitytype = array('12','34','35','36','37','38','39');
		// if(in_array($orgStatus, $org_bentitytype))

		if($orgStatus != 11 && $orgStatus != 47 && $orgStatus != 48){
		$this->Assign("org_pcdetail", $_POST['org_pcdetail'],"noempty",
					"".$this->nullmessage);
		}

		$this->Assign("org_form_year", $_POST['org_form_year'],"noempty/nostring/nospecial' '",
					"".$this->nullmessage.
					"/".$this->numbermessage.
					"/".$this->spcharmessage);

		$this->Assign("org_share_cap", $_POST['org_share_cap'],"noempty/nostring/nospecial' '",
					"".$this->nullmessage.
					"/".$this->numbermessage.
					"/".$this->spcharmessage);

		if($_POST['org_website'] !=''){

			if(!$this->isValidURL($_POST['org_website']))
				$this->Assign("org_website","","noempty",$this->urlmessage);
		}
		$this->Assign("org_ctn", $_POST['org_ctn'],"noempty/nospecial' '",
					"".$this->nullmessage."/".$this->spcharmessage);

		$this->Assign("org_vat", $_POST['org_vat'],"nospecial' '",
					"".$this->spcharmessage);

		$this->Assign("org_totemp", $_POST['org_totemp'],"noempty/nostring/nospecial' '",
					"".$this->nullmessage.
					"/".$this->numbermessage.
					"/".$this->spcharmessage);

		$this->Assign("prg_oth_cg", $_POST['org_oth_cg'],"nospecial' '",
					"".$this->spcharmessage);

		$this->Assign("org_detail", $_POST['org_odetail'],"nospecial' '",
					"".$this->spcharmessage);

		$this->PerformValidation('index.php?do=editorganisation&id='.$_REQUEST['id']);
	}


	function validateApplicationBegin()
	{
		$this->PerformValidation('index.php?do=application0');
	}


	function validateAddIntrmInvestorTwo()
	{

		for($i=0; $i<count($_POST['cp_fname']); $i++)
		{
			$this->Assign("cp_fname".$i,$_POST['cp_fname'][$i],"noempty",$this->nullmessage);
			$this->Assign("cp_lname".$i,$_POST['cp_lname'][$i],"noempty",$this->nullmessage);
			$this->Assign("cp_jtitle".$i,$_POST['cp_jtitle'][$i],"noempty/nonumber/nospecial' '",$this->nullmessage."/".
						$this->numbermessage."/".
						$this->spcharmessage);


			if(checkdate(intval($_POST['cp_dob_mon'][$i]),intval($_POST['cp_dob_date'][$i]),intval($_POST['cp_dob_year'][$i])))
			{
					$birth = $_POST['cp_dob_year'][$i].'-'.$_POST['cp_dob_mon'][$i].'-'.$_POST['cp_dob_date'][$i];
					$age = $this->determine_age($birth);
					if($age < 18)
						$this->Assign("cp_dob_year".$i,"","noempty","Age should be above 18");

			}
			else
			{
				$this->Assign("cp_dob_year".$i,"","noempty","Enter a valid date");
			}

			$this->Assign("cp_dob_year".$i,$_POST['cp_dob_mon'][$i],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("cp_dob_year".$i,$_POST['cp_dob_date'][$i],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("cp_dob_year".$i,$_POST['cp_dob_year'][$i],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);


			$this->Assign("cp_os_type".$i,$_POST['cp_os_type'][$i],"noempty",$this->nullmessage);

			if($_POST['cp_os_type'][$i] == '2')
			{
				$this->Assign("cp_per".$i,$_POST['cp_per'][$i],"noempty",$this->nullmessage);
				if($_POST['cp_per'][$i]>'100')
				{
					$this->Assign("cp_per".$i,"","noempty","Enter a valid percentage");
				}
			}

	// 		$this->Assign("cp_act_part".$i,$_POST['cp_act_part'][$i],"noempty",$this->nullmessage);


			$this->Assign("cp_ha_addr1".$i,$_POST['cp_ha_addr1'][$i],"noempty",
				$this->nullmessage);
			$this->Assign("cp_ha_city".$i,$_POST['cp_ha_city'][$i],"noempty",
				$this->nullmessage);
// 			$this->Assign("cp_ha_state".$i,$_POST['cp_ha_state'][$i],"nonumber/nospecial",
// 			"".$this->numbermessage."/".$this->spcharmessage);
//
// 			$this->Assign("cp_ha_pcode".$i,$_POST['cp_ha_pcode'][$i],"nospecial' '",$this->spcharmessage);
// 			if($_POST['cp_ha_country'][$i]=='0')
// 			{
// 			$this->Assign("cp_ha_country".$i,"","noempty",$this->nullmessage);
// 			}
			$this->Assign("cp_ha_ph_pn".$i,$_POST['cp_ha_ph_country'][$i],"noempty/nospecial''",
				" ".$this->nullmessage."/".
				"".$this->spcharmessage);
			$this->Assign("cp_ha_ph_pn".$i,$_POST['cp_ha_ph_area'][$i],"noempty/nospecial''/nostring",
				"".$this->nullmessage."/".
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_ha_ph_pn".$i,$_POST['cp_ha_ph_pn'][$i],"noempty/nospecial''/nostring",
				"".$this->nullmessage."/".
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_ha_fn_pn".$i,$_POST['cp_ha_fn_country'][$i],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_ha_fn_pn".$i,$_POST['cp_ha_fn_area'][$i],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_ha_fn_pn".$i,$_POST['cp_ha_fn_pn'][$i],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);

			if(!$this->isValidEmail($_POST['cp_ha_email'][$i]))
				$this->Assign("cp_ha_email".$i,"","noempty",
					"".$this->nullmessage);


			$this->Assign("address_select", $_POST['address_select'],"noempty",
							"".$this->nullmessage);

			if($_POST["address_select"] !=''){

			$this->Assign("cp_wa_addr1",$_POST['cp_wa_addr1'],"noempty",
				$this->nullmessage);
			$this->Assign("cp_wa_city",$_POST['cp_wa_city'],"noempty",
				$this->nullmessage);
/*			$this->Assign("cp_wa_state",$_POST['cp_wa_state'],"nonumber/nospecial' '",
			"".$this->numbermessage."/".$this->spcharmessage);

			$this->Assign("cp_wa_pcode",$_POST['cp_wa_pcode'],"nospecial' '",$this->spcharmessage);
			if($_POST['cp_wa_country']=='0')
			{
			$this->Assign("cp_wa_country","","noempty",$this->nullmessage);
			}*/
			$this->Assign("cp_wa_ph_pn",$_POST['cp_wa_ph_country'],"noempty/nospecial''",
				" ".$this->nullmessage."/".
				"".$this->spcharmessage);
			$this->Assign("cp_wa_ph_pn",$_POST['cp_wa_ph_area'],"noempty/nospecial''/nostring",
				"".$this->nullmessage."/".
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_ph_pn",$_POST['cp_wa_ph_pn'],"noempty/nospecial''/nostring",
				"".$this->nullmessage."/".
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_fn_pn",$_POST['cp_wa_fn_country'],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_fn_pn",$_POST['cp_wa_fn_area'],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_fn_pn",$_POST['cp_wa_fn_pn'],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);

			if(!$this->isValidEmail($_POST['cp_wa_email']))
				$this->Assign("cp_wa_email","","noempty/nospecial' '",
					"".$this->nullmessage."/".
					"".$this->emailmessage);
			}
		}


			$this->Assign("sub_fname",$_POST['sub_fname'],"noempty",
				"".$this->nullmessage);
			$this->Assign("sub_lname",$_POST['sub_lname'],"noempty",
				"".$this->nullmessage);
			if(!checkdate(intval($_POST['sub_month']),intval($_POST['sub_date']),intval($_POST['sub_year'])))
			{
				$this->Assign("sub_year","","noempty","Enter a valid date");

			}

			$this->Assign("sub_year",$_POST['sub_date'],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("sub_year",$_POST['sub_month'],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("sub_year",$_POST['sub_year'],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);


			$this->Assign("sub_approvel",$_POST['sub_approvel'],"noempty","".$this->nullmessage);
					$this->Assign("terms",$_POST['terms'],"noempty",
						$this->nullmessage);

			$this->PerformValidation('index.php?do=intrminvapplication2&id='.$_SESSION['organisation_id']);

	}







	function validateAddIntrmInvestor()
	{
		if(!$this->isValidURL($_POST['org_website']) && $_POST['org_website']!='')
			$this->Assign("org_website","","noempty",$this->urlmessage);

        $this->Assign("org_organisationname",$_POST['org_organisationname'],"noempty",$this->nullmessage);
		$this->Assign("currency_id",$_POST['currency_id'],"noempty",$this->nullmessage);

		if($_POST['org_orgtype']=='0')
		{
		$this->Assign("org_orgtype","","noempty","".$this->nullmessage);
		}
		if($_POST['org_jurorg']=='0')
		{
		$this->Assign("org_jurorg","","noempty","".$this->nullmessage);
		}
		$this->Assign("org_pn",$_POST['org_country'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_pn",$_POST['org_area'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_pn",$_POST['org_pn'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_fx_pn",$_POST['org_fx_country'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_fx_pn",$_POST['org_fx_area'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_fx_pn",$_POST['org_fx_pn'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		if($_POST['busi_entity']=='0')
		{
		$this->Assign("busi_entity","","noempty","".$this->nullmessage);
		}
		if($_POST['juris_org']=='0')
		{
		$this->Assign("juris_org","","noempty","".$this->nullmessage);
		}

		$orgStatus = $_POST['org_bentitytype'];

		if($orgStatus != 11 && $orgStatus != 47 && $orgStatus != 48){

		$this->Assign("org_pcdetail",$_POST['org_pcdetail'],"noempty","".$this->nullmessage);

		}

		$this->Assign("org_form_year",$_POST['org_form_year'],"noempty","".$this->nullmessage);
		/*$this->Assign("org_ctn",$_POST['org_ctn'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_vat",$_POST['org_vat'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);		*/
		$this->Assign("orgcaddr1",$_POST['orgcaddr1'],"noempty","".$this->nullmessage);
		$this->Assign("orgc_city",$_POST['orgc_city'],"noempty",
			$this->nullmessage);

// 		$this->Assign("orgc_state",$_POST['orgc_state'],"nonumber/nospecial",
// 			"".$this->numbermessage."/".$this->spcharmessage);

		if($_POST['orgc_country']=='0')
		{
			$this->Assign("orgc_country","","noempty","".$this->nullmessage);
		}

/*		$this->Assign("orgc_pc",$_POST['orgc_pc'],"nospecial' '",
			$this->spcharmessage);*/
		$this->Assign("orgc_ph_pn",$_POST['orgc_ph_country'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgc_ph_pn",$_POST['orgc_ph_area'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgc_ph_pn",$_POST['orgc_ph_pn'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgc_fn_country",$_POST['orgc_fn_country'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgc_fn_country",$_POST['orgc_fn_area'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgc_fn_country",$_POST['orgc_fn_pn'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);

		if(!$this->isValidEmail($_POST['orgc_email']))
					$this->Assign("orgc_email","","noempty"," ".$this->nullmessage);

		$this->Assign("address_select", $_POST['address_select'],"noempty",
							"".$this->nullmessage);

		if($_POST["address_select"] !=''){

		$this->Assign("orgp_add1",$_POST['orgp_add1'],"noempty",
			" ".$this->nullmessage);

		$this->Assign("orgp_city",$_POST['orgp_city'],"noempty",
			$this->nullmessage);
/*		$this->Assign("orgp_state",$_POST['orgp_state'],"nonumber/nospecial",
			"".$this->numbermessage."/".$this->spcharmessage);*/
		if($_POST['orgp_country']=='0')
		{
			$this->Assign("orgp_country","","noempty",
			$this->nullmessage);
		}

// 		$this->Assign("orgp_pc",$_POST['orgp_pc'],"nospecial' '",
// 			$this->spcharmessage);

		$this->Assign("orgp_pn_country",$_POST['orgp_pn_country'],"noempty/nospecial''",
			" ".$this->nullmessage."/".
			"".$this->spcharmessage);

		$this->Assign("orgp_pn_country",$_POST['orgp_pn_country'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgp_pn_area",$_POST['orgp_pn_area'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgp_pn_pn",$_POST['orgp_pn_pn'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgp_fx_pn",$_POST['orgp_fx_country'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgp_fx_pn",$_POST['orgp_fx_area'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgp_fx_pn",$_POST['orgp_fx_pn'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);


		if(!$this->isValidEmail($_POST['orgp_email']))
			$this->Assign("orgp_email","","noempty",
				"".$this->nullmessage);
		}

			for($i=0; $i<count($_POST['orgb_addr1']); $i++)
			{


				$this->Assign("orgb_addr1".$i,$_POST['orgb_addr1'][$i],"noempty",
					$this->nullmessage);
				$this->Assign("orgb_city".$i,$_POST['orgb_city'][$i],"noempty",
					$this->nullmessage);
				$this->Assign("orgb_state".$i,$_POST['orgb_state'][$i],"nonumber",
				"".$this->numbermessage);

				/*$this->Assign("orgb_pc".$i,$_POST['orgb_pc'][$i],"nospecial' '",$this->spcharmessage);*/
				if($_POST['orgb_country'][$i]=='0')
				{
					$this->Assign("orgb_country".$i,"","noempty",$this->nullmessage);
				}
				$this->Assign("orgb_pn_pn".$i,$_POST['orgb_pn_country'][$i],"noempty/nospecial''",
					" ".$this->nullmessage."/".
					"".$this->spcharmessage);
				$this->Assign("orgb_pn_pn".$i,$_POST['orgb_pn_area'][$i],"noempty/nospecial''/nostring",
					"".$this->nullmessage."/".
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_pn_pn".$i,$_POST['orgb_pn_pn'][$i],"noempty/nospecial''/nostring",
					"".$this->nullmessage."/".
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_fn_pn".$i,$_POST['orgb_fn_country'][$i],"nospecial''/nostring",
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_fn_pn".$i,$_POST['orgb_fn_area'][$i],"nospecial''/nostring",
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_fn_pn".$i,$_POST['orgb_fn_pn'][$i],"nospecial''/nostring",
					"".$this->spcharmessage."/".$this->stringmessage);


				if(!$this->isValidEmail($_POST['orgb_email'][$i]))
					$this->Assign("orgb_email".$i,"","noempty",
						"".$this->nullmessage);
			}


		// $this->Assign("bank_c_fname", $_POST['bank_c_fname'],"noempty",
		// 					"".$this->nullmessage);

		// $this->Assign("bank_c_lname", $_POST['bank_c_lname'],"noempty",
		// 					"".$this->nullmessage);

		// $this->Assign("bank_c_ph_country", $_POST['bank_c_ph_country'],"noempty/nostring/nospecial' '",
		// 					"".$this->nullmessage.
		// 					"/".$this->numbermessage.
		// 					"/".$this->spcharmessage);

		// $this->Assign("bank_c_ph_area", $_POST['bank_c_ph_area'],"noempty/nostring/nospecial' '",
		// 					"".$this->nullmessage.
		// 					"/".$this->numbermessage.
		// 					"/".$this->spcharmessage);

		// $this->Assign("bank_c_ph_pn", $_POST['bank_c_ph_pn'],"noempty/nostring/nospecial' '",
		// 					"".$this->nullmessage.
		// 					"/".$this->numbermessage.
		// 					"/".$this->spcharmessage);

		if($_POST['bank_c_email'] !='')	{

			if(!$this->isValidEmail($_POST['bank_c_email']))
			$this->Assign("bank_c_email", "","noempty",
								"".$this->emailmessage);
		}


		$this->Assign("account_name", $_POST['account_name'],"noempty",
							"".$this->nullmessage);

		$this->Assign("account_no", $_POST['account_no'],"noempty",
							"".$this->nullmessage);

		$this->Assign("sort_code", $_POST['sort_code'],"noempty",
							"".$this->nullmessage);

		/*$this->Assign("iban_code", $_POST['iban_code'],"noempty",
							"".$this->nullmessage);

		$this->Assign("swift_code", $_POST['swift_code'],"noempty",
							"".$this->nullmessage);*/


		$this->PerformValidation('index.php?do=intrminvapplication1');
	}


function validateIntermediaryTwo()
	{

		for($i=0; $i<count($_POST['cp_fname']); $i++)
		{
			$this->Assign("cp_fname".$i,$_POST['cp_fname'][$i],"noempty",$this->nullmessage);
			$this->Assign("cp_lname".$i,$_POST['cp_lname'][$i],"noempty",$this->nullmessage);
			$this->Assign("cp_jtitle".$i,$_POST['cp_jtitle'][$i],"noempty/nonumber/nospecial' '",$this->nullmessage."/".
						$this->numbermessage."/".
						$this->spcharmessage);


			if(checkdate(intval($_POST['cp_dob_mon'][$i]),intval($_POST['cp_dob_date'][$i]),intval($_POST['cp_dob_year'][$i])))
			{
					$birth = $_POST['cp_dob_year'][$i].'-'.$_POST['cp_dob_mon'][$i].'-'.$_POST['cp_dob_date'][$i];
					$age = $this->determine_age($birth);
					if($age < 18)
						$this->Assign("cp_dob_year".$i,"","noempty","Age should be above 18");

			}
			elseif($_POST['cp_dob_mon'][$i]!='' && $_POST['cp_dob_date'][$i]!='' && $_POST['cp_dob_year'][$i]!='')
			{
				$this->Assign("cp_dob_year".$i,"","noempty","Enter a valid date");
			}

			$this->Assign("cp_dob_year".$i,$_POST['cp_dob_mon'][$i],"nostring/nospecial"," ".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("cp_dob_year".$i,$_POST['cp_dob_date'][$i],"nostring/nospecial"," ".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("cp_dob_year".$i,$_POST['cp_dob_year'][$i],"nostring/nospecial"," ".$this->stringmessage."/".$this->spcharmessage);


			// $this->Assign("cp_os_type".$i,$_POST['cp_os_type'][$i],"noempty",$this->nullmessage);

			// if($_POST['cp_os_type'][$i] == '2')
			// {
			// 	$this->Assign("cp_per".$i,$_POST['cp_per'][$i],"noempty",$this->nullmessage);
			// 	if($_POST['cp_per'][$i]>'100')
			// 	{
			// 		$this->Assign("cp_per".$i,"","noempty","Enter a valid percentage");
			// 	}
			// }

	// 		$this->Assign("cp_act_part".$i,$_POST['cp_act_part'][$i],"noempty",$this->nullmessage);


// 			$this->Assign("cp_ha_addr1".$i,$_POST['cp_ha_addr1'][$i],"noempty",
// 				$this->nullmessage);
// 			$this->Assign("cp_ha_city".$i,$_POST['cp_ha_city'][$i],"noempty",
// 				$this->nullmessage);
// // 			$this->Assign("cp_ha_state".$i,$_POST['cp_ha_state'][$i],"nonumber/nospecial",
// // 			"".$this->numbermessage."/".$this->spcharmessage);
// //
// // 			$this->Assign("cp_ha_pcode".$i,$_POST['cp_ha_pcode'][$i],"nospecial' '",$this->spcharmessage);
// // 			if($_POST['cp_ha_country'][$i]=='0')
// // 			{
// // 			$this->Assign("cp_ha_country".$i,"","noempty",$this->nullmessage);
// // 			}
// 			$this->Assign("cp_ha_ph_pn".$i,$_POST['cp_ha_ph_country'][$i],"noempty/nospecial''",
// 				" ".$this->nullmessage."/".
// 				"".$this->spcharmessage);
// 			$this->Assign("cp_ha_ph_pn".$i,$_POST['cp_ha_ph_area'][$i],"noempty/nospecial''/nostring",
// 				"".$this->nullmessage."/".
// 				"".$this->spcharmessage."/".$this->stringmessage);
// 			$this->Assign("cp_ha_ph_pn".$i,$_POST['cp_ha_ph_pn'][$i],"noempty/nospecial''/nostring",
// 				"".$this->nullmessage."/".
// 				"".$this->spcharmessage."/".$this->stringmessage);
// 			$this->Assign("cp_ha_fn_pn".$i,$_POST['cp_ha_fn_country'][$i],"nospecial''/nostring",
// 				"".$this->spcharmessage."/".$this->stringmessage);
// 			$this->Assign("cp_ha_fn_pn".$i,$_POST['cp_ha_fn_area'][$i],"nospecial''/nostring",
// 				"".$this->spcharmessage."/".$this->stringmessage);
// 			$this->Assign("cp_ha_fn_pn".$i,$_POST['cp_ha_fn_pn'][$i],"nospecial''/nostring",
// 				"".$this->spcharmessage."/".$this->stringmessage);

// 			if(!$this->isValidEmail($_POST['cp_ha_email'][$i]))
// 				$this->Assign("cp_ha_email".$i,"","noempty",
// 					"".$this->nullmessage);


			$this->Assign("address_select", $_POST['address_select'],"noempty",
							"".$this->nullmessage);

			if($_POST["address_select"] !=''){

			$this->Assign("cp_wa_addr1",$_POST['cp_wa_addr1'],"noempty",
				$this->nullmessage);
			$this->Assign("cp_wa_city",$_POST['cp_wa_city'],"noempty",
				$this->nullmessage);
/*			$this->Assign("cp_wa_state",$_POST['cp_wa_state'],"nonumber/nospecial' '",
			"".$this->numbermessage."/".$this->spcharmessage);

			$this->Assign("cp_wa_pcode",$_POST['cp_wa_pcode'],"nospecial' '",$this->spcharmessage);
			if($_POST['cp_wa_country']=='0')
			{
			$this->Assign("cp_wa_country","","noempty",$this->nullmessage);
			}*/
			$this->Assign("cp_wa_ph_pn",$_POST['cp_wa_ph_country'],"noempty/nospecial''",
				" ".$this->nullmessage."/".
				"".$this->spcharmessage);
			$this->Assign("cp_wa_ph_pn",$_POST['cp_wa_ph_area'],"noempty/nospecial''/nostring",
				"".$this->nullmessage."/".
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_ph_pn",$_POST['cp_wa_ph_pn'],"noempty/nospecial''/nostring",
				"".$this->nullmessage."/".
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_fn_pn",$_POST['cp_wa_fn_country'],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_fn_pn",$_POST['cp_wa_fn_area'],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_fn_pn",$_POST['cp_wa_fn_pn'],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);

			if(!$this->isValidEmail($_POST['cp_wa_email']))
				$this->Assign("cp_wa_email","","noempty/nospecial' '",
					"".$this->nullmessage."/".
					"".$this->emailmessage);
			}
		}


			$this->Assign("sub_fname",$_POST['sub_fname'],"noempty",
				"".$this->nullmessage);
			$this->Assign("sub_lname",$_POST['sub_lname'],"noempty",
				"".$this->nullmessage);
			if(!checkdate(intval($_POST['sub_month']),intval($_POST['sub_date']),intval($_POST['sub_year'])))
			{
				$this->Assign("sub_year","","noempty","Enter a valid date");

			}

			$this->Assign("sub_year",$_POST['sub_date'],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("sub_year",$_POST['sub_month'],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("sub_year",$_POST['sub_year'],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);


			$this->Assign("sub_approvel",$_POST['sub_approvel'],"noempty","".$this->nullmessage);
					$this->Assign("terms",$_POST['terms'],"noempty",
						$this->nullmessage);

			$this->PerformValidation('index.php?do=intermedapplication2&id='.$_SESSION['organisation_id']);

	}


	function validateIntermediaryOne()
	{
		if(!$this->isValidURL($_POST['org_website']) && $_POST['org_website']!='')
			$this->Assign("org_website","","noempty",$this->urlmessage);

        $this->Assign("org_organisationname",$_POST['org_organisationname'],"noempty",$this->nullmessage);
		$this->Assign("currency_id",$_POST['currency_id'],"noempty",$this->nullmessage);

		if($_POST['org_orgtype']=='0')
		{
		$this->Assign("org_orgtype","","noempty","".$this->nullmessage);
		}
		if($_POST['org_jurorg']=='0')
		{
		$this->Assign("org_jurorg","","noempty","".$this->nullmessage);
		}
		$this->Assign("org_pn",$_POST['org_country'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_pn",$_POST['org_area'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_pn",$_POST['org_pn'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_fx_pn",$_POST['org_fx_country'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_fx_pn",$_POST['org_fx_area'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_fx_pn",$_POST['org_fx_pn'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		if($_POST['busi_entity']=='0')
		{
		$this->Assign("busi_entity","","noempty","".$this->nullmessage);
		}
		if($_POST['juris_org']=='0')
		{
		$this->Assign("juris_org","","noempty","".$this->nullmessage);
		}


		$orgStatus = $_POST['org_bentitytype'];

 		if($orgStatus != 11 && $orgStatus != 47 && $orgStatus != 48){

		$this->Assign("org_pcdetail", $_POST['org_pcdetail'],"noempty",
					"".$this->nullmessage);
		}

		// $this->Assign("org_pcdetail",$_POST['org_pcdetail'],"noempty","".$this->nullmessage);
		$this->Assign("org_form_year",$_POST['org_form_year'],"noempty","".$this->nullmessage);
		/*$this->Assign("org_ctn",$_POST['org_ctn'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_vat",$_POST['org_vat'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);		*/
		$this->Assign("orgcaddr1",$_POST['orgcaddr1'],"noempty","".$this->nullmessage);
		// $this->Assign("orgc_city",$_POST['orgc_city'],"noempty",
		// 	$this->nullmessage);

// 		$this->Assign("orgc_state",$_POST['orgc_state'],"nonumber/nospecial",
// 			"".$this->numbermessage."/".$this->spcharmessage);

		if($_POST['orgc_country']=='0')
		{
			$this->Assign("orgc_country","","noempty","".$this->nullmessage);
		}

		$this->Assign("orgc_pc",$_POST['orgc_pc'],"noempty/nospecial' '",
			"".$this->nullmessage."/".
			$this->spcharmessage);
		// $this->Assign("orgc_ph_pn",$_POST['orgc_ph_country'],"noempty/nospecial' '/nostring",
		// 	"".$this->nullmessage."/".
		// 	"".$this->spcharmessage."/".$this->stringmessage);
		// $this->Assign("orgc_ph_pn",$_POST['orgc_ph_area'],"noempty/nospecial' '/nostring",
		// 	"".$this->nullmessage."/".
		// 	"".$this->spcharmessage."/".$this->stringmessage);
		// $this->Assign("orgc_ph_pn",$_POST['orgc_ph_pn'],"noempty/nospecial' '/nostring",
		// 	"".$this->nullmessage."/".
		// 	"".$this->spcharmessage."/".$this->stringmessage);
		// $this->Assign("orgc_fn_country",$_POST['orgc_fn_country'],"nospecial' '/nostring",
		// 	"".$this->spcharmessage."/".$this->stringmessage);
		// $this->Assign("orgc_fn_country",$_POST['orgc_fn_area'],"nospecial' '/nostring",
		// 	"".$this->spcharmessage."/".$this->stringmessage);
		// $this->Assign("orgc_fn_country",$_POST['orgc_fn_pn'],"nospecial' '/nostring",
		// 	"".$this->spcharmessage."/".$this->stringmessage);

		// if(!$this->isValidEmail($_POST['orgc_email']))
		// 			$this->Assign("orgc_email","","noempty"," ".$this->nullmessage);

		$this->Assign("address_select", $_POST['address_select'],"noempty",
							"".$this->nullmessage);

		if($_POST["address_select"] !=''){

		$this->Assign("orgp_add1",$_POST['orgp_add1'],"noempty",
			" ".$this->nullmessage);

		// $this->Assign("orgp_city",$_POST['orgp_city'],"noempty",
		// 	$this->nullmessage);
/*		$this->Assign("orgp_state",$_POST['orgp_state'],"nonumber/nospecial",
			"".$this->numbermessage."/".$this->spcharmessage);*/
		if($_POST['orgp_country']=='0')
		{
			$this->Assign("orgp_country","","noempty",
			$this->nullmessage);
		}

// 		$this->Assign("orgp_pc",$_POST['orgp_pc'],"nospecial' '",
// 			$this->spcharmessage);
		$this->Assign("orgp_pc",$_POST['orgp_pc'],"noempty/nospecial' '",
			"".$this->nullmessage."/".
			$this->spcharmessage);

		// $this->Assign("orgp_pn_country",$_POST['orgp_pn_country'],"noempty/nospecial''",
		// 	" ".$this->nullmessage."/".
		// 	"".$this->spcharmessage);

		// $this->Assign("orgp_pn_country",$_POST['orgp_pn_country'],"noempty/nospecial' '/nostring",
		// 	"".$this->nullmessage."/".
		// 	"".$this->spcharmessage."/".$this->stringmessage);
		// $this->Assign("orgp_pn_area",$_POST['orgp_pn_area'],"noempty/nospecial' '/nostring",
		// 	"".$this->nullmessage."/".
		// 	"".$this->spcharmessage."/".$this->stringmessage);
		// $this->Assign("orgp_pn_pn",$_POST['orgp_pn_pn'],"noempty/nospecial' '/nostring",
		// 	"".$this->nullmessage."/".
		// 	"".$this->spcharmessage."/".$this->stringmessage);
		// $this->Assign("orgp_fx_pn",$_POST['orgp_fx_country'],"nospecial' '/nostring",
		// 	"".$this->spcharmessage."/".$this->stringmessage);
		// $this->Assign("orgp_fx_pn",$_POST['orgp_fx_area'],"nospecial' '/nostring",
		// 	"".$this->spcharmessage."/".$this->stringmessage);
		// $this->Assign("orgp_fx_pn",$_POST['orgp_fx_pn'],"nospecial' '/nostring",
		// 	"".$this->spcharmessage."/".$this->stringmessage);


		// if(!$this->isValidEmail($_POST['orgp_email']))
		// 	$this->Assign("orgp_email","","noempty",
		// 		"".$this->nullmessage);
		}

			for($i=0; $i<count($_POST['orgb_addr1']); $i++)
			{


				$this->Assign("orgb_addr1".$i,$_POST['orgb_addr1'][$i],"noempty",
					$this->nullmessage);
				$this->Assign("orgb_city".$i,$_POST['orgb_city'][$i],"noempty",
					$this->nullmessage);
				$this->Assign("orgb_state".$i,$_POST['orgb_state'][$i],"nonumber",
				"".$this->numbermessage);

				/*$this->Assign("orgb_pc".$i,$_POST['orgb_pc'][$i],"nospecial' '",$this->spcharmessage);*/
				if($_POST['orgb_country'][$i]=='0')
				{
					$this->Assign("orgb_country".$i,"","noempty",$this->nullmessage);
				}
				$this->Assign("orgb_pn_pn".$i,$_POST['orgb_pn_country'][$i],"noempty/nospecial''",
					" ".$this->nullmessage."/".
					"".$this->spcharmessage);
				$this->Assign("orgb_pn_pn".$i,$_POST['orgb_pn_area'][$i],"noempty/nospecial''/nostring",
					"".$this->nullmessage."/".
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_pn_pn".$i,$_POST['orgb_pn_pn'][$i],"noempty/nospecial''/nostring",
					"".$this->nullmessage."/".
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_fn_pn".$i,$_POST['orgb_fn_country'][$i],"nospecial''/nostring",
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_fn_pn".$i,$_POST['orgb_fn_area'][$i],"nospecial''/nostring",
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_fn_pn".$i,$_POST['orgb_fn_pn'][$i],"nospecial''/nostring",
					"".$this->spcharmessage."/".$this->stringmessage);


				if(!$this->isValidEmail($_POST['orgb_email'][$i]))
					$this->Assign("orgb_email".$i,"","noempty",
						"".$this->nullmessage);
			}


		// $this->Assign("bank_c_fname", $_POST['bank_c_fname'],"noempty",
		// 					"".$this->nullmessage);

		// $this->Assign("bank_c_lname", $_POST['bank_c_lname'],"noempty",
		// 					"".$this->nullmessage);

		// $this->Assign("bank_c_ph_country", $_POST['bank_c_ph_country'],"noempty/nostring/nospecial' '",
		// 					"".$this->nullmessage.
		// 					"/".$this->numbermessage.
		// 					"/".$this->spcharmessage);

		// $this->Assign("bank_c_ph_area", $_POST['bank_c_ph_area'],"noempty/nostring/nospecial' '",
		// 					"".$this->nullmessage.
		// 					"/".$this->numbermessage.
		// 					"/".$this->spcharmessage);

		// $this->Assign("bank_c_ph_pn", $_POST['bank_c_ph_pn'],"noempty/nostring/nospecial' '",
		// 					"".$this->nullmessage.
		// 					"/".$this->numbermessage.
		// 					"/".$this->spcharmessage);

		if($_POST['bank_c_email'] !='')	{

			if(!$this->isValidEmail($_POST['bank_c_email']))
			$this->Assign("bank_c_email", "","noempty",
								"".$this->emailmessage);
		}


		$this->Assign("account_name", $_POST['account_name'],"noempty",
							"".$this->nullmessage);

		$this->Assign("account_no", $_POST['account_no'],"noempty",
							"".$this->nullmessage);

		$this->Assign("sort_code", $_POST['sort_code'],"noempty",
							"".$this->nullmessage);

		/*$this->Assign("iban_code", $_POST['iban_code'],"noempty",
							"".$this->nullmessage);

		$this->Assign("swift_code", $_POST['swift_code'],"noempty",
							"".$this->nullmessage);*/


		$this->PerformValidation('index.php?do=intermedapplication1');
	}





	function valIntermedQuestion(){

		$this->Assign("secret_quest", $_POST["secret_quest"],"noempty","".$this->nullmessage);
		$this->Assign("secret_answer", $_POST["secret_answer"],"noempty","".$this->nullmessage);

		$this->PerformValidation('index.php?do=editaccountinfo');
	}

	function valIntermedPassword(){
		$user_id = $_SESSION['user']['userid'];

		$this->Assign("oldpasswd", $_POST["oldpasswd"],"noempty","".$this->nullmessage);
		$this->Assign("passwd", $_POST["passwd"],"noempty","".$this->nullmessage);
		$this->Assign("retype", $_POST["retype"],"noempty","".$this->nullmessage);

		if($_POST["oldpasswd"] !='')
		{
			$query = new Bin_Query();
			$sql_user = "SELECT * FROM temp_registration WHERE user_id = '".$user_id."'
				AND password = '".$_POST["oldpasswd"]."'";
			$query->executeQuery($sql_user);
			$profile = $query->records;

			if(count($profile) == 0)
			{
				$message="Incorrect current password";
				$this->Assign("oldpasswd",'',"noempty",$message);
			}
		}


		if($_POST["passwd"] !='' && $_POST["retype"] !='')
		{
			if($_POST["passwd"] != $_POST["retype"])
			{
				$message="Incorrect password confirmation";
				$this->Assign("retype",'',"noempty",$message);
				$_POST["retype"]='';
			}
		}

		$this->PerformValidation('index.php?do=editaccountinfo');

	}

	function valIntermedProfile(){

		$this->Assign("email", $_POST["email"],"noempty",
						"".$this->nullmessage);

		$this->Assign("f_name", $_POST["f_name"],"noempty",$this->nullmessage);

		$this->Assign("l_name", $_POST["l_name"],"noempty",$this->nullmessage);

		$this->Assign("job", $_POST["job"],"noempty",$this->nullmessage);

		$this->Assign("org_name", $_POST["org_name"],"noempty",$this->nullmessage);

		$this->Assign("org_addr", $_POST["org_addr"],"noempty",$this->nullmessage);

// 		$this->Assign("org_addr1", $_POST["org_addr1"],"noempty/nostring/nospecial' '",
// 								"".$this->nullmessage.
// 								"/".$this->numbermessage.
// 								"/".$this->spcharmessage);

		$this->Assign("org_code", $_POST["org_code"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_state", $_POST["org_state"],"nospecial' '",
								"".$this->spcharmessage);
		$this->Assign("org_country", $_POST["org_country"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_country", $_POST["org_ph_country"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_area", $_POST["org_ph_area"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_phone", $_POST["org_ph_phone"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_m_country", $_POST["org_m_country"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_m_area", $_POST["org_m_area"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_m_phone", $_POST["org_m_phone"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);


		$this->PerformValidation('index.php?do=editintermedprofile');
	}


	function valAddInvestor()
	{

		if($_POST['confirm_type']!='1'){

			if($_POST['email']==''){
			$this->Assign("email", $_POST['email'],"noempty",
								"".$this->nullmessage);
			}else{
				if(!$this->isValidEmail($_POST['email'])){
					$this->Assign("email", "" ,"noempty",
								"Enter a valid email Address");
				}
			}
		}else{

			if($_POST['email']!=''){
				if(!$this->isValidEmail($_POST['email'])){
					$this->Assign("email", "" ,"noempty",
								"Enter a valid email Address");
				}
			}
		}

		$this->Assign("first_name", $_POST['first_name'],"noempty","".$this->nullmessage);
        $this->Assign("last_name", $_POST['last_name'],"noempty","".$this->nullmessage);
		$this->Assign("currency_id", $_POST['currency_id'],"noempty","".$this->nullmessage);

		$this->Assign("dob", $_POST['dob'],"noempty",
							"".$this->nullmessage);

		$dobdate=explode('-',$_POST['dob']);

		$_POST['year']=$dobdate[0];
		$_POST['month']=$dobdate[1];
		$_POST['date']=$dobdate[2];


		if($_POST['dob']==''){
				$this->Assign("dob", $_POST['dob'],"noempty",
							"".$this->nullmessage);
		}elseif($_POST['month']=="" || $_POST['date']==""){

			$message = "Enter a date in given format";
			$this->Assign("dob", '',"noempty",''.$message);
		}

		$this->Assign("dob", $_POST['date'],"nostring/nospecial' '",
						"".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("dob", $_POST['month'],"nostring/nospecial' '",
						"".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("dob", $_POST['year'],"nostring/nospecial' '",
						"".$this->numbermessage.
						"/".$this->spcharmessage);
		if($_POST['year']!=''){

			if(strlen($_POST['year'])<4){
				$message = "Enter a date in given format.";
				$this->Assign("dob", '',"noempty",''.$message);
			}
		}


		if(checkdate(intval($_POST['month']),intval($_POST['date']),intval($_POST['year'])))
		{
				$birth = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['date'];
				$age = $this->determine_age($birth);

				if($age < 18){
				$this->Assign("dob", "" ,"noempty","Age should be above 18");
				}
		}

		$this->Assign("address_one", $_POST['address_one'],"noempty",
							"".$this->nullmessage);
		$this->Assign("postal_code", $_POST['postal_code'],"noempty",
							"".$this->nullmessage);
		$this->Assign("country", $_POST['country'],"noempty",
							"".$this->nullmessage);

		$this->Assign("directdial", $_POST['hc_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);
		$this->Assign("directdial", $_POST['ha_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);
		$this->Assign("directdial", $_POST['hph_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("mobile", $_POST['mc_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);
		$this->Assign("mobile", $_POST['ma_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);
		$this->Assign("mobile", $_POST['mph_code'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("quote_rate", $_POST['quote_rate'],"nostring",
							"".$this->numbermessage);


		// if(strlen($_POST['quote_rate'])>2){
		// 		$message = "Exceeds the 2 digits limit.";
		// 		$this->Assign("quote_rate", '',"noempty",''.$message);
		// }

		$quote=explode('.',$_POST['quote_rate']);


		$round=$quote[0];
		$decimal=$quote[1];

		if(strlen($round)>2){
				$message = "Exceeds the 2 digits limit.";
				$this->Assign("quote_rate", '',"noempty",''.$message);
		}

		if(strlen($decimal)>3){
				$message = "Exceeds the 3 digits decimal limit.";
				$this->Assign("quote_rate", '',"noempty",''.$message);
		}


		if($_POST['dp_type']=='1'){

			$message = "Pension Trustee, cannnot be Blank!";
			$this->Assign("dp_organisation", $_POST['dp_organisation'],"noempty",
							"".$message);
		}


		//UPlaod File Check
		$dcnt =  count($_FILES);
		//$tmp = 'file_invoice';
		if($_POST['confirm_type']=='1'){
			$tmp = array("p_passport","b_bill","signed_rpa");

		}else{
			$tmp = array("p_passport","b_bill");

		}
		$i=0;
		for($d=1;$d<=$dcnt;$d++)
		{
			$mime = array('application/download','application/pdf', 'application/x-download');

				// if($tmp[$i]=='signed_rpa'){

				// 	if($_FILES[$tmp[$i]]['name']=='')

				// 			$this->Assign($tmp[$i],'',"noempty",''.$this->nullmessage);
				// }



			if($_FILES[$tmp[$i]]['tmp_name'] != "")
			{
				//$type = explode('/',$_FILES[$tmp[$i]]['type']);
				//$type = $type[1];
				$type = $_FILES[$tmp[$i]]['type'];



				if($_FILES[$tmp[$i]]['size'] <= 419430400)
				{
					//if($type!="csv"&& $type!="pdf")
					if(!in_array($type, $mime))
					{
						$message = "Upload Document only in the format PDF";
						$this->Assign($tmp[$i],'',"noempty",''.$message);
					}
				}
				else
				{
					$size_mes = "Document  size should be less than 4MB";
					$this->Assign($tmp[$i],"","noempty",'Document - '.$size_mes);
				}

			}
			$i++;
		}



		$this->PerformValidation('index.php?do=addnewinvestor');
	}

	function valBranchApplication()
	{

		$fields = array("br_orgcaddr1","br_orgc_addr2","br_orgc_city","br_orgc_country","br_orgc_pc","br_orgc_ph_country","br_orgc_ph_area", "br_orgc_ph_pn","br_orgc_fn_country","br_orgc_fn_area","br_orgc_fn_pn","br_orgc_email");
		$addressno = $_POST['addressno'];




		$this->Assign("br_orgcaddr1", $_POST['br_orgcaddr1'],"noempty",
							"".$this->nullmessage);

// 		$this->Assign("orgc_addr2", $_POST['orgc_addr2'],"nospecial' '",
// 							"".$this->spcharmessage);

		$this->Assign("br_orgc_city", $_POST['br_orgc_city'],"noempty/nospecial' '",
							"".$this->nullmessage.
							"/".$this->spcharmessage);

		$this->Assign("br_orgc_state", $_POST['br_orgc_state'],"nospecial' '",
							"".$this->spcharmessage);

		$this->Assign("br_orgc_country", $_POST['br_orgc_country'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("br_orgc_pc", $_POST['br_orgc_pc'],"noempty/nospecial' '",
							"".$this->nullmessage."/".$this->spcharmessage);

		$this->Assign("br_orgc_ph_country", $_POST['br_orgc_ph_country'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("br_orgc_ph_area", $_POST['br_orgc_ph_area'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("br_orgc_ph_pn", $_POST['br_orgc_ph_pn'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("br_orgc_fn_country", $_POST['br_orgc_fn_country'],"nostring/nospecial' '",
							"".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("br_orgc_fn_area", $_POST['br_orgc_fn_area'],"nostring/nospecial' '",
							"".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("br_orgc_fn_pn", $_POST['br_orgc_fn_pn'],"nostring/nospecial' '",
							"".$this->numbermessage.
							"/".$this->spcharmessage);

		if(!$this->isValidEmail($_POST['br_orgc_email']))
		$this->Assign("br_orgc_email","","noempty",
							"".$this->emailmessage);

/*
			$this->Assign("p_orgcaddr1", $_POST['p_orgcaddr1'],"noempty",
							"".$this->nullmessage);

	// 		$this->Assign("p_orgc_addr2", $_POST['p_orgc_addr2'],"nospecial' '",
	// 							"".$this->spcharmessage);

			$this->Assign("p_orgc_city", $_POST['p_orgc_city'],"noempty/nospecial' '",
								"".$this->nullmessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_state", $_POST['p_orgc_state'],"nospecial' '",
								"".$this->spcharmessage);

			$this->Assign("p_orgc_country", $_POST['p_orgc_country'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_pc", $_POST['p_orgc_pc'],"noempty/nospecial' '",
								"".$this->nullmessage."/".$this->spcharmessage);

			$this->Assign("p_orgc_ph_country", $_POST['p_orgc_ph_country'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_ph_area", $_POST['p_orgc_ph_area'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_ph_pn", $_POST['p_orgc_ph_pn'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_ph_pn", $_POST['p_orgc_ph_pn'],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_fn_area", $_POST['p_orgc_fn_area'],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);

			$this->Assign("p_orgc_fn_pn", $_POST['p_orgc_fn_pn'],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);

			if(!$this->isValidEmail($_POST['p_orgc_email']))
			$this->Assign("p_orgc_email", "","noempty",
								"".$this->emailmessage);*/


		$this->Assign("bank_name", $_POST['bank_name'],"noempty",
							"".$this->nullmessage);


		$this->Assign("bank_orgcaddr1", $_POST['bank_orgcaddr1'],"noempty",
							"".$this->nullmessage);

// 		$this->Assign("bank_orgc_addr2", $_POST['bank_orgc_addr2'],"nospecial' '",
// 							"".$this->spcharmessage);

		$this->Assign("bank_orgc_city", $_POST['bank_orgc_city'],"noempty/nospecial' '",
							"".$this->nullmessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_state", $_POST['bank_orgc_state'],"nospecial' '",
							"".$this->spcharmessage);

		$this->Assign("bank_orgc_country", $_POST['bank_orgc_country'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_pc", $_POST['bank_orgc_pc'],"noempty/nospecial' '",
							"".$this->nullmessage."/".$this->spcharmessage);


		$this->Assign("bank_orgc_ph_country", $_POST['bank_orgc_ph_country'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_ph_area", $_POST['bank_orgc_ph_area'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_ph_pn", $_POST['bank_orgc_ph_pn'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_fn_country", $_POST['bank_orgc_fn_country'],"nostring/nospecial' '",
							"".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_fn_area", $_POST['bank_orgc_fn_area'],"nostring/nospecial' '",
							"".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("bank_orgc_fn_pn", $_POST['bank_orgc_fn_pn'],"nostring/nospecial' '",
							"".$this->numbermessage.
							"/".$this->spcharmessage);


		if($_POST['bank_orgc_email'] !='')	{
			if(!$this->isValidEmail($_POST['bank_orgc_email']))
			$this->Assign("bank_orgc_email", "","noempty",
								"".$this->emailmessage);
		}



		if($_POST['bank_c_email'] !='')	{

			if(!$this->isValidEmail($_POST['bank_c_email']))
			$this->Assign("bank_c_email", "","noempty",
								"".$this->emailmessage);
		}


		$this->Assign("account_name", $_POST['account_name'],"noempty",
							"".$this->nullmessage);

		$this->Assign("account_no", $_POST['account_no'],"noempty",
							"".$this->nullmessage);

		$this->Assign("sort_code", $_POST['sort_code'],"noempty",
							"".$this->nullmessage);

		$this->Assign("iban_code", $_POST['iban_code'],"noempty",
							"".$this->nullmessage);

		$this->Assign("swift_code", $_POST['swift_code'],"noempty",
							"".$this->nullmessage);

		$this->PerformValidation('index.php?do=addnewbranch');

	}


	function updateDebtorHistory()
	{
		$this->Assign("report_type",trim($_POST['report_type']),"noempty",$this->nullmessage);
		$this->Assign("report_number",trim($_POST['report_number']),"noempty",$this->nullmessage);
		$this->Assign("report_day",trim($_POST['report_day']),"noempty",$this->nullmessage);
		$this->Assign("report_month",trim($_POST['report_month']),"noempty",$this->nullmessage);
		$this->Assign("report_year",trim($_POST['report_year']),"noempty",$this->nullmessage);
		$this->Assign("report_branch",trim($_POST['report_branch']),"noempty",$this->nullmessage);
		$this->Assign("report_total",trim($_POST['report_total']),"noempty",$this->nullmessage);

		$this->Performvalidation('index.php?do=editdebtorhistory&id='.intval($_REQUEST['id']).'&rep_id='.intval($_REQUEST['rep_id']));
	}

	function updateDebtorApplication() {
		$this->Assign("deb_name",trim($_POST['deb_name']),"noempty",$this->nullmessage);
		$this->Assign("debtor_crn",trim($_POST['debtor_crn']),"noempty",$this->nullmessage);
		$this->Assign("address1",trim($_POST['address1']),"noempty",$this->nullmessage);
		$this->Assign("state",trim($_POST['state']),"noempty",$this->nullmessage);

        $query=new Bin_Query();
		$query->executeQuery('SELECT `type`
                              FROM debtors_detail
                              WHERE debtor_id='.$_POST['id']);

		if($query->records[0]['type']=='creditor') {
			$this->Assign("payment_discount",trim($_POST['payment_discount']),
				"noempty/nostring/percentage",
				$this->nullmessage."/".$this->numbermessage."/".$this->maxpercentvaluemessage);
        }

		$this->Assign("postal",trim($_POST['postal']),"noempty",$this->nullmessage);
		$this->Assign("country",trim($_POST['country']),"noempty",$this->nullmessage);

		$this->Assign("p_ph_code",trim($_POST['p_ph_code']),
			"noempty/format'".FORMAT_VALIDATE_PHONE_NUMBER."'",
			$this->nullmessage."/".$this->formatmessage);

		if(strlen(trim($_POST['f_ph_code']))>0) {
			$this->Assign("f_ph_code",trim($_POST['f_ph_code']),
				"noempty/format'".FORMAT_VALIDATE_PHONE_NUMBER."'",
				$this->nullmessage."/".$this->formatmessage);
		}

		$this->Assign("email",trim($_POST['email']),
			"noempty/emailcheck",
			$this->nullmessage."/".$this->emailmessage);

		$this->Assign("b_address1",trim($_POST['b_address1']),"noempty",$this->nullmessage);
		$this->Assign("b_state",trim($_POST['b_state']),"noempty",$this->nullmessage);
		$this->Assign("b_postal",trim($_POST['b_postal']),"noempty",$this->nullmessage);
		$this->Assign("b_country",trim($_POST['b_country']),"noempty",$this->nullmessage);

		$this->Assign("b_ph_code",trim($_POST['b_ph_code']),
			"noempty/format'".FORMAT_VALIDATE_PHONE_NUMBER."'",
			$this->nullmessage."/".$this->formatmessage);

		if(strlen(trim($_POST['f1_ph_code']))>0) {
			$this->Assign("f1_ph_code",trim($_POST['f1_ph_code']),
				"noempty/format'".FORMAT_VALIDATE_PHONE_NUMBER."'",
				$this->nullmessage."/".$this->formatmessage);
		}

		$this->Assign("b_email",trim($_POST['b_email']),
			"noempty/emailcheck",
			$this->nullmessage."/".$this->emailmessage);

		$this->Assign("d_name",trim($_POST['d_name']),"noempty",$this->nullmessage);

		$this->Assign("d_ph_code",trim($_POST['d_ph_code']),
			"noempty/format'".FORMAT_VALIDATE_PHONE_NUMBER."'",
			$this->nullmessage."/".$this->formatmessage);

		$this->Assign("d_email",trim($_POST['d_email']),
			"noempty/emailcheck",
			$this->nullmessage."/".$this->emailmessage);


		$this->Assign("d_since",$_POST['d_since'],"noempty/nospecial''",
			$this->nullmessage."/".$this->spcharmessage);

		if(strlen(trim($_POST['d_value']))>0) {
			$this->Assign("d_value",trim($_POST['d_value']),
				"noempty/nostring",
				$this->nullmessage."/".$this->numbermessage);
		}

		$this->Assign("d_payment",trim($_POST['d_payment']),
			"noempty/onlyinteger",
			$this->nullmessage."/".$this->numbermessage);

		if(strlen(trim($_POST['d_notes']))>0) {
			$this->Assign("d_notes",trim($_POST['d_notes']),
				"onlyinteger",$this->numbermessage);
		}

		$this->Assign("d_invoice",trim($_POST['d_invoice']),
			"noempty/onlyinteger",
			$this->nullmessage."/".$this->numbermessage);

		$this->Assign("d_revenue",$_POST['d_revenue'],
			"noempty/nostring",
			$this->nullmessage."/".$this->numbermessage);

		$this->Assign("debtor_id",trim($_POST['id']),"noempty",$this->nullmessage);
		$this->Performvalidation('index.php?do=editdebtor&id='.intval($_REQUEST['id']));
	}

	function saveMyTradeQuestion(){
		//echo "<pre>"; print_r($_POST); exit;
		$this->Assign("secret_quest", $_POST["secret_quest"],"noempty","".$this->nullmessage);
		$this->Assign("secret_answer", $_POST["secret_answer"],"noempty","".$this->nullmessage);

		$this->PerformValidation('index.php?do=editpersonal');
	}

	function saveMyTradePassword(){
		$user_id = $_SESSION['user']['userid'];

		$this->Assign("oldpasswd", $_POST["oldpasswd"],"noempty","".$this->nullmessage);
		$this->Assign("passwd", $_POST["passwd"],"noempty","".$this->nullmessage);
		$this->Assign("retype", $_POST["retype"],"noempty","".$this->nullmessage);

		if($_POST["oldpasswd"] !='')
		{
			$query = new Bin_Query();
			$sql_user = "SELECT * FROM temp_registration WHERE user_id = '".$user_id."'
				AND password = '" . Bin_Security::hashPassword($_POST["oldpasswd"]) . "'";
			$query->executeQuery($sql_user);
			$profile = $query->records;

			if(count($profile) == 0)
			{
				$message="Incorrect current password";
				$this->Assign("oldpasswd",'',"noempty",$message);
			}
		}


		if($_POST["passwd"] !='' && $_POST["retype"] !='')
		{
			if($_POST["passwd"] != $_POST["retype"])
			{
				$message="Incorrect password confirmation";
				$this->Assign("retype",'',"noempty",$message);
				$_POST["retype"]='';
			}
		}
        if (Bin_Security::hashPassword($_POST['oldpasswd']) === Bin_Security::hashPassword($_POST['passwd'])) {
            $this->Assign("passwd", '', "noempty", "" . $this->samepasswordmessage);
        }
        if(mb_strlen($_POST['passwd'])<8)
        {
            $this->Assign("passwd", '', "noempty", '' . $this->passwordlengthmessage);
        }

		$this->PerformValidation('index.php?do=editpersonal');

	}
	function saveMyTrade(){

		$this->Assign("email", $_POST["email"],"noempty",
						"".$this->nullmessage);


		$this->Assign("f_name", $_POST["f_name"],"noempty",$this->nullmessage);

		$this->Assign("l_name", $_POST["l_name"],"noempty",$this->nullmessage);

		$this->Assign("job", $_POST["job"],"noempty",$this->nullmessage);

		$this->Assign("org_name", $_POST["org_name"],"noempty",$this->nullmessage);

		$this->Assign("org_addr", $_POST["org_addr"],"noempty",$this->nullmessage);

// 		$this->Assign("org_addr1", $_POST["org_addr1"],"noempty/nostring/nospecial' '",
// 								"".$this->nullmessage.
// 								"/".$this->numbermessage.
// 								"/".$this->spcharmessage);

		$this->Assign("org_code", $_POST["org_code"],"noempty",
								"".$this->nullmessage);
		$this->Assign("org_state", $_POST["org_state"],"nospecial' '",
								"".$this->spcharmessage);
		$this->Assign("org_country", $_POST["org_country"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_country", $_POST["org_ph_country"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_area", $_POST["org_ph_area"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_phone", $_POST["org_ph_phone"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);

		$this->Assign("org_m_country", $_POST["org_m_country"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_m_area", $_POST["org_m_area"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_m_phone", $_POST["org_m_phone"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);


		$this->Assign("address_fax_country", $_POST["address_fax_country"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("address_fax_code", $_POST["address_fax_code"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("address_fax", $_POST["address_fax"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);

		$this->Assign("siccat", $_POST["siccat"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("sicgp", $_POST["sicgp"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);


		$this->PerformValidation('index.php?do=editprofile');
	}



	function validateApplicationSeven(){

		$this->Assign("card_type", $_POST["card_type"],"noempty/nospecial' '",
						"".$this->nullmessage.
						"/".$this->spcharmessage);

		$this->Assign("number", $_POST["number"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("month", $_POST["month"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("year", $_POST["year"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("amount", $_POST["amount"],"noempty/nostring",
						"".$this->nullmessage.
						"/".$this->numbermessage);

		$this->Assign("cvv2", $_POST["cvv2"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);
		$this->Assign("name", $_POST["name"],"noempty/nospecial' '",
						"".$this->nullmessage.
						"/".$this->spcharmessage);

		$this->Assign("code", $_POST["code"],"nospecial' '",
						"".$this->spcharmessage);
		$this->PerformValidation('index.php?do=application7&org_id='.$_POST['org_id']);
	}

	function validateApplicationSix(){
		$this->Assign("inv_type",$_POST['inv_type'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		$this->Assign("debtor_id",$_POST['debtor_id'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		$query= new Bin_Query();
		if (empty($_REQUEST['debtor_type']))
		{
			$query->executeQuery('SELECT debtors_detail.type
                                  FROM invoice_master
                                  LEFT JOIN debtors_detail ON debtors_detail.debtor_id = invoice_master.debtor_id
                                  WHERE invoice_id="'.$_POST['debtor_id'].'"');
		}
		elseif($_REQUEST['debtor_type']=='creditor')
		{
			$query->executeQuery('SELECT debtors_detail.type
                                  FROM debtors_detail
                                  WHERE debtor_id="'.$_POST['debtor_id'].'"');
		}

		if (count($query->records)==0)
		{
			$this->Assign("debtor_id",$_POST['debtor_id'],"nonumber","Debtor is Not Available");
			$this->PerformValidation('index.php?do=application6&org_id='.$_SESSION['org_id'].'&type=debtor');
		}

		$debtor=$query->records[0];

		if($_REQUEST['submits'] == 'Submit' AND $debtor['type']=='debtor')
		{
			$invoice_id = trim($_POST['debtor_id']);

			if($invoice_id !='')
			{
				$query->executeQuery("SELECT * 
                                     FROM `invoice_closed` 
                                     where  invoice_id = '".$invoice_id."' 
                                     LIMIT 1 ");
				if(count($query->records) == 0)
				{
					$this->Assign("invoice","","noempty","Until the Revolving ETR is Live on Trade Floor, You cannot Upload the new Invoice");
				}
				else
				{
					$query->executeQuery("SELECT * 
                                          FROM `invoice_master` 
                                          WHERE  root_invoice_id = '".$invoice_id."' && invoice_id != '".$_REQUEST['id']."'  && invoice_status != 3 ");

					if(count($query->records) > 0)
					{
						$this->Assign("invoice","","noempty","Until the Revolving ETR is Live on Trade Floor, You cannot Upload the new Invoice");
					}
				}
			}
		}

		if($_POST['face_value']=='')
		{
			$this->Assign("face_value",$_POST['face_value'],"noempty/nostring","".$this->nullmessage."/".$this->numbermessage);
		}
		elseif($_POST['face_value']<=0)
		{
			$this->Assign("face_value",'',"noempty","It Should be greater than 0");
		}
		else
		{
			if(!$this->validateSpecialChar($_POST['face_value']))
			{
				$this->Assign("face_value",'',"noempty",$this->spcharmessage);
			}
		}

		if ($debtor['type']=='debtor')
		{
			if($_POST['payment']=='')
			{
				$this->Assign("payment",$_POST['payment'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
			}
			elseif($_POST['payment']<=0)
			{
				$this->Assign("payment",'',"noempty","It Should be greater than 0");
			} else {
				include("admin/classes/Model/MSiteSetting.php");

				$siteSettings = new Model_MSiteSetting();
				$settings = $siteSettings->ViewSiteSetting();
				if ($_POST['payment'] > (int)$settings['max_edso']) {
					$this->Assign("payment", '', "noempty", "The value must not exceed  " . $settings['max_edso'] . "!");
				}
			}

			$this->Assign("ex_date",$_POST['ex_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

			$this->Assign("ex_date",$_POST['ex_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

			$this->Assign("ex_date",$_POST['ex_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
		}
		else
		{
			$this->Assign("payment_discount",$_POST['payment_discount'],"noempty",$this->nullmessage);
		}

		$dates = $_POST['ex_year']."-".$_POST['ex_month']."-".$_POST['ex_date'];

		$this->Assign("invoice_date",$_POST['invoice_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("invoice_date",$_POST['invoice_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		$this->Assign("invoice_date",$_POST['invoice_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		$dates= $_POST['invoice_year']."-".$_POST['invoice_month']."-".$_POST['invoice_date'];
		$query->executeQuery(" SELECT DATEDIFF('".$dates."',NOW()) as day ");
		$apprtime= $query->records;

		if($apprtime[0]['day'] > 0)
		{
			$this->Assign("invoice_date","","noempty","the Invoice Date cannot be greater than today’s date!  Enter today’s date or a prior date");
		}

		$dates 		= $_POST['ex_year'].$_POST['ex_month'].$_POST['ex_date'];

		$dates1 		= $_POST['invoice_year'].$_POST['invoice_month'].$_POST['invoice_date'];

		if($dates < $dates1)
		{
			$this->Assign("ex_date","","noempty","Expected Date should be greater than Invoice Date");
		}

		$mime = array('application/force-download','application/pdf','application/x-pdf','application/x-bzpdf','application/x-gzpdf');

		if($_POST['invoicefile'] =='' && $_FILES['file_invoice']['tmp_name'] == "")
		{
			$this->Assign("invoicefile",$_POST['invoicefile'],"noempty","".$this->nullmessage);
		}

		$query->executeQuery("SELECT etr_pod_mandatory  
                              FROM organisation_details
                              WHERE  user_id ='".$_SESSION['user']['userid']."' LIMIT 1 ");
		$orgDetails 	= $query->records[0];

		if($orgDetails['etr_pod_mandatory'] == '1' && $_POST['pofile'] =='' && $_FILES['file_po']['tmp_name'] == "")
		{
			$this->Assign("pofile",$_POST['pofile'],"noempty","".$this->nullmessage);
		}


		$query->executeQuery("SELECT organisation_reference_id 
                              FROM organisation_details 
                              WHERE user_id='".$_SESSION['user']['userid']."' 
                              LIMIT 1 ");
		$organisation_reference_id = $query->records[0]['organisation_reference_id'];

		if(!isset($_SESSION['invoicefile']))
		{
			$_SESSION['invoicefile'] = $_POST['invoicefile'];
		}

		if(!isset($_SESSION['supportfile']))
		{
			$_SESSION['supportfile'] = $_POST['supportfile'];
		}

		if(!isset($_SESSION['pofile']))
		{
			$_SESSION['pofile'] = $_POST['pofile'];
		}

		$this->Assign("po",$_POST['po'],"noempty","".$this->nullmessage);

		if($_POST['invoice_no']=='')
		{
			$this->Assign("invoice_no",$_POST['invoice_no'],"noempty","".$this->nullmessage);
		}
		else
		{
			$pos = strpos($_POST['invoice_no'], '0');

			if($pos=='0' && is_numeric($pos))
			{
				$this->Assign("invoice_no","","noempty","0 not allowed for first digit on Invoice No, remove and re-enter!");
			}
			else
			{
				$qry 	= new Bin_Query();
				if($_REQUEST['do']=='saverevolvingdraft')
				{
					$sql 	= "SELECT m.invoice_no FROM `invoice_master` m WHERE m.invoice_no='".trim($_POST['invoice_no'])."' && m.invoice_id!='".$_REQUEST['id']."' && m.user_id='".$_SESSION['user']['userid']."' ";
				}
				else
				{
					$sql 	= "SELECT m.invoice_no FROM `invoice_master` m WHERE m.invoice_no='".trim($_POST['invoice_no'])."' && m.user_id='".$_SESSION['user']['userid']."' ";
				}
				$qry->executeQuery($sql);
				if($qry->totrows>0)
				{
					$this->Assign("invoice_no","","noempty","This invoice number has already been traded. Enter a new, previously untraded invoice!");
				}
			}
		}

		$dcnt =  count($_FILES);
		$tmp = 'file_invoice';
		for($d=1;$d<=$dcnt;$d++)
		{
			if($_FILES[$tmp]['tmp_name'] != "")
			{
				$type = $_FILES[$tmp]['type'];
				if($_FILES[$tmp]['size'] <= 419430400)
				{
					if(!in_array($type, $mime))
					{
						$message = "Invoice upload that creates an ETR can only be in PDF format";
						$this->Assign("invoicefile",'',"noempty",''.$message);
					}
				}
				else
				{
					$size_mes = "Invoice upload that creates an ETR can only be in PDF format and size should be less than 4MB";
					$this->Assign("invoicefile","","noempty",''.$size_mes);
				}
			}
			if($d==1)$tmp = 'file_support'; if($d==2)$tmp = 'file_po';
		}

		$this->PerformValidation('index.php?do=application6&org_id='.$_SESSION['org_id'].'&type=debtor');
	}

	function validateApplicationSixCEtr()
	{
		$this->Assign("inv_type",$_POST['inv_type'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		$this->Assign("debtor_id",$_POST['debtor_id'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		$query= new Bin_Query();
		if (empty($_REQUEST['debtor_type']))
		{
			$query->executeQuery('SELECT debtors_detail.type
                                  FROM invoice_master
                                  LEFT JOIN debtors_detail ON debtors_detail.debtor_id = invoice_master.debtor_id
                                  WHERE invoice_id="'.$_POST['debtor_id'].'"');
		}
		elseif($_REQUEST['debtor_type']=='creditor')
		{
			$query->executeQuery('SELECT debtors_detail.type
                                  FROM debtors_detail
                                  WHERE debtor_id="'.$_POST['debtor_id'].'"');
		}
		$link = 'application6&type=creditor';

		if (count($query->records)==0)
		{
            $this->PerformValidation('index.php?do=' . $link);
		}

		$debtor=$query->records[0];



		if($_POST['face_value']=='')
		{
			$this->Assign("face_value",$_POST['face_value'],"noempty/nostring","".$this->nullmessage."/".$this->numbermessage);
		}
		elseif($_POST['face_value']<=0)
		{
			$this->Assign("face_value",'',"noempty","It Should be greater than 0");
		}
		else
		{
			if(!$this->validateSpecialChar($_POST['face_value']))
			{
				$this->Assign("face_value",'',"noempty",$this->spcharmessage);
			}
		}

		if ($debtor['type']=='debtor')
		{
			if($_POST['payment']=='')
			{
				$this->Assign("payment",$_POST['payment'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
			}
			elseif($_POST['payment']<=0)
			{
				$this->Assign("payment",'',"noempty","It Should be greater than 0");
			} else {
				include_once("admin/classes/Model/MSiteSetting.php");

				$siteSettings = new Model_MSiteSetting();
				$settings = $siteSettings->ViewSiteSetting();
				if ($_POST['payment'] > (int)$settings['max_edso']) {
					$this->Assign("payment", '', "noempty", "The value must not exceed  " . $settings['max_edso'] . "!");
				}
			}

			$this->Assign("ex_date",$_POST['ex_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

			$this->Assign("ex_date",$_POST['ex_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

			$this->Assign("ex_date",$_POST['ex_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
		}
		else
		{
			$this->Assign("payment_discount",$_POST['payment_discount'],"noempty",$this->nullmessage);
		}

		$dates = $_POST['ex_year']."-".$_POST['ex_month']."-".$_POST['ex_date'];

		$this->Assign("invoice_date",$_POST['invoice_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("invoice_date",$_POST['invoice_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		$this->Assign("invoice_date",$_POST['invoice_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		$dates= $_POST['invoice_year']."-".$_POST['invoice_month']."-".$_POST['invoice_date'];
		$query->executeQuery(" SELECT DATEDIFF('".$dates."',NOW()) as day ");
		$apprtime= $query->records;

		if($apprtime[0]['day'] > 0)
		{
			$this->Assign("invoice_date","","noempty","the Invoice Date cannot be greater than today’s date!  Enter today’s date or a prior date");
		}

		$dates 		= $_POST['ex_year'].$_POST['ex_month'].$_POST['ex_date'];

		$dates1 		= $_POST['invoice_year'].$_POST['invoice_month'].$_POST['invoice_date'];

		if($dates < $dates1)
		{
			$this->Assign("ex_date","","noempty","Expected Date should be greater than Invoice Date");
		}

		$mime = array('application/force-download','application/pdf','application/x-pdf','application/x-bzpdf','application/x-gzpdf');

		if($_POST['invoicefile'] =='' && $_FILES['file_invoice']['tmp_name'] == "")
		{
			$this->Assign("invoicefile",$_POST['invoicefile'],"noempty","".$this->nullmessage);
		}

		$query->executeQuery("SELECT etr_pod_mandatory  
                              FROM organisation_details
                              WHERE  user_id ='".$_SESSION['user']['userid']."' LIMIT 1 ");
		$orgDetails 	= $query->records[0];

		if($orgDetails['etr_pod_mandatory'] == '1' && $_POST['pofile'] =='' && $_FILES['file_po']['tmp_name'] == "")
		{
			$this->Assign("pofile",$_POST['pofile'],"noempty","".$this->nullmessage);
		}


		$query->executeQuery("SELECT organisation_reference_id 
                              FROM organisation_details 
                              WHERE user_id='".$_SESSION['user']['userid']."' 
                              LIMIT 1 ");
		$organisation_reference_id = $query->records[0]['organisation_reference_id'];

		if(!isset($_SESSION['invoicefile']))
		{
			$_SESSION['invoicefile'] = $_POST['invoicefile'];
		}

		if(!isset($_SESSION['supportfile']))
		{
			$_SESSION['supportfile'] = $_POST['supportfile'];
		}

		if(!isset($_SESSION['pofile']))
		{
			$_SESSION['pofile'] = $_POST['pofile'];
		}

		$this->Assign("po",$_POST['po'],"noempty","".$this->nullmessage);

		if($_POST['invoice_no']=='')
		{
			$this->Assign("invoice_no",$_POST['invoice_no'],"noempty","".$this->nullmessage);
		}
		else
		{
			$pos = strpos($_POST['invoice_no'], '0');

			if($pos=='0' && is_numeric($pos))
			{
				$this->Assign("invoice_no","","noempty","0 not allowed for first digit on Invoice No, remove and re-enter!");
			}
			else
			{
				$qry 	= new Bin_Query();
				if($_REQUEST['do']=='saverevolvingdraft')
				{
					$sql 	= "SELECT m.invoice_no FROM `invoice_master` m WHERE m.invoice_no='".trim($_POST['invoice_no'])."' && m.invoice_id!='".$_REQUEST['id']."' && m.user_id='".$_SESSION['user']['userid']."' ";
				}
				else
				{
					$sql 	= "SELECT m.invoice_no FROM `invoice_master` m WHERE m.invoice_no='".trim($_POST['invoice_no'])."' && m.user_id='".$_SESSION['user']['userid']."' ";
				}
				$qry->executeQuery($sql);
				if($qry->totrows>0)
				{
					$this->Assign("invoice_no","","noempty","This invoice number has already been traded. Enter a new, previously untraded invoice!");
				}
			}
		}

		$dcnt =  count($_FILES);
		$tmp = 'file_invoice';
		for($d=1;$d<=$dcnt;$d++)
		{
			if($_FILES[$tmp]['tmp_name'] != "")
			{
				$type = $_FILES[$tmp]['type'];
				if($_FILES[$tmp]['size'] <= 419430400)
				{
					if(!in_array($type, $mime))
					{
						$message = "Invoice upload that creates an ETR can only be in PDF format";
						$this->Assign("invoicefile",'',"noempty",''.$message);
					}
				}
				else
				{
					$size_mes = "Invoice upload that creates an ETR can only be in PDF format and size should be less than 4MB";
					$this->Assign("invoicefile","","noempty",''.$size_mes);
				}
			}
			if($d==1)$tmp = 'file_support'; if($d==2)$tmp = 'file_po';
		}

        $this->PerformValidation('index.php?do='.$link);
	}

	function validateApplicationFive_Two()
	{



		if(!checkdate(intval($_POST['fye_month']),intval($_POST['fye_date']),intval($_POST['fye_year'])))
		{
			$this->Assign("fye_year","","noempty","Enter a valid date");

		}
			$this->Assign("fye_year",$_POST['fye_month'],"noempty/nostring/nospecial' '"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("fye_year",$_POST['fye_date'],"noempty/nostring/nospecial' '"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("fye_year",$_POST['fye_year'],"noempty/nostring/nospecial' '"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);

		$this->Assign("turnover",$_POST['turnover'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("costofsale",$_POST['costofsale'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("sales_exp",$_POST['sales_exp'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("general_exp",$_POST['general_exp'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("hire",$_POST['hire'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("rent",$_POST['rent'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("admin_exp",$_POST['admin_exp'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("wages",$_POST['wages'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("social",$_POST['social'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("pension",$_POST['pension'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("depreciation",$_POST['depreciation'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("interest",$_POST['interest'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("ctax",$_POST['ctax'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);


		$this->PerformValidation('index.php?do=application5_2&org_id='.$_GET['org_id']);

	}

    function validateApplicationFive()
	{

		$this->Assign("debtor_name",$_POST['debtor_name'],"noempty","".$this->nullmessage);
		$this->Assign("debtor_crn",$_POST['debtor_crn'],"noempty","".$this->nullmessage);
		$this->Assign("organisation_id",$_POST['organisation_id'],"noempty","".$this->nullmessage);
		$this->Assign("debtor_type",$_POST['debtor_type'],"noempty","".$this->nullmessage);

		if ($_POST['debtor_type']=='creditor')
		{
			$this->Assign("payment_discount",$_POST['payment_discount'],"noempty","".$this->nullmessage);
			$this->Assign("sort_code",$_POST['sort_code'],"noempty","".$this->nullmessage);
			$this->Assign("swift_code",$_POST['swift_code'],"noempty","".$this->nullmessage);
			$this->Assign("account_number",$_POST['account_number'],"noempty","".$this->nullmessage);
			$this->Assign("bank_name",$_POST['bank_name'],"noempty","".$this->nullmessage);
			$this->Assign("iban_number",$_POST['iban_number'],"noempty","".$this->nullmessage);
		}


		$this->Assign("address1",$_POST['address1'],"noempty","".$this->nullmessage);
		$this->Assign("city",$_POST['city'],"noempty","".$this->nullmessage);
		$this->Assign("currency_id",$_POST['currency_id'],"noempty","".$this->nullmessage);
		$this->Assign("country",$_POST['country'],"noempty","".$this->nullmessage);
		$this->Assign("postal",$_POST['postal'],"noempty","".$this->nullmessage);
		$this->Assign("p_c_code",$_POST['p_c_code'],"nostring/nospecial''","".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("p_area_code",$_POST['p_area_code'],"nostring/nospecial''","".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("p_ph_code",$_POST['p_ph_code'],"nostring/nospecial''","".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("f_c_code",$_POST['f_c_code'],"nostring/nospecial' '","".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("f_area_code",$_POST['f_area_code'],"nostring/nospecial''","".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("f_ph_code",$_POST['f_ph_code'],"nostring/nospecial''","".$this->numbermessage."/".$this->spcharmessage);

		if(!$this->isValidEmail($_POST['email']) && $_POST['email'] !="")
			$this->Assign("email","","noempty","".$this->emailmessage);

		if($_POST['same_billing_address']!="1")
		{
			$this->Assign("b_address1",$_POST['b_address1'],"noempty","".$this->nullmessage);
			$this->Assign("b_city",$_POST['b_city'],"noempty","".$this->nullmessage);
			$this->Assign("b_country",$_POST['b_country'],"noempty/nospecial''","".$this->nullmessage."/".$this->spcharmessage);
			$this->Assign("b_postal",$_POST['b_postal'],"noempty","".$this->nullmessage);
			$this->Assign("b_p_c_code",$_POST['b_p_c_code'],"nostring/nospecial''","".$this->numbermessage."/".$this->spcharmessage);
			$this->Assign("b_p_area_code",$_POST['b_p_area_code'],"nostring/nospecial''","".$this->numbermessage."/".$this->spcharmessage);
			$this->Assign("b_p_ph_code",$_POST['b_p_ph_code'],"nostring/nospecial''","".$this->numbermessage."/".$this->spcharmessage);
			$this->Assign("b_f_c_code",$_POST['b_f_c_code'],"nostring","".$this->numbermessage);
			$this->Assign("b_f_area_code",$_POST['b_f_area_code'],"nostring/nospecial''","".$this->numbermessage."/".$this->spcharmessage);
			$this->Assign("b_f_ph_code",$_POST['b_f_ph_code'],"nostring/nospecial''","".$this->numbermessage."/".$this->spcharmessage);

			if(!$this->isValidEmail($_POST['b_email']) && $_POST['b_email'] !="")
				$this->Assign("b_email","","noempty/nospecial''","".$this->emailmessage."/".$this->emailmessage);
		}

		$this->Assign("d_name",$_POST['d_name'],"noempty/nospecial' '","".$this->nullmessage."/".$this->spcharmessage);
		$this->Assign("d_c_code",$_POST['d_c_code'],"noempty/nospecial''","".$this->nullmessage."/".$this->spcharmessage);
		$this->Assign("d_area_code",$_POST['d_area_code'],"noempty/nospecial''","".$this->nullmessage."/".$this->spcharmessage);
		$this->Assign("d_ph_code",$_POST['d_ph_code'],"noempty/nospecial''","".$this->nullmessage."/".$this->spcharmessage);

		if(!$this->isValidEmail($_POST['d_email']))
			$this->Assign("d_email","","noempty/nospecial''","".$this->emailmessage."/".$this->emailmessage);

		$this->Assign("d_since",$_POST['d_since'],"noempty/nospecial''","".$this->nullmessage."/".$this->spcharmessage);
		$this->Assign("found_date",$_POST['found_date'],"nostring/nospecial","".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("found_date",$_POST['found_month'],"nostring/nospecial","".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("found_date",$_POST['found_year'],"nostring/nospecial","".$this->numbermessage."/".$this->spcharmessage);

		$this->Assign("d_payment",$_POST['d_payment'],"noempty/nostring","".$this->nullmessage."/".$this->numbermessage);

		$this->Assign("d_invoice",$_POST['d_invoice'],"noempty/nostring","".$this->nullmessage."/".$this->numbermessage);
		$this->Assign("d_revenue",$_POST['d_revenue'],"noempty/nostring","".$this->nullmessage."/".$this->numbermessage);

		$action='index.php?do=application5&org_id='.$_GET['org_id'];

		if ($_POST['debtor_type']=='debtor')
		{
			$tmp='filecsv';

			require_once('classes/Lib/PHPExcel/IOFactory.php');
			require_once('classes/Lib/debtorHistoryFileAPI.php');

			if(empty($_POST['customMapping']))
			{
				if(empty($_FILES[$tmp]['tmp_name']))
				{
					$this->Assign($tmp,"","noempty","You must upload Debtor Experience File!");
					$this->PerformValidation($action);
					return;
				}

				if(debtorHistoryFileAPI::checkFileCount($_FILES)===false)
				{
					$this->Assign($tmp,'',"noempty","You can upload only ".
						"a single Debtor Experience File!");
					$this->PerformValidation($action);
					return;
				}

				if(debtorHistoryFileAPI::checkFileSize($_FILES[$tmp]['size'])===false)
				{
					$this->Assign($tmp,"","noempty","The Debtor Experience File size ".
						"should be less than 4MB");
					$this->PerformValidation($action);
					return;
				}

				if(debtorHistoryFileAPI::checkFileMime($_FILES[$tmp]['type'])===false)
				{
					$this->Assign($tmp,'',"noempty","The Debtor Experience File must be ".
						"uploaded in either of the following formats: XLS, XLSX, CSV");
					$this->PerformValidation($action);
					return;
				}
				$fileName=$_FILES[$tmp]["tmp_name"];
			}
			else
				$fileName="";

			$debtHistFileObj=new debtorHistoryFileAPI($fileName);
			if(strlen($fileName)==0 && !empty($_SESSION['csvFileObject']))
			{
				$debtHistFileObj->setDataObject($_SESSION['csvFileObject']);
				$debtHistFileObj->setTypeMapping($_POST);
				$debtHistFileObj->parseWorkSheet();
				unset($_SESSION['csvFileObject']);
			}

			$errorsFound=$debtHistFileObj->getErrors();
			$undefTypes=$debtHistFileObj->getUndefinedTypes();

			if(count($undefTypes)>0 && strlen($errorsFound)==0)
			{
				$_SESSION['csvFileUndefinedTypes']=$undefTypes;
				$errorsFound=1;
			}
			else
				unset($_SESSION['csvFileUndefinedTypes']);


			if(strlen($errorsFound)>0)
			{
				if(empty($_SESSION['csvFileUndefinedTypes']))
				{
					$errorsFound=preg_replace("/".trim($nlChars)."$/","",trim($errorsFound));
					$message="Upload file may not be correctly formatted. ".
						"Use the template link below, format the file correctly and then try again.  ".
						"<br>".$errorsFound;
				}
				else
				{
					$message="Type clarification required. See above for details.";
					$_SESSION['csvFileObject']=$debtHistFileObj->getSerializedDataObject();
				}
				$this->Assign($tmp,'',"noempty",$message);
				unset($_SESSION['csvFileData']);
			}
			else
			{
				$data=$debtHistFileObj->getData();
				array_shift($data);
				$_SESSION['csvFileData']=$data;
			}
		}
		$this->PerformValidation($action);
	}

	function validateApplicationFour(){
		$this->Assign("f_date", $_POST['f_date'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("f_month", $_POST['f_month'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("f_year", $_POST['f_year'],"noempty/nostring/nospecial' '",
							"".$this->nullmessage.
							"/".$this->numbermessage.
							"/".$this->spcharmessage);

		$this->Assign("f_bank", $_POST['f_bank'],"noempty/nospecial' '",
							"".$this->nullmessage.
							"/".$this->spcharmessage);

		$this->Assign("allowance", $_POST['allowance'],"noempty/nospecial' '",
							"".$this->nullmessage.
							"/".$this->spcharmessage);

		if($_POST['allowance'] == 1){
		$this->Assign("f_allowance", $_POST['f_allowance'],"noempty",
							"".$this->nullmessage);
		}

		$this->Assign("f_paywork", $_POST['f_paywork'],"noempty",
							"".$this->nullmessage);

		$this->Assign("system", $_POST['system'],"noempty",
							"".$this->nullmessage);

		if($_POST['system'] == 1){
			$this->Assign("f_system", $_POST['f_system'],"noempty",
							"".$this->nullmessage);
		}

		$this->Assign("f_sell", $_POST['f_sell'],"noempty/nospecial' '",
							"".$this->nullmessage.
							"/".$this->spcharmessage);

		$this->Assign("f_warranty", $_POST['f_warranty'],"noempty/nospecial' '",
							"".$this->nullmessage.
							"/".$this->spcharmessage);

		if($_POST['f_warranty'] ==1){
			$this->Assign("warranty", $_POST['warranty'],"noempty",
							"".$this->nullmessage);
		}

		$this->Assign("f_return", $_POST['f_return'],"noempty/nospecial' '",
							"".$this->nullmessage.
							"/".$this->spcharmessage);

		$documents = Model_MTradeApplication::getStepFiveDocuments($_SESSION['org_id']);
		foreach($_FILES as $key => $file){
			if(!empty($file['name'])){
				if($file['type']!=='application/pdf'){
					$this->Assign($key, '', 'noempty', $this->doctypemessage);
				}
				if ($file['size'] > 4194304) {
					$this->Assign($key, '', 'noempty', $this->docsizemessage);
				}
			}else{
				if(empty($documents[$key])) {
					$this->Assign($key, '', 'noempty', $this->nullmessage);
				}
			}
		}

		$this->PerformValidation('index.php?do=application4&org_id='.$_POST['org_id']);

	}

	function validateApplicationThree()
    {
		$noder = $_POST['noder'];

		$this->Assign("fname", $_POST['fname'],"noempty",
						"".$this->nullmessage);

		$this->Assign("lname", $_POST['lname'],"noempty",
						"".$this->nullmessage);

		$this->Assign("pn", $_POST['pn'],"noempty",
						"".$this->nullmessage);

		if(!$this->isValidEmail($_POST["w_email"]))
			$this->Assign("w_email", "","noempty",
							"".$this->emailmessage);

		$mtrade = new Model_MTradeApplication();
		$details = current($mtrade->getOrgDetails($_SESSION['org_id']));


		$email_array = array();
		for($i = 0; $i < (int)$details['number_of_directors']; $i++)
		{
			$email_array["email_address_$i"] = $_POST["email_address_$i"];

			foreach(array('first_name', 'last_name', 'address_1',
						'email_address', 'ph_code', 'country_code',
                                        'financial_advisor','pension_value','savings_value') as $field
			) {
				$this->Assign( $field."_$i", $_POST[$field."_$i"], "noempty",
					"" . $this->nullmessage);
			}

			$this->Assign("email_address_".$i, $_POST["email_address_".$i], "emailcheck",
				$this->emailmessage);
                        $this->Assign("pension_value_".$i, $_POST["pension_value_".$i],"noempty/nostring",
				"".$this->nullmessage.
				"/".$this->numbermessage);
                        $this->Assign("savings_value_".$i, $_POST["savings_value_".$i],"noempty/nostring",
				"".$this->nullmessage.
				"/".$this->numbermessage);
		}
		$check_dublicate_email = array_count_values($email_array);
		foreach ($check_dublicate_email as $key => $val) {
			if ($val > 1 and !empty($key)) {
				$keys = array_keys($email_array, $key);
				foreach ($keys as $el) {
					// Dublicate email
					$this->Assign($el, '', 'noempty', 'Email address should be unique.');
				}
			}
		}

		$this->PerformValidation('index.php?do=application3&org_id='.$_POST['org_id']);
	}


	function validateApplicationTwo()
    {

        $this->Assign("currency_id",$_POST['currency_id'],"noempty","".$this->nullmessage);

		$this->Assign("bank_name", $_POST['bank_name'],"noempty",
							"".$this->nullmessage);
		if($_POST['bank_name'] == '0'){
			$this->Assign('bank_name', $_POST['bank_new'], 'noempty', $this->nullmessage);
		}
		$_SESSION['step_2_save']['bank_name'] = $_POST['bank_name'];

		if (empty($_POST['iban_code']) or empty($_POST['swift_code'])) {
			$this->Assign("account_name", $_POST['account_name'], "noempty",
				"" . $this->nullmessage);

			$this->Assign("account_no", $_POST['account_no'], "noempty",
				"" . $this->nullmessage);

			$this->Assign("sort_code", $_POST['sort_code'], "noempty",
				"" . $this->nullmessage);
		}

		if (empty($_POST['account_name']) or empty($_POST['account_no']) or empty($_POST['sort_code'])) {
			$this->Assign("iban_code", $_POST['iban_code'], "noempty",
				"" . $this->nullmessage);

			$this->Assign("swift_code", $_POST['swift_code'], "noempty",
				"" . $this->nullmessage);
		}

		$this->PerformValidation('index.php?do=application2&org_id='.$_POST['org_id']);


	}

	public function validateApplicationUpload()
	{
		$application = new Model_MTradeApplication();
		$documents = $application->getUploadedDocuments($_SESSION['user']['userid']);
		$this->Assign("uged_d", $documents['uged_d'], 'noempty', $this->nullmessage);

		$this->PerformValidation('index.php?do=applicationupload');
	}

	function validateApplicationOne()
    {
		$this->Assign("org_orgtype", $_POST['org_orgtype'],"noempty/nostring/nospecial' '",
					"".$this->nullmessage.
					"/".$this->numbermessage.
					"/".$this->spcharmessage);

		if(!in_array((int)$_POST['org_orgtype'], array(1, 27, 50)) and (int)$_POST['org_orgtype'] > 0)
		{
			$this->Assign("number_of_directors", $_POST['number_of_directors'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->numbermessage.
				"/".$this->spcharmessage);
		}

		$this->Assign("org_jurorg", $_POST['org_jurorg'],"noempty/nostring/nospecial' '",
					"".$this->nullmessage.
					"/".$this->numbermessage.
					"/".$this->spcharmessage);

		if($_POST['org_website'] !=''){

			if(!$this->isValidURL($_POST['org_website']))
				$this->Assign("org_website","","noempty",$this->urlmessage);
		}
		$this->Assign("org_ctn", $_POST['org_ctn'],"noempty/nospecial' '",
					"".$this->nullmessage."/".$this->spcharmessage);

		$this->Assign("org_vat", $_POST['org_vat'],"nospecial' '",
					"".$this->spcharmessage);

		$this->Assign("org_totemp", $_POST['org_totemp'],"noempty/nostring/nospecial' '",
					"".$this->nullmessage.
					"/".$this->numbermessage.
					"/".$this->spcharmessage);

		if($_POST['insurance_provider'] === 'null'){
			$this->Assign('insurance_provider', null, 'noempty', $this->nullmessage);
		}
		if($_POST['discount_provider'] === 'null'){
			$this->Assign('discount_provider', null, 'noempty', $this->nullmessage);
		}

		$this->PerformValidation('index.php?do=application1');
	}

	function saveDraftTrade(){


		$this->Assign("debtor_id",$_POST['debtor_id'],"noempty/nostring/nospecial",
			"".$this->nullmessage.
			"/".$this->numbermessage.
			"/".$this->spcharmessage);

		$sales_type=$_POST['sales_type'];
		$sales_arr=explode("-",$sales_type);
		$fieldSet=$sales_arr[1];
		$sales_type1=$sales_arr[0];

		$debtor_id = trim($_POST['debtor_id']);

		if($debtor_id !=''){

			$user_id 		= $_SESSION['user']['userid'];
			$query			= new Bin_Query();
			$sql 			= " SELECT dm.*  FROM `debtors_detail` as d, `debtors_master` as dm, `debtor_relation` as r ".
							" WHERE r.trader_id ='".$user_id."' && r.debtor_id = '".$debtor_id."' && (r.status ='1' || r.status ='5' || r.status ='6' || r.status ='7' || r.status='8') ".
							" && d.debtor_id = r.debtor_id && d.parent_id != 0 ".
							" && dm.debtor_master_id = d.parent_id  limit 1 ";
			$query->executeQuery($sql);
			$debtor 		= $query->records;


			$qry 			= new Bin_Query();
			$sql 			= "SELECT agreed_rate FROM `organisation_details` WHERE user_id='".$user_id."' ";
			$qry->executeQuery($sql);
			$agreed_rate 	= $qry->records[0]['agreed_rate'];


			if(count($debtor) > 0){

				if($fieldSet=="model1")
				{

					if($_POST['purchase_price']!=''){

						if($_POST['purchase_price'] < $agreed_rate){

						$this->Assign("purchase_price",$_POST['purchase_price'],"nonumber","The Outright Purchase price you are offering is lower than agreed rate. Increase it please");
						}

						// if($_POST['purchase_price'] < $debtor[0]['debtor_min_offers']){

						// $this->Assign("purchase_price",$_POST['purchase_price'],"nonumber","The Outright Purchase price you are offering is lower than minimum offer price. Increase it please");
						// }
					}


					if($_POST['purchase_price'] !=''  && $_POST['face_value'] != ''){

						$offer = ($debtor[0]['debtor_min_offers'] / 100 ) * $_POST['face_value'];

						if($_POST['purchase_price'] < $offer ){

							$this->Assign("purchase_price",$_POST['purchase_price'],"nonumber","The Outright Purchase price you are offering is too low. Increase it please");
						}
					}


					if($_POST['buyout_price'] != ''){

						if($_POST['buyout_price'] < $agreed_rate)


						$this->Assign("buyout_price",$_POST['buyout_price'],"nonumber","The Outright Purchase price you are offering is lower than agreed rate. Increase it please");
					}

					if($_POST['buyout_price'] > 0 && $_POST['buyout_price'] !=''   && $_POST['face_value'] != ''){

						$offer = ($debtor[0]['debtor_min_offers'] / 100 ) * $_POST['face_value'];

						if($_POST['buyout_price'] < $offer ){

							$this->Assign("buyout_price",$_POST['buyout_price'],"nonumber","The Outright Purchase price you are offering is too low. Increase it please");
						}
					}

				}else if($fieldSet=="model2"){

					if(isset($_POST['buyout']) and false){


						if($_POST['discount_price']==''){
							$this->Assign("discount_price",$_POST['discount_price'],"noempty",
							"".$this->nullmessage);
						}elseif($_POST['discount_price']<=0){

							$this->Assign("discount_price",'',"noempty","It Should be greater than 0");
						}

						if($_POST['discount_price'] !='' && $_POST['discount_price'] < $agreed_rate ){


							$this->Assign("discount_price",$_POST['discount_price'],"nonumber","The Minimum Agreed Rate ".
														" permitted is currently ".$agreed_rate."% ".
														" (where ".$agreed_rate." is the Minimum Offer percentage".
														")");

						}

						if($_POST['discount_price'] !='' && $_POST['discount_price'] < $debtor[0]['debtor_min_offers'] ){



							$this->Assign("discount_price",$_POST['discount_price'],"nonumber","The Minimum Discount Percentage ".
														" permitted is currently ".$debtor[0]['debtor_min_offers']."% ".
														" (where ".$debtor[0]['debtor_min_offers']." is the Minimum Offer percentage".
														" figure for the specific Master Debtor)");

						}


						if($_POST['buyout_discount_price']==''){
							$this->Assign("buyout_discount_price",$_POST['buyout_discount_price'],"noempty",
							"".$this->nullmessage);
						}elseif($_POST['buyout_discount_price']<=0){

							$this->Assign("buyout_discount_price",'',"noempty","It Should be greater than 0");
						}


						if($_POST['buyout_discount_price'] !='' && $_POST['buyout_discount_price'] < $agreed_rate ){


							$this->Assign("buyout_discount_price",$_POST['buyout_discount_price'],"nonumber","The Minimum Agreed Rate ".
														" permitted is currently ".$agreed_rate."% ".
														" (where ".$agreed_rate." is the Minimum Offer percentage".
														")");

						}

						if($_POST['buyout_discount_price'] > 0 && $_POST['buyout_discount_price'] !='' && $_POST['buyout_discount_price'] < $debtor[0]['debtor_min_offers'] ){

							$this->Assign("buyout_discount_price",$_POST['buyout_discount_price'],"nonumber","The Minimum Discount".
														" Percentage permitted is currently ".$debtor[0]['debtor_min_offers']."% ".
														" (where ".$debtor[0]['debtor_min_offers']." is the Minimum Offer ".
														" Percentage figure for the specific Master Debtor)");
						}
					}
				}

			}else{
				$this->Assign("debtor_id",$_POST['debtor_id'],"nonumber","Debtor is Not Available");
			}

		}


		if($sales_type=="4-model2")
		{
			if($_POST['etr_face_value']==''){
				$this->Assign("etr_face_value",$_POST['etr_face_value'],"noempty/nostring",
				"".$this->nullmessage."/".$this->numbermessage);
			}elseif($_POST['etr_face_value']<=0){

				$this->Assign("etr_face_value",'',"noempty","It Should be greater than 0");
			}else{

				if(!$this->validateSpecialChar($_POST['etr_face_value'])){
					$this->Assign("etr_face_value",'',"noempty",$this->spcharmessage);
				}
			}

			if(isset($_POST['etr_type']))

			$this->Assign("etr_type",$_POST['etr_type'],"noempty/nostring",
			"".$this->nullmessage."/".$this->numbermessage);


			if($_POST['etr_no']==''){
				$this->Assign("etr_no",$_POST['etr_no'],"noempty",
				"".$this->nullmessage);
			}elseif($_POST['etr_no']<=0){

				$this->Assign("etr_no",'',"noempty","It Should be greater than 0");
			}

			if($_POST['etr_months']==''){

				$this->Assign("etr_months",$_POST['etr_months'],"noempty",
				"".$this->nullmessage);

			}elseif($_POST['etr_months']<=0){

				$this->Assign("etr_months",'',"noempty","It Should be greater than 0");
			}

		}else{

			// $this->Assign("inv_type",$_POST['inv_type'],"noempty/nostring/nospecial",
			// "".$this->nullmessage.
			// "/".$this->numbermessage.
			// "/".$this->spcharmessage);

			$this->Assign("face_value",$_POST['face_value'],"noempty/nostring/nospecial'.'","".$this->nullmessage."/"."Face Value -".$this->numbermessage."/"."Face Value -".$this->spcharmessage);

			if($_POST['invoicefile'] =='' && $_FILES['file_invoice']['tmp_name'] == ""){
				$this->Assign("invoicefile",$_POST['invoicefile'],"noempty","".$this->nullmessage);
			}

			$this->Assign("po",$_POST['po'],"noempty","".$this->nullmessage);

			// $this->Assign("invoice_no",$_POST['invoice_no'],"noempty","".$this->nullmessage);

			if($_POST['invoice_no']==''){

				$this->Assign("invoice_no",$_POST['invoice_no'],"noempty","".$this->nullmessage);

			}else{

				$pos = strpos($_POST['invoice_no'], '0');

				if($pos=='0' && is_numeric($pos)){

					$this->Assign("invoice_no","","noempty","0 not allowed for first digit on Invoice No, remove and re-enter!");


				}else{
					$qry 	= new Bin_Query();
					$sql 	= "SELECT m.invoice_no FROM `invoice_master` m WHERE m.invoice_no='".trim($_POST['invoice_no'])."' && m.invoice_id!='".$_REQUEST['id']."'  && m.user_id='".$_SESSION['user']['userid']."' ";
					$qry->executeQuery($sql);
					if($qry->totrows>0){

						$this->Assign("invoice_no","","noempty","This invoice number has already been traded. Enter a new, previously untraded invoice!");

					}
				}

			}

		}



		//$this->Assign("face_value",$_POST['face_value'],"noempty","Face Value -".$this->nullmessage);

		$this->Assign("country_id",$_POST['country_id'],"noempty/nostring/nospecial",
			"".$this->nullmessage.
			"/".$this->numbermessage.
			"/".$this->spcharmessage);

		if($_POST['payment']==''){
			$this->Assign("payment",$_POST['payment'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->numbermessage.
				"/".$this->spcharmessage);
		}elseif($_POST['payment']<=0){

			$this->Assign("payment",'',"noempty","It Should be greater than 0");
		}


		if($sales_type1!='4'){

			$this->Assign("invoice_date",$_POST['invoice_date'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->numbermessage.
				"/".$this->spcharmessage);

			$this->Assign("invoice_date",$_POST['invoice_month'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->numbermessage.
				"/".$this->spcharmessage);

			$this->Assign("invoice_date",$_POST['invoice_year'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->numbermessage.
				"/".$this->spcharmessage);

			$dates 		= $_POST['invoice_year']."-".$_POST['invoice_month']."-".$_POST['ex_date'];
			$query			= new Bin_Query();
			$sql 			= " SELECT DATEDIFF('".$dates."',NOW()) as day ";
			$query->executeQuery($sql);
			$apprtime 		= $query->records;

			if($apprtime[0]['day'] < 0){
				$this->Assign("invoice_date","","noempty","Date & Time should be Greater than Current Date & Time");

			}


			$this->Assign("ex_date",$_POST['ex_date'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->numbermessage.
				"/".$this->spcharmessage);

			$this->Assign("ex_date",$_POST['ex_month'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->numbermessage.
				"/".$this->spcharmessage);

			$this->Assign("ex_date",$_POST['ex_year'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->numbermessage.
				"/".$this->spcharmessage);

			$dates 		= $_POST['ex_year']."-".$_POST['ex_month']."-".$_POST['ex_date'];
			$query			= new Bin_Query();
			$sql 			= " SELECT DATEDIFF('".$dates."',NOW()) as day ";
			$query->executeQuery($sql);
			$time 		= $query->records;

			if($time[0]['day'] < 0){
				$this->Assign("ex_date","","noempty","Date & Time should be Greater than Current Date & Time");

			}

			$dates 		= $_POST['tr_year']."-".$_POST['tr_month']."-".$_POST['tr_date']." ".$_POST['hours'].":".$_POST['mins'].":00";
			$query			= new Bin_Query();
			$sql 			= " SELECT DATEDIFF('".$dates."',NOW()) as day , TIMEDIFF('".$dates."',NOW()) as mins";
			$query->executeQuery($sql);
			$time 		= $query->records;

			if($time[0]['day'] <= 0 && substr($time[0]['mins'],0,1) == '-'){
				$this->Assign("tr_date","","noempty","Date & Time should be Greater than Current Date & Time");

			}


			$this->Assign("tr_date",$_POST['tr_date'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->numbermessage.
				"/".$this->spcharmessage);

			$this->Assign("tr_date",$_POST['tr_month'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->numbermessage.
				"/".$this->spcharmessage);

			$this->Assign("tr_date",$_POST['tr_year'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->numbermessage.
				"/".$this->spcharmessage);

			$this->Assign("hours",$_POST['hours'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->nullmessage.
				"/".$this->spcharmessage);

			$this->Assign("mins",$_POST['mins'],"noempty/nostring/nospecial",
				"".$this->nullmessage.
				"/".$this->nullmessage.
				"/".$this->spcharmessage);

		/*$this->Assign("ac_date",$_POST['ac_date'],"noempty/nostring/nospecial",
			"".$this->nullmessage.
			"/".$this->numbermessage.
			"/".$this->spcharmessage);

		$this->Assign("ac_date",$_POST['ac_month'],"noempty/nostring/nospecial",
			"".$this->nullmessage.
			"/".$this->numbermessage.
			"/".$this->spcharmessage);

		$this->Assign("ac_date",$_POST['ac_year'],"noempty/nostring/nospecial",
			"".$this->nullmessage.
			"/".$this->numbermessage.
			"/".$this->spcharmessage);*/

		}

		/*$this->Assign("po",$_POST['po'],"noempty",
			"".$this->nullmessage);

		if($_POST['invoicefile'] =='')
			$this->Assign("invoicefile",$_POST['invoicefile'],"noempty","".$this->nullmessage);*/

		/*$mime = array('application/force-download','application/msexcel','application/x-ms-download','application/vnd.ms-excel','application/octet-stream','application/excel','application/x-excel','application/x-msexcel','application/vnd.ms-excel.sheet.macroEnabled.12','application/vnd.ms-excel.template.macroEnabled.12','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/pdf','application/x-pdf',
									'application/x-bzpdf',
									'application/x-gzpdf');*/

		$mime = array('application/force-download','application/pdf','application/x-pdf',
									'application/x-bzpdf',
									'application/x-gzpdf');


		//UPload File Check
        foreach($_FILES as $file)
		{

			if($file['error'] == 0)
			{
				$type = $file['type'];
				if($file['size'] <= MAX_UPLOAD_DOCUMENT_SIZE)
				{
					if(!in_array($type, $mime))
					{
						$message = "Invoice upload that creates an ETR can only be in PDF format";
						$this->Assign("invoicefile",'',"noempty",''.$message);
					}
				}
				else
				{
					$size_mes = "Invoice upload that creates an ETR can only be in PDF format and size should be less than 4MB";
					$this->Assign("invoicefile","","noempty",''.$size_mes);
				}
			}
		}


//		$qry 					= new Bin_Query();
//		$sql 					= "SELECT organisation_reference_id FROM organisation_details WHERE user_id='".$_SESSION['user']['userid']."' LIMIT 1 ";
//		$qry->executeQuery($sql);
//		$organisation_reference_id = $qry->records[0]['organisation_reference_id'];

//		$uploadfile 			= array('file_invoice','file_support','file_po');
//
//			foreach($uploadfile as $key){
//
//				//Upload PDF FIle
//				$file = $key;
//				if($_FILES[$key]['tmp_name'] !=''){
//
//					if($file=='file_invoice'){
//						$upload_file = 'invoicefile';
//					}elseif($file=='file_po'){
//						$upload_file = 'pofile';
//					}elseif($file=='file_support'){
//						$upload_file = 'supportfile';
//					}
//
//
//					$user_id   	= $_SESSION['user']['userid'];
//					$exp 		= explode('_',$key);
//					$name 		= $user_id;
//					$ref_id 	= $organisation_reference_id;
//					$dir 		= "../documents/debtor/".$name; //Creating Folder W.r.t Debtor Name and Trader Id
//
//					if(!is_dir($dir)){
//						mkdir($dir, 0777);//Folder Path assigning
//					}
//
//					$type 		= $_FILES[$file]['type'];
//
//					chmod($dir, 0777);  //Folder Permission assigning
//
//					if(!is_dir('../documents/debtor/'.$name."/".date('Y'))){
//						mkdir('../documents/debtor/'.$name."/".date('Y'), 0777);
//					}
//
//					if(!is_dir('../documents/debtor/'.$name."/".date('Y').'/'.date('m'))){
//						mkdir('../documents/debtor/'.$name."/".date('Y').'/'.date('m'), 0777);
//					}
//
//					if(!is_dir('../documents/debtor/'.$name."/".date('Y').'/'.date('m').'/'.date('d'))){
//						mkdir('../documents/debtor/'.$name."/".date('Y').'/'.date('m').'/'.date('d'), 0777);
//					}
//
//					$file_date_dir = date('Y').'/'.date('m').'/'.date('d');
//
//					//File Path assigning
//					$path 		= pathinfo($_FILES[$file]["name"]);
//					$file_name 	= $ref_id.'_'.$key."_".time().".".$path['extension'];
//					$dir_path 	= $dir."/".$file_date_dir."/".$file_name;
//
//					$ext = pathinfo($_FILES[$file]['name'], PATHINFO_EXTENSION);
//
//					if($_FILES[$tmp]['size'] <= 419430400)
//					{
//						if(!in_array($type, $mime))
//						{
//
//							$this->Assign($upload_file,'',"noempty","Only PDF documents can be attached.  Please attach a PDF");
//
//						}elseif($ext =='pdf' || $ext =='PDF'){
//
//
//							// include_once('../include/pdf_parser_check.php');
//							//include_once('classes/Lib/PDF/pdf_parser_check.php');
//
//
//							//$ob = new pdf_parsers($_FILES[$file]['tmp_name']);
//
//
//							//if($ob->error !='1'){
//
//
//								//$this->Assign($upload_file,'',"noempty","This document probably uses a compression technique which is not supported");
//
//							//}else{
//
//								// IT is Good to GO
//								move_uploaded_file($_FILES[$file]["tmp_name"],$dir_path);
//								chmod($dir."/".$file_name, 0777); //File Permission assigning
//
//								$_SESSION[$upload_file] = $name."/".$file_date_dir."/".$file_name;
//								// echo $name."/".$file_name;
//								// exit;
//							//}
//
//						}/*elseif(!empty($_FILES[$file]["tmp_name"])){
//
//
//								move_uploaded_file($_FILES[$file]["tmp_name"],$dir_path);
//								chmod($dir."/".$file_name, 0777); //File Permission assigning
//
//								$_SESSION[$upload_file] = $name."/".$file_date_dir."/".$file_name;
//								// echo $name."/".$file_name;
//								// exit;
//
//						}*/
//						else{
//
//							$this->Assign($upload_file,'',"noempty","Invoice upload that creates an ETR can only be in PDF format");
//						}
//					}
//					else{
//
//						$this->Assign($upload_file,'',"noempty","File Upload Error, Please Try Again");
//
//					}
//				}
//			}


			if(!isset($_SESSION['invoicefile'])){

				$_SESSION['invoicefile'] = $_POST['invoicefile'];
			}

			if(!isset($_SESSION['supportfile'])){

				$_SESSION['supportfile'] = $_POST['supportfile'];
			}

			if(!isset($_SESSION['pofile'])){

				$_SESSION['pofile'] = $_POST['pofile'];
			}



		$this->Assign("sales_type",$_POST['sales_type'],"noempty",
			"".$this->nullmessage);

		$sales_type=$_POST['sales_type'];
		$sales_arr=explode("-",$sales_type);
		$fieldSet=$sales_arr[1];

		if($fieldSet=="model1")
		{
			$this->Assign("purchase_price",$_POST['purchase_price'],"noempty",
			"".$this->nullmessage);
			if($_POST['buyout']=="1")
			{
				$this->Assign("buyout_price",$_POST['buyout_price'],"noempty",
				"".$this->nullmessage);
			}
		}
		else if($fieldSet=="model2")
		{
			$this->Assign("discount_price",$_POST['discount_price'],"noempty",
			"".$this->nullmessage);

			if($_POST['buyout']=="1")
			{

				$this->Assign("buyout_discount_price",$_POST['buyout_discount_price'],"noempty",
			"".$this->nullmessage);
			}
		}




		// $this->Assign("ack_notice",$_POST['ack_notice'],"noempty",
		// 	"0");

		// $this->Assign("closing",$_POST['closing'],"noempty",
		// 	"".$this->nullmessage);


		// $this->PerformValidation('index.php?do=editmydraft&id='.$_REQUEST['id']);

		if($_REQUEST['do']=='saverejecttrade')
		{
			$this->PerformValidation('index.php?do=editrejectedetr&id='.$_REQUEST['id']);

		}else{
			$this->PerformValidation("index.php?do=editmydraft&id=".$_REQUEST['id']);
		}
	}


	//Validates Open Trade Form
	function savetraderValidate()
    {
        $query            = new Bin_Query();
        $query->executeQuery(" SELECT dm.*
                               FROM `debtors_detail` as d, `debtors_master` as dm, `debtor_relation` as r  
                               WHERE r.trader_id ='".$_SESSION['user']['userid']."' && r.debtor_id = '".trim($_POST['debtor_id'])."' && r.status IN (1,5,6,7,8) && d.debtor_id = r.debtor_id && d.parent_id != 0  && dm.debtor_master_id = d.parent_id  
                               limit 1 ");
        $debtor= $query->records;

        if (count($debtor)==0)
        {
            $this->Assign("debtor_id",$_POST['debtor_id'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
            $this->Assign("debtor_id",$_POST['debtor_id'],"nonumber","Counterparty is Not Available");

            if($_REQUEST['do']=='save_instalment_etr')
                $this->PerformValidation('index.php?do=instalment_etr');
            else
                $this->PerformValidation('index.php?do=opentrade');
        }

        $this->Assign("sales_type",$_POST['sales_type'],"noempty","".$this->nullmessage);

        $sales_type=$_POST['sales_type'];
        $sales_arr=explode("-",$sales_type);
        $fieldSet=$sales_arr[1];
        $sales_type1= $sales_arr[0];

		if($fieldSet=="model1")
		{
            if ($debtor[0]['type']=='debtor')
            {
                $this->Assign("purchase_price",$_POST['purchase_price'],"noempty","".$this->nullmessage);
            }

			if($_POST['buyout']=="1")
			{
				$this->Assign("buyout_price",$_POST['buyout_price'],"noempty","".$this->nullmessage);
			}
		}
		else if($fieldSet=="model2" || $fieldSet=="model3")
		{
            if ($debtor[0]['type']=='debtor')
            {
                if($_POST['discount_price']=='')
                {
                    $this->Assign("discount_price",$_POST['discount_price'],"noempty","".$this->nullmessage);
                }
                elseif($_POST['discount_price']<=0)
                {
                    $this->Assign("discount_price",'',"noempty","It Should be greater than 0");
                }
            }

			if($_POST['buyout']=="1")
			{
				if($_POST['buyout_discount_price']=='')
                {
					$this->Assign("buyout_discount_price",$_POST['buyout_discount_price'],"noempty","".$this->nullmessage);
				}
                elseif($_POST['buyout_discount_price']<=0)
                {
					$this->Assign("buyout_discount_price",'',"noempty","It Should be greater than 0");
				}
			}
		}

		if($sales_type=="4-model2")
		{
			if($_POST['etr_face_value']=='')
            {
				$this->Assign("etr_face_value",$_POST['etr_face_value'],"noempty/nostring","".$this->nullmessage."/".$this->numbermessage);
			}
            elseif($_POST['etr_face_value']<=0)
            {
				$this->Assign("etr_face_value",'',"noempty","It Should be greater than 0");
			}
            else
            {
				if(!$this->validateSpecialChar($_POST['etr_face_value']))
                {
					$this->Assign("etr_face_value",'',"noempty",$this->spcharmessage);
				}
			}

			$qry 	= new Bin_Query();
			$sql 	= "SELECT type_id FROM `sales_types` WHERE status='1' AND (type_id='2' OR type_id='3') ORDER BY type_id ASC ";
			$qry->executeQuery($sql);

			if($qry->totrows>0)
            {
			    $this->Assign("etr_type",$_POST['etr_type'],"noempty/nostring","".$this->nullmessage."/".$this->numbermessage);
			}

			if($_POST['etr_no']=='')
            {
				$this->Assign("etr_no",$_POST['etr_no'],"noempty","".$this->nullmessage);
			}
            elseif($_POST['etr_no']<=0)
            {
				$this->Assign("etr_no",'',"noempty","It Should be greater than 0");
			}

			if($_POST['etr_months']=='')
            {
				$this->Assign("etr_months",$_POST['etr_months'],"noempty","".$this->nullmessage);
			}
            elseif($_POST['etr_months']<=0)
            {
				$this->Assign("etr_months",'',"noempty","It Should be greater than 0");
			}
		}
        elseif($sales_type=="5-model3")
		{
			if($_POST['etr_face_value']=='')
            {
				$this->Assign("etr_face_value",$_POST['etr_face_value'],"noempty/nostring","".$this->nullmessage."/".$this->numbermessage);
			}
            elseif($_POST['etr_face_value']<=0)
            {
				$this->Assign("etr_face_value",'',"noempty","It Should be greater than 0");
			}
            else
            {
				if(!$this->validateSpecialChar($_POST['etr_face_value']))
                {
					$this->Assign("etr_face_value",'',"noempty",$this->spcharmessage);
				}
			}

			$qry 	= new Bin_Query();
			$sql 	= "SELECT type_id FROM `sales_types` WHERE status='1' AND (type_id='2' OR type_id='3') ORDER BY type_id ASC ";
			$qry->executeQuery($sql);

			if($qry->totrows>0)
            {
			    $this->Assign("etr_type",$_POST['etr_type'],"noempty/nostring","".$this->nullmessage."/".$this->numbermessage);
			}

			if($_POST['etr_no']=='')
            {
				$this->Assign("etr_no",$_POST['etr_no'],"noempty","".$this->nullmessage);
			}
            elseif($_POST['etr_no']<=0)
            {
				$this->Assign("etr_no",'',"noempty","It Should be greater than 0");
			}

			if($_POST['no_of_instalments']=='')
            {
				$this->Assign("no_of_instalments",$_POST['no_of_instalments'],"noempty","".$this->nullmessage);
			}
            elseif($_POST['no_of_instalments']<=0)
            {
				$this->Assign("no_of_instalments",'',"noempty","It Should be greater than 0");
			}

			if($_POST['payments_remaining']=='')
            {
				$this->Assign("payments_remaining",$_POST['payments_remaining'],"noempty","".$this->nullmessage);
			}
            elseif($_POST['payments_remaining']<=0)
            {
				$this->Assign("payments_remaining",'',"noempty","It Should be greater than 0");
			}
		}
        else
        {
			$this->Assign("etr_face_value",$_POST['etr_face_value'],"noempty/nostring/nospecial'.'","".$this->nullmessage."/"."Face Value -".$this->numbermessage."/"."Face Value -".$this->spcharmessage);

			if($_POST['invoicefile'] =='' && $_FILES['file_invoice']['tmp_name'] == "")
            {
				$this->Assign("invoicefile",$_POST['invoicefile'],"noempty","".$this->nullmessage);
			}

			$this->Assign("po",$_POST['po'],"noempty","".$this->nullmessage);

			if($_POST['invoice_no']=='')
            {
				$this->Assign("invoice_no",$_POST['invoice_no'],"noempty","".$this->nullmessage);
			}
            else
            {
				$pos = strpos($_POST['invoice_no'], '0');

				if($pos=='0' && is_numeric($pos))
                {
                    $this->Assign("invoice_no","","noempty","0 not allowed for first digit on Invoice No, remove and re-enter!");
				}
                else
                {
					$qry 	= new Bin_Query();
					$sql 	= "SELECT m.invoice_no FROM `invoice_master` m WHERE m.invoice_no='".trim($_POST['invoice_no'])."'  && m.user_id='".$_SESSION['user']['userid']."' ";
					$qry->executeQuery($sql);
					if($qry->totrows>0)
                    {
						$this->Assign("invoice_no","","noempty","This invoice number has already been traded. Enter a new, previously untraded invoice!");
					}
				}
			}
		}

		$qry 			= new Bin_Query();
		$sql 			= "SELECT agreed_rate FROM `organisation_details` WHERE user_id='".$_SESSION['user']['userid']."' ";
		$qry->executeQuery($sql);
		$agreed_rate 	= $qry->records[0]['agreed_rate'];

		if($fieldSet=="model1")
		{
            if ($debtor[0]['type']=='debtor')
            {
                if($_POST['purchase_price']!='')
                {
                    if($_POST['purchase_price'] < $agreed_rate)
                    {
                        $this->Assign("purchase_price",$_POST['purchase_price'],"nonumber","The Outright Purchase price you are offering is lower than agreed rate. Increase it please");
                    }
                }

                if($_POST['purchase_price'] !=''  && $_POST['etr_face_value'] != '')
                {
                    $offer = ($debtor[0]['debtor_min_offers'] / 100 ) * $_POST['etr_face_value'];

                    if($_POST['purchase_price'] < $offer )
                    {
                        $this->Assign("purchase_price",$_POST['purchase_price'],"nonumber","The Outright Purchase price you are offering is too low. Increase it please");
                    }
                }
            }

			if($_POST['buyout_price'] != '')
            {
				if($_POST['buyout_price'] < $agreed_rate)
                    $this->Assign("buyout_price",$_POST['buyout_price'],"nonumber","The Outright Purchase price you are offering is lower than agreed rate. Increase it please");
			}

			if($_POST['buyout_price'] !=''   && $_POST['etr_face_value'] != '')
            {
				$offer = ($debtor[0]['debtor_min_offers'] / 100 ) * $_POST['etr_face_value'];

				if($_POST['buyout_price'] < $offer )
                {
					$this->Assign("buyout_price",$_POST['buyout_price'],"nonumber","The Outright Purchase price you are offering is too low. Increase it please");
				}
			}
		}
        elseif($fieldSet=="model2")
        {
        	// temporary disable
            if(isset($_POST['buyout']) and false)
            {
                if ($debtor[0]['type']=='debtor')
                {
                    if($_POST['discount_price']<=0)
                    {
                        $this->Assign("discount_price",'',"noempty","It Should be greater than 0");
                    }

                    if($_POST['discount_price'] !='' && $_POST['discount_price'] < $agreed_rate )
                    {
                        $this->Assign("discount_price",$_POST['discount_price'],"nonumber","The Minimum Agreed Rate  permitted is currently ".$agreed_rate."% (where ".$agreed_rate." is the Minimum Offer percentage )");
                    }

                    if($_POST['discount_price'] !='' && $_POST['discount_price'] < $debtor[0]['debtor_min_offers'] )
                    {
                        $this->Assign("discount_price",$_POST['discount_price'],"nonumber","The Minimum Discount Percentage permitted is currently ".$debtor[0]['debtor_min_offers']."%  (where ".$debtor[0]['debtor_min_offers']." is the Minimum Offer percentage  figure for the specific Master Debtor)");
                    }
                }

				if($_POST['buyout_discount_price']<=0)
                {
					$this->Assign("buyout_discount_price",'',"noempty","It Should be greater than 0");
				}

				if($_POST['buyout_discount_price'] !='' && $_POST['buyout_discount_price'] < $agreed_rate )
                {
					$this->Assign("buyout_discount_price",$_POST['buyout_discount_price'],"nonumber","The Minimum Agreed Rate  permitted is currently ".$agreed_rate."%  (where ".$agreed_rate." is the Minimum Offer percentage )");
				}

				if($_POST['buyout_discount_price'] !='' && $_POST['buyout_discount_price'] < $debtor[0]['debtor_min_offers'] )
                {
                    $this->Assign("buyout_discount_price",$_POST['buyout_discount_price'],"nonumber","The Minimum Discount  Percentage permitted is currently ".$debtor[0]['debtor_min_offers']."%  (where ".$debtor[0]['debtor_min_offers']." is the Minimum Offer  Percentage figure for the specific Master Debtor)");
				}
			}
		}

        if($sales_type1!='5')
        {
            $field_name=($debtor[0]['type']=='debtor')?'payment':'payment_discount';

            if($_POST[$field_name]=='')
            {
                $this->Assign($field_name,$_POST[$field_name],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
            }
            elseif($_POST[$field_name]<=0 AND $field_name=='payment')
            {
                $this->Assign($field_name,'',"noempty","It Should be greater than 0");
            }
        }

		if($sales_type1!='4' && $sales_type1!='5')
        {
		    $this->Assign("ex_date",$_POST['ex_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		    $this->Assign("ex_date",$_POST['ex_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		    $this->Assign("ex_date",$_POST['ex_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		    $dates 		= $_POST['ex_year']."-".$_POST['ex_month']."-".$_POST['ex_date'];
		    $query			= new Bin_Query();
		    $sql 			= " SELECT DATEDIFF('".$dates."',NOW()) as day ";
		    $query->executeQuery($sql);
		    $time 		= $query->records;

		    if($time[0]['day'] < 0)
            {
			    $this->Assign("ex_date","","noempty","Date & Time should be Greater than Current Data & Time");
		    }

		    $this->Assign("invoice_date",$_POST['invoice_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		    $this->Assign("invoice_date",$_POST['invoice_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		    $this->Assign("invoice_date",$_POST['invoice_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);


		    $dates 		= $_POST['invoice_year']."-".$_POST['invoice_month']."-".$_POST['invoice_date'];
		    $query			= new Bin_Query();
		    $sql 			= " SELECT DATEDIFF('".$dates."',NOW()) as day ";
		    $query->executeQuery($sql);
		    $apprtime 		= $query->records;

		    if($apprtime[0]['day'] < 0)
            {
			    $this->Assign("invoice_date","","noempty","Date & Time should be Greater than Current Data & Time");
		    }

		    $dates 		= $_POST['tr_year']."-".$_POST['tr_month']."-".$_POST['tr_date']." ".$_POST['hours'].":".$_POST['mins'].":00";
		    $query			= new Bin_Query();
		    $sql 			= " SELECT DATEDIFF('".$dates."',NOW()) as day , TIMEDIFF('".$dates."',NOW()) as mins";
		    $query->executeQuery($sql);
		    $time 		= $query->records;

		    if($time[0]['day'] <= 0 && substr($time[0]['mins'],0,1) == '-')
            {
			    $this->Assign("tr_date","","noempty","Date & Time should be Greater than Current Date & Time");
		    }

		    $this->Assign("tr_date",$_POST['tr_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
		    $this->Assign("tr_date",$_POST['tr_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
		    $this->Assign("tr_date",$_POST['tr_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		    $this->Assign("hours",$_POST['hours'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->nullmessage."/".$this->spcharmessage);
		    $this->Assign("mins",$_POST['mins'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->nullmessage."/".$this->spcharmessage);
		}

		$mime = array('application/force-download','application/pdf','application/x-pdf',
									'application/x-bzpdf',
									'application/x-gzpdf');
		//UPlaod File Check
		$dcnt =  count($_FILES);
		$tmp = 'file_invoice';
		for($d=1;$d<=$dcnt;$d++)
		{
			if($_FILES[$tmp]['tmp_name'] != "")
			{
				$type = $_FILES[$tmp]['type'];
				if($_FILES[$tmp]['size'] <= 419430400)
				{
					if(!in_array($type, $mime))
					{
						$message = "Invoice upload that creates an ETR can only be in PDF format";
						$this->Assign("invoicefile",'',"noempty",''.$message);
					}
				}
				else
				{
					$size_mes = "Invoice upload that creates an ETR can only be in PDF format and size should be less than 4MB";
					$this->Assign("invoicefile","","noempty",''.$size_mes);
				}
			}
			if($d==1)$tmp = 'file_support'; if($d==2)$tmp = 'file_po';
		}


//		$qry 					= new Bin_Query();
//		$sql 					= "SELECT organisation_reference_id FROM organisation_details WHERE user_id='".$_SESSION['user']['userid']."' LIMIT 1 ";
//		$qry->executeQuery($sql);
//		$organisation_reference_id = $qry->records[0]['organisation_reference_id'];


//		$uploadfile= array('file_invoice','file_support','file_po');
//
//		foreach($uploadfile as $key)
//        {
//			$file = $key;
//			if($_FILES[$key]['tmp_name'] !=''){
//
//				if($file=='file_invoice'){
//					$upload_file = 'invoicefile';
//				}elseif($file=='file_po'){
//					$upload_file = 'pofile';
//				}elseif($file=='file_support'){
//					$upload_file = 'supportfile';
//				}
//
//				$exp 		= explode('_',$key);
//				$name 		= $_SESSION['user']['userid'];
//				$ref_id 	= $organisation_reference_id;
//
//				$dir 		= "../documents/debtor/".$name; //Creating Folder W.r.t Debtor Name and Trader Id
//
//				if(!is_dir($dir)){
//					mkdir($dir, 0777);//Folder Path assigning
//				}
//
//				$type 		= $_FILES[$file]['type'];
//
//				chmod($dir, 0777);  //Folder Permission assigning
//
//				if(!is_dir('../documents/debtor/'.$name."/".date('Y'))){
//					mkdir('../documents/debtor/'.$name."/".date('Y'), 0777);
//				}
//
//				if(!is_dir('../documents/debtor/'.$name."/".date('Y').'/'.date('m'))){
//					mkdir('../documents/debtor/'.$name."/".date('Y').'/'.date('m'), 0777);
//				}
//
//				if(!is_dir('../documents/debtor/'.$name."/".date('Y').'/'.date('m').'/'.date('d'))){
//					mkdir('../documents/debtor/'.$name."/".date('Y').'/'.date('m').'/'.date('d'), 0777);
//				}
//
//				$file_date_dir = date('Y').'/'.date('m').'/'.date('d');
//
//				//File Path assigning
//				$path 		= pathinfo($_FILES[$file]["name"]);
//				$file_name 	= $ref_id.'_'.$key."_".time().".".$path['extension'];
//				$dir_path 	= $dir."/".$file_date_dir."/".$file_name;
//
//				$ext = pathinfo($_FILES[$file]['name'], PATHINFO_EXTENSION);
//
//				if($_FILES[$tmp]['size'] <= 419430400)
//				{
//					if(!in_array($type, $mime))
//					{
//                        $this->Assign($upload_file,'',"noempty","Only PDF documents can be attached.  Please attach a PDF");
//					}
//                    elseif($ext =='pdf' || $ext =='PDF')
//                    {
//						move_uploaded_file($_FILES[$file]["tmp_name"],$dir_path);
//						chmod($dir."/".$file_date_dir."/".$file_name, 0777); //File Permission assigning
//
//						$_SESSION[$upload_file] = $name."/".$file_date_dir."/".$file_name;
//					}
//					else
//                    {
//						$this->Assign($upload_file,'',"noempty","Invoice upload that creates an ETR can only be in PDF format");
//					}
//				}
//				else
//                {
//					$this->Assign($upload_file,'',"noempty","File Upload Error, Please Try Again");
//				}
//			}
//		}

		if(!isset($_SESSION['invoicefile']))
        {
			$_SESSION['invoicefile'] = $_POST['invoicefile'];
		}

		if(!isset($_SESSION['supportfile'])){

			$_SESSION['supportfile'] = $_POST['supportfile'];
		}

		if(!isset($_SESSION['pofile'])){

			$_SESSION['pofile'] = $_POST['pofile'];
		}


//		$query=new Bin_Query();
//		$sql 				= " SELECT r.notify FROM `debtor_relation` as r where r.trader_id ='".$_SESSION['user']['userid']."' ".
//							"  && r.debtor_id = '".$_POST['debtor_id']."'  limit 1 ";
//		$query->executeQuery($sql);
//		$debtors 			= $query->records;

		if($_REQUEST['do']=='save_instalment_etr')
			$this->PerformValidation('index.php?do=instalment_etr');
		else
			$this->PerformValidation('index.php?do=opentrade');
	}

	//Validate revolving ETR Upload Form
	function validateRevolvingTrade()
    {
		$this->Assign("inv_type",$_POST['inv_type'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		$this->Assign("debtor_id",$_POST['debtor_id'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

        $query= new Bin_Query();
        if (empty($_REQUEST['debtor_type']))
        {
            $query->executeQuery('SELECT debtors_detail.debtor_id, debtors_detail.type, debtors_detail.currency_id, currencies.currency_code,
       							  IF(od.credebt_facility_type = \'fixed\', IFNULL(debtors_detail.face_value_charge, od.face_value_charge), 0) as face_value_charge,
       							  IFNULL(debtors_detail.ldc_premium, od.ldc_premium) as ldc_premium,
       							  IFNULL(debtors_detail.agent_commission, od.agent_commission) as agent_commission,
								  od.processing_fee,
       							  IF(od.purchase_price>debtors_detail.purchase_price AND debtors_detail.purchase_price>0,debtors_detail.purchase_price, od.purchase_price) as purchase_price,
       							  max_thirty_day_reserve as sell_rate
                                  FROM invoice_master
                                  LEFT JOIN debtors_detail ON debtors_detail.debtor_id = invoice_master.debtor_id
                                  LEFT JOIN currencies ON currencies.currency_id = debtors_detail.currency_id
								  LEFT JOIN debtor_relation dr ON debtors_detail.debtor_id = dr.debtor_id
								  LEFT JOIN organisation_details od ON od.user_id = dr.trader_id
                                  WHERE invoice_id="'.$_POST['debtor_id'].'"');
        }
        elseif($_REQUEST['debtor_type']=='creditor')
        {
            $query->executeQuery('SELECT debtors_detail.debtor_id,debtors_detail.type, debtors_detail.currency_id, currencies.currency_code
                                  FROM debtors_detail
                                  LEFT JOIN currencies ON currencies.currency_id = debtors_detail.currency_id
                                  WHERE debtor_id="'.$_POST['debtor_id'].'"');
        }

        if (count($query->records)==0)
        {
           $this->Assign("debtor_id",$_POST['debtor_id'],"nonumber","Debtor is Not Available");

           if($_REQUEST['do']=='saverevolvingdraft')
           {
               if (empty($_REQUEST['debtor_type'])) {
                   $errors = $this->PerformValidation('service');
                   if ($errors) {
                       exit(json_encode($errors));
                   }
               } else {
                   $this->PerformValidation('index.php?do=editrevolvingdraft&id='.$_REQUEST['id']);
               }
           } else {
               if (empty($_REQUEST['debtor_type'])) {
                   $errors = $this->PerformValidation('service');
                   if ($errors) {
                       exit(json_encode($errors));
                   }
               } else {
                   $this->PerformValidation('index.php?do=creditortrade');
               }
           }
        }

        $debtor=$query->records[0];

		if($_REQUEST['submits'] == 'Submit' AND $debtor['type']=='debtor')
        {
			$invoice_id = trim($_POST['debtor_id']);

			if($invoice_id !='')
            {
				$query->executeQuery("SELECT * 
                                     FROM `invoice_closed` 
                                     where  invoice_id = '".$invoice_id."' 
                                     LIMIT 1 ");
				if(count($query->records) == 0)
                {
					$this->Assign("invoice","","noempty","Until the Revolving ETR is Live on Trade Floor, You cannot Upload the new Invoice");
				}
                else
                {
					$query->executeQuery("SELECT * 
                                          FROM `invoice_master` 
                                          WHERE  root_invoice_id = '".$invoice_id."' && invoice_id != '".$_REQUEST['id']."'  && invoice_status != 3 ");

                    if(count($query->records) > 0)
                    {
						$this->Assign("invoice","","noempty","Until the Revolving ETR is Live on Trade Floor, You cannot Upload the new Invoice");
					}
				}
			}
		}

		if($_POST['face_value']=='')
        {
			$this->Assign("face_value",$_POST['face_value'],"noempty/nostring","".$this->nullmessage."/".$this->numbermessage);
		}
        elseif($_POST['face_value']<=0)
        {
			$this->Assign("face_value",'',"noempty","It Should be greater than 0");
		}
        else
        {
			if(!$this->validateSpecialChar($_POST['face_value']))
            {
                $this->Assign("face_value",'',"noempty",$this->spcharmessage);
			}
		}

        include_once('classes/Model/MUserOrpa.php');
        if ($_POST['orpa_id'] === '0') {
            unset($_POST['orpa_id']);
        }
        if ($_POST['po_no'] === '0') {
            unset($_POST['po_no']);
        }
        $checkOrpaEnabledSql = "SELECT orpa_enabled FROM organisation_details WHERE user_id = " . $_SESSION['user']['userid'];
        $query->executeQuery($checkOrpaEnabledSql);
        $orpaEnabled = (bool)array_get($query->records[0], 'orpa_enabled');
        $orpaModel = new Model_MUserOrpa();
        if ($debtor['type'] == 'debtor') {
            $isOrpa = (bool)$orpaModel->getOrpaForDEtr($debtor['debtor_id']);
        } else {
            $isOrpa = (bool)$orpaModel->getOrpaForCEtr($_SESSION['user']['userid']);
        }
        if (!isset($_POST['orpa_id']) and $isOrpa and $orpaEnabled) {
            $this->Assign('orpa_id', '', 'noempty', $this->nullmessage);
        }
		
        if ($debtor['type']=='debtor')
        {
            if (!empty($_POST['orpa_id']) and !empty($_POST['face_value']) and !empty($debtor['currency_id'])) {
                $orpaModel = new Model_MUserOrpa();
                if (!$orpaModel->isOriginatorsOrpa($_POST['orpa_id'], $_SESSION['user']['userid'])
                    or !$orpaModel->isDebtorInOrpa($_POST['orpa_id'], $debtor['debtor_id'])
                ) {
                    $this->Assign('orpa_id', '', 'noempty', $this->allowedoetrmessage);
                }
                if(!empty($_POST['po_no'])){
                    $po = $orpaModel->getPoByOrpaId($_POST['orpa_id'], $debtor['debtor_id']);
                    $currentPo = null;
                    foreach ($po as $item) {
                        if ($item['id'] == $_POST['po_no']) {
                            $currentPo = $item;
                            break;
                        }
                    }
                    if ($currentPo) {
                        $availableAmount = sprintf("%01.2f", $currentPo['amount'] - $currentPo['traded_amount']);
                        if ($_POST['face_value'] > $availableAmount) {
                            $this->Assign('po_no', '', 'noempty', $this->allowedoetrfordetrmessage);
                        }
                    }
				}
            }

		    if($_POST['payment']=='')
            {
			    $this->Assign("payment",$_POST['payment'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
		    }
            elseif($_POST['payment']<=0)
            {
			    $this->Assign("payment",'',"noempty","It Should be greater than 0");
            } else {
                include_once("admin/classes/Model/MSiteSetting.php");

                $siteSettings = new Model_MSiteSetting();
                $settings = $siteSettings->ViewSiteSetting();
                if ($_POST['payment'] > (int)$settings['max_edso']) {
                    $this->Assign("payment", '', "noempty", "The value must not exceed  " . $settings['max_edso'] . "!");
                }
            }

            $this->Assign("ex_date",$_POST['ex_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		    $this->Assign("ex_date",$_POST['ex_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		    $this->Assign("ex_date",$_POST['ex_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

			if (isset($_POST['etr_deliver_to_debtor_contact'])) {
				$query->executeQuery("SELECT * FROM debtor_contacts
				WHERE id = " . (int)$_POST['etr_deliver_to_debtor_contact'] . " AND debtor_id = " . (int)$debtor['debtor_id']);
				if (count($query->records) == 0) {
					$this->Assign("etr_deliver_to_debtor_contact", "", "noempty", "Incorrect Contact");
				}
			}
		}
		else
        {
            if (!empty($_POST['orpa_id']) and !empty($_POST['face_value']) and !empty($debtor['currency_id']))
            {
                $orpaModel = new Model_MUserOrpa();
                if(!$orpaModel->isOriginatorsOrpa($_POST['orpa_id'], $_SESSION['user']['userid']))
                {
                    $this->Assign('orpa_id', '', 'noempty', $this->allowedoetrmessage);
                }
                elseif (empty($_POST['unscheduled_cetr']) and !$orpaModel->isAllowedCEtrForOrpa($_POST['orpa_id'], $_POST['face_value'], $debtor['currency_id']))
                {
                    $this->Assign('orpa_id', '', 'noempty', $this->oEtrLimitError);
                    $this->Assign('unscheduled_cetr', '', 'noempty', $this->nullmessage);
                }
                
                $query->executeQuery('SELECT SUM(amount) as amount
                                    FROM (
                                        SELECT SUM(manual_transactions.amount * IF(manual_transactions.currency_id=1,1,currency_rates.currency_rate)) as amount, "manual_transactions" as `type`
                                        FROM manual_transactions
                                        LEFT JOIN currency_rates ON currency_rates.currency_id = manual_transactions.currency_id AND currency_rates.currency_date = CURDATE()
                                        WHERE manual_transactions.transaction_type='.ORIGINATOR_DEPOSIT.' AND manual_transactions.orpa_id='.(int)$_POST['orpa_id'].' AND manual_transactions.originator_id='.$_SESSION['user']['userid'].' AND manual_transactions.status=1

                                        UNION ALL

                                        SELECT -SUM(if(invoice_master.vat_included=\'1\', invoice_master.face_value*(100-' . Model_MSiteSetting::getSetting('vat_tax_percentage', 0) . ')/100, invoice_master.face_value) * IF(debtors_detail.currency_id=1,1,currency_rates.currency_rate) * (orpa.deposit_percent/100) ) as amount, "invoice_master" as `type`
                                        FROM invoice_master
                                        LEFT JOIN debtors_detail ON debtors_detail.debtor_id = invoice_master.debtor_id
                                        LEFT JOIN currency_rates ON currency_rates.currency_id = debtors_detail.currency_id AND currency_rates.currency_date = CURDATE()
                                        LEFT JOIN orpa ON orpa.id  = '.(int)$_POST['orpa_id'].'
                                        WHERE invoice_master.orpa_id='.(int)$_POST['orpa_id'].' AND debtors_detail.`type`="creditor" AND invoice_master.manual_transaction_id=0 AND invoice_master.user_id='.$_SESSION['user']['userid'].' AND invoice_master.root_invoice_id>0 AND invoice_master.log_status IN (0,1) AND invoice_master.draft=0

                                        UNION ALL

                                        SELECT -'.(float)$_POST['face_value']*((empty($_POST['vat_included']))?1:(100-Model_MSiteSetting::getSetting('vat_tax_percentage'))/100).' * IF(debtors_detail.currency_id=1,1,currency_rates.currency_rate) * (orpa.deposit_percent/100)  as amount, "real" as `type`
                                        FROM debtors_detail
                                        LEFT JOIN currency_rates ON currency_rates.currency_id = debtors_detail.currency_id AND currency_rates.currency_date = CURDATE()
                                        LEFT JOIN orpa ON orpa.id  = '.(int)$_POST['orpa_id'].'
                                        WHERE debtors_detail.debtor_id='.$debtor['debtor_id'].'
                                     ) AS T');
                
                $avaliable=$query->records[0]['amount'];
                
                if ($avaliable<0)
                {
                    $this->Assign('orpa_id', '', 'noempty', 'Insufficient amount of Deposit available. Please transfer equivalent of EUR '.number_format(abs($avaliable),2).' before submiting this c-ETR');
                }
            }
            $this->Assign("payment_discount", $_POST['payment_discount'], "noempty/check_payment_discount_ogui", $this->nullmessage . '/' . $this->checkpaymentdiscountogui);
        }

        $dates = $_POST['ex_year']."-".$_POST['ex_month']."-".$_POST['ex_date'];

		$this->Assign("invoice_date",$_POST['invoice_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
		$this->Assign("invoice_date",$_POST['invoice_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		$this->Assign("invoice_date",$_POST['invoice_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);

		$dates= $_POST['invoice_year']."-".$_POST['invoice_month']."-".$_POST['invoice_date'];
		$query->executeQuery(" SELECT DATEDIFF('".$dates."',NOW()) as day ");
		$apprtime= $query->records;

		if($apprtime[0]['day'] > 0)
        {
			$this->Assign("invoice_date","","noempty","the Invoice Date cannot be greater than today’s date!  Enter today’s date or a prior date");
		}
        
        if (strtotime($dates)<strtotime(FIRST_TRADE_DATE))
        {
            $this->Assign("invoice_date","","noempty","Invoice Date should be greater than '".FIRST_TRADE_DATE."'");
        }
        
        
		$dates 		= $_POST['ex_year'].$_POST['ex_month'].$_POST['ex_date'];

		$dates1 		= $_POST['invoice_year'].$_POST['invoice_month'].$_POST['invoice_date'];

		if($dates < $dates1)
        {
			$this->Assign("ex_date","","noempty","Expected Date should be greater than Invoice Date");
		}
        
        if (strtotime($_POST['ex_year'].'-'.$_POST['ex_month'].'-'.$_POST['ex_date'])<strtotime(FIRST_TRADE_DATE))
        {
            $this->Assign("ex_date","","noempty","Expected Date should be greater than '".FIRST_TRADE_DATE."'");
        }

        if (!checkdate($_POST['ex_month'], $_POST['ex_date'], $_POST['ex_year'])) {
            $this->Assign("ex_date", "", "noempty", $this->invaliddatemessage);
        }
        if (!checkdate($_POST['invoice_month'], $_POST['invoice_date'], $_POST['invoice_year'])) {
            $this->Assign("invoice_date", "", "noempty", $this->invaliddatemessage);
        }

		$mime = array('application/force-download','application/pdf','application/x-pdf','application/x-bzpdf','application/x-gzpdf');

		if($_POST['invoicefile'] =='' && $_FILES['file_invoice']['tmp_name'] == "")
        {
			$this->Assign("invoicefile",$_POST['invoicefile'],"noempty","".$this->nullmessage);
		}

		$query->executeQuery("SELECT etr_pod_mandatory  
                              FROM organisation_details
                              WHERE  user_id ='".$_SESSION['user']['userid']."' LIMIT 1 ");
		$orgDetails 	= $query->records[0];

        if ($orgDetails['etr_pod_mandatory'] == '1'
            and $_POST['pofile'] == ''
            and $_FILES['file_po']['tmp_name'] == ""
            and ($debtor['type'] == TYPE_CREDITOR
                or ($debtor['type'] == TYPE_DEBTOR and empty($_POST['orpa_id'])))
        )
        {
			$this->Assign("pofile",$_POST['pofile'],"noempty","".$this->nullmessage);
		}


		$query->executeQuery("SELECT organisation_reference_id 
                              FROM organisation_details 
                              WHERE user_id='".$_SESSION['user']['userid']."' 
                              LIMIT 1 ");
		$organisation_reference_id = $query->records[0]['organisation_reference_id'];

		if(!isset($_SESSION['invoicefile']))
        {
			$_SESSION['invoicefile'] = $_POST['invoicefile'];
		}

		if(!isset($_SESSION['supportfile']))
        {
			$_SESSION['supportfile'] = $_POST['supportfile'];
		}

		if(!isset($_SESSION['pofile']))
        {
			$_SESSION['pofile'] = $_POST['pofile'];
		}

        $modelUserOrpa = new Model_MUserOrpa();
        $poNumbers = $modelUserOrpa->getPoNumbersForDebtor($debtor['debtor_id']);
        if ($debtor['type'] == TYPE_CREDITOR or ($debtor['type'] == TYPE_DEBTOR and empty($_POST['orpa_id']))) {
            $this->Assign("po", $_POST['po'], "noempty", "" . $this->nullmessage);
            if (in_array($_POST['po'], $poNumbers)) {
                $this->Assign("po", '', "noempty", $this->existpomessage);
            }
        } else {
            $this->Assign("po", $_POST['po_no'], "noempty", "" . $this->nullmessage);
        }

		if($_POST['invoice_no']=='')
        {
			$this->Assign("invoice_no",$_POST['invoice_no'],"noempty","".$this->nullmessage);
		}
        else
        {
			$pos = strpos($_POST['invoice_no'], '0');

			if($pos=='0' && is_numeric($pos))
            {
				$this->Assign("invoice_no","","noempty","0 not allowed for first digit on Invoice No, remove and re-enter!");
			}
            else
            {
				$qry 	= new Bin_Query();
				if($_REQUEST['do']=='saverevolvingdraft')
                {
					$sql 	= "SELECT m.invoice_no FROM `invoice_master` m WHERE m.invoice_no='".trim($_POST['invoice_no'])."' && m.invoice_id!='".$_REQUEST['id']."' && m.user_id='".$_SESSION['user']['userid']."' ";
				}
                else
                {
					$sql 	= "SELECT m.invoice_no FROM `invoice_master` m WHERE m.invoice_no='".trim($_POST['invoice_no'])."' && m.user_id='".$_SESSION['user']['userid']."' ";
				}
				$qry->executeQuery($sql);
				if($qry->totrows>0)
                {
					$this->Assign("invoice_no","","noempty","This invoice number has already been traded. Enter a new, previously untraded invoice!");
				}
			}
		}

		$tmpArray = array('invoicefile' => 'file_invoice', 'pofile' => 'file_po');
		foreach($tmpArray as $key=>$tmp)
		{
			if($_FILES[$tmp]['tmp_name'] != "")
			{
				$type = $_FILES[$tmp]['type'];
				if($_FILES[$tmp]['size'] <= 419430400)
				{
					if(!in_array($type, $mime) and $key == 'invoicefile')
					{
						$message = "Invoice upload that creates an ETR can only be in PDF format";
						$this->Assign($key,'',"noempty",''.$message);
					}
				}
				else
				{
					$size_mes = "Size should be less than 4MB";
					$this->Assign($key,"","noempty",''.$size_mes);
				}
			}
		}

        /*if (isset($_REQUEST['new_document'])) {
            foreach ($_REQUEST['new_document'] as $key => $value) {
                $this->Assign("new_document[$key][name]", $value['name'], "noempty", $this->nullmessage);
                $this->Assign("new_document[$key][file]", $_FILES['new_document']['name'][$key], "noempty",
                    $this->nullmessage);
                $this->Assign("new_document[$key][amount]", $value['amount'], "noempty", $this->nullmessage);
                $this->Assign("new_document[$key][amount]", $value['amount'], "nostring", $this->numbermessage);
            }
        }*/

        if ($debtor['type'] == 'debtor') {
            Bin_Config::requireAdminModel('MOriginator');

			/*// validate ldc premium amount
			if(!empty($_POST['orpa_id'])){
				$orpa = $orpaModel->getOrpa($_POST['orpa_id']);
				$debtor['purchase_price'] = $orpa['d_etr_purchase_discount'];
			}
			$ldcPremium = floatval($debtor['ldc_premium']);
			$agentCommission = floatval($debtor['agent_commission']);
			$faceValue = floatval($_POST['face_value']);
			$sellRate = floatval($debtor['sell_rate']);
			$purchasePrice = floatval($debtor['purchase_price']);
			$tradeFee = floatval($debtor['processing_fee']);
			$faceValueCharge = floatval($debtor['face_value_charge']);
			$overrideRule = false;
			$issueDate = strtotime($_POST['invoice_year'] . "-" . $_POST['invoice_month'] . "-" . $_POST['invoice_date']) ? new DateTime($_POST['invoice_year'] . "-" . $_POST['invoice_month'] . "-" . $_POST['invoice_date']) : new DateTime();
			$expectedDate = strtotime($_POST['ex_year'] . "-" . $_POST['ex_month'] . "-" . $_POST['ex_date']) ? new DateTime($_POST['ex_year'] . "-" . $_POST['ex_month'] . "-" . $_POST['ex_date']) : new DateTime();
			if (!Model_MTrade::validateLDCPremiumValue($ldcPremium, $agentCommission, $faceValue, $sellRate, $purchasePrice, $tradeFee, $faceValueCharge, $overrideRule, $issueDate, $expectedDate)) {
				$this->Assign('ldc_premium', '', 'noempty', 'The calculated value of LDC premium must not exceed the amount of reserve available for a d-ETR invoice');
			}
			// validate agent commission percent
			if ($agentCommission >= 99
				or ($sellRate * 100 / (100 - $agentCommission)) > 100
				or ($faceValueCharge * 100 / (100 - $agentCommission)) > 100) {
				$this->Assign('ldc_premium', '', 'noempty', 'Calculated Sell Rate can not exceed 100');
			}
			if (!Model_MTrade::validateCommissionValue($ldcPremium, $agentCommission, $faceValue, $sellRate, $purchasePrice, $tradeFee, $faceValueCharge, $overrideRule, $issueDate, $expectedDate)) {
				$this->Assign('ldc_premium', '', 'noempty', ' Commission exceed the difference between the Invoice Face Value minus Purchase Price');
			}*/

            $requestedDocuments = Model_MOriginator::getRequestedDocuments($_SESSION['org_id']);
            foreach ($requestedDocuments as $document) {
                if (empty($_FILES['requested_document']['name'][$document['id']]) and empty($_REQUEST['requested_document'][$document['id']['requested_file']])) {
                    $this->Assign("requested_document", '', 'noempty', $this->requireddocumentmessage);
                }
            }
            if (isset($_REQUEST['requested_document'])) {
                foreach ($_REQUEST['requested_document'] as $key => $value) {
                    if (empty($value['requested_file'])) {
                        $this->Assign("requested_document[$key][file]", $_FILES['requested_document']['name'][$key],
                            "noempty",
                            $this->nullmessage);
                    }
                    $this->Assign("requested_document[$key][amount]", $value['amount'], "nostring",
                        $this->numbermessage);
                }
            }
        }

		if($_REQUEST['do']=='saverevolvingdraft')
        {
            $link=(empty($_REQUEST['debtor_type']))?'editrevolvingdraft':'editcreditordraft';
            if (empty($_REQUEST['debtor_type'])) {
                $errors = $this->PerformValidation('service');
                if ($errors) {
                    exit(json_encode($errors));
                }
            } else {
                $this->PerformValidation('index.php?do='.$link.'&id='.$_REQUEST['id']);
            }
		}
        else
        {
            if (empty($_REQUEST['debtor_type'])) {
                $errors = $this->PerformValidation('service');
                if ($errors) {
                    exit(json_encode($errors));
                }
            } else {
                $this->PerformValidation('index.php?do=creditortrade');
            }
		}
	}

	// * Validates Create Debtor/Creditor Form
    function registrationDebtorValidate() {
		$this->Assign("debtor_name",$_POST['debtor_name'],"noempty",$this->nullmessage);
		$this->Assign("organisation_id",$_POST['organisation_id'],"noempty",$this->nullmessage);
		$this->Assign("debtor_type",$_POST['debtor_type'],"noempty",$this->nullmessage);
		$this->Assign("debtor_crn",trim($_POST['debtor_crn']),"noempty",$this->nullmessage);

		if($_POST['debtor_type']=='creditor')
		{
			$this->Assign("payment_discount",trim($_POST['payment_discount']),
				"noempty/nostring/percentage",
				$this->nullmessage."/".$this->numbermessage."/".$this->maxpercentvaluemessage);

			$this->Assign("bank_name",$_POST['bank_name'],"noempty","".$this->nullmessage);

			if($_POST['iban_number']=='' && $_POST['account_number']=='')
			{
				$this->Assign("iban_number",$_POST['iban_number'],"noempty","Either IBAN Number or Account Number mandatory fields");
			}
			elseif( $_POST['iban_number'] != '' )
			{
				//$tmpCountry=intval(empty($_POST['b_country'])?$_POST['country']:$_POST['b_country']);

				if(!$this->validateIBANCode(trim($_POST['iban_number']),null)) $this->Assign("iban_number",$_POST['iban_number'],"wrong_iban",$this->iban_message);
			}

			if($_POST['swift_code']=='') $this->Assign("swift_code",$_POST['swift_code'],"noempty",$this->nullmessage);
        }

		

        $this->Assign("address1",$_POST['address1'],"noempty",$this->nullmessage);
        $this->Assign("state",$_POST['state'],"noempty",$this->nullmessage);
        $this->Assign("currency_id",$_POST['currency_id'],"noempty",$this->nullmessage);
        $this->Assign("country",$_POST['country'],"noempty",$this->nullmessage);
        $this->Assign("postal",$_POST['postal'],"noempty",$this->nullmessage);
		$this->Assign("p_ph_code",trim($_POST['p_ph_code']),
			"noempty/format'".FORMAT_VALIDATE_PHONE_NUMBER."'",
			$this->nullmessage."/".$this->formatmessage);

		if(strlen(trim($_POST['f_ph_code']))>0) {
			$this->Assign("f_ph_code",trim($_POST['f_ph_code']),
				"noempty/format'".FORMAT_VALIDATE_PHONE_NUMBER."'",
				$this->nullmessage."/".$this->formatmessage);
		}

		$this->Assign("email",trim($_POST['email']),
			"noempty/emailcheck",
			$this->nullmessage."/".$this->emailmessage);

		// * deal with billing address
        if($_POST['same_billing_address']!="1") {
			$this->Assign("b_address1",$_POST['b_address1'],"noempty",$this->nullmessage);
			$this->Assign("b_state",$_POST['b_state'],"noempty",$this->nullmessage);

			$this->Assign("b_country",$_POST['b_country'],
				"noempty/nospecial''",
				$this->nullmessage."/".$this->spcharmessage);

			$this->Assign("b_postal",$_POST['b_postal'],"noempty",$this->nullmessage);

			$this->Assign("b_p_ph_code",trim($_POST['b_p_ph_code']),
				"noempty/format'".FORMAT_VALIDATE_PHONE_NUMBER."'",
				$this->nullmessage."/".$this->formatmessage);

			$this->Assign("b_email",trim($_POST['b_email']),
				"noempty/emailcheck",
				$this->nullmessage."/".$this->emailmessage);

			if(strlen(trim($_POST['b_f_ph_code']))>0) {
				$this->Assign("b_f_ph_code",trim($_POST['b_f_ph_code']),
					"noempty/format'".FORMAT_VALIDATE_PHONE_NUMBER."'",
					$this->nullmessage."/".$this->formatmessage);
			}
        }

        $this->Assign("d_name",$_POST['d_name'],
			"noempty/nospecial' '",
			$this->nullmessage."/".$this->spcharmessage);

		$this->Assign("d_ph_code",trim($_POST['d_ph_code']),
			"noempty/format'".FORMAT_VALIDATE_PHONE_NUMBER."'",
			$this->nullmessage."/".$this->formatmessage);

		$this->Assign("d_email",trim($_POST['d_email']),
			"noempty/emailcheck",
			$this->nullmessage."/".$this->emailmessage);

		$this->Assign("d_since",$_POST['d_since'],"noempty/nospecial''",
			$this->nullmessage."/".$this->spcharmessage);

		if(strlen(trim($_POST['d_value']))>0) {
			$this->Assign("d_value",trim($_POST['d_value']),
				"noempty/nostring",
				$this->nullmessage."/".$this->numbermessage);
		}

		$this->Assign("d_payment",trim($_POST['d_payment']),
			"noempty/onlyinteger",
			$this->nullmessage."/".$this->numbermessage);

		if(strlen(trim($_POST['d_notes']))>0) {
			$this->Assign("d_notes",trim($_POST['d_notes']),
				"onlyinteger",$this->numbermessage);
		}

		$this->Assign("d_invoice",trim($_POST['d_invoice']),
			"noempty/onlyinteger",
			$this->nullmessage."/".$this->numbermessage);

        $this->Assign("d_revenue",$_POST['d_revenue'],
			"noempty/nostring",
			$this->nullmessage."/".$this->numbermessage);

        $action='index.php?do=createdebtor';

		// * deal with file upload
        if($_POST['debtor_type']=='debtor') {
			require_once('classes/Lib/PHPExcel/IOFactory.php');
            require_once('classes/Lib/debtorHistoryFileAPI.php');

			$tmp='filecsv';

            if(empty($_POST['customMapping'])) {
				if(empty($_FILES[$tmp]['tmp_name'])) {
					$this->Assign($tmp,"","noempty",
						"You must upload Debtor Experience File!");
					$this->PerformValidation($action);
					return;
				}

				if(debtorHistoryFileAPI::checkFileCount($_FILES)===false) {
					$this->Assign($tmp,'',"noempty",
						"You can upload only a single Debtor Experience File!");
					$this->PerformValidation($action);
                    return;
                }

				if(debtorHistoryFileAPI::checkFileSize($_FILES[$tmp]['size'])===false) {
					$this->Assign($tmp,"","noempty",
						"The Debtor Experience File size should be less than 4MB");
					$this->PerformValidation($action);
					return;
				}

				if(debtorHistoryFileAPI::checkFileMime($_FILES[$tmp]['type'])===false) {
					$this->Assign($tmp,'',
						"noempty",
						"The Debtor Experience File must be uploaded in one of the following formats: XLS, XLSX, CSV");
                    $this->PerformValidation($action);
                    return;
                }
                $fileName=$_FILES[$tmp]['tmp_name'];
            }
            else
                $fileName="";

            $debtHistFileObj=new debtorHistoryFileAPI($fileName);
            if(strlen($fileName)==0 && !empty($_SESSION['csvFileObject'])) {
				$debtHistFileObj->setDataObject($_SESSION['csvFileObject']);
				$debtHistFileObj->setTypeMapping($_POST);
				$debtHistFileObj->parseWorkSheet();
				unset($_SESSION['csvFileObject']);
			}

			$errorsFound=$debtHistFileObj->getErrors();
			$undefTypes=$debtHistFileObj->getUndefinedTypes();

            if(count($undefTypes)>0 && strlen($errorsFound)==0) {
				$_SESSION['csvFileUndefinedTypes']=$undefTypes;
                $errorsFound=1;
            }
            else
                unset($_SESSION['csvFileUndefinedTypes']);

            if(strlen($errorsFound)>0) {
				if(empty($_SESSION['csvFileUndefinedTypes'])) {
					$errorsFound=preg_replace("/".trim($debtHistFileObj->nlChars)."$/",
						"",trim($errorsFound));
                    $message="Upload file may not be correctly formatted. ".
                            "Use the template link below, format the file correctly and then try again.  ".
                            "<br/>".$errorsFound;
                }
                else {
					$message="Type clarification required. See above for details.";
                    $_SESSION['csvFileObject']=$debtHistFileObj->getSerializedDataObject();
                }
                $this->Assign($tmp,'',"noempty",$message);
				unset($_SESSION['csvFileData']);
            }
            else {
				$data=$debtHistFileObj->getData();
                array_shift($data);
                $_SESSION['csvFileData']=$data;
            }
        }
        $this->PerformValidation($action);
    }

	//Validates First Bid input of an Invoice
	function openbidnow()
	{


		$this->Assign("min_bid",$_POST['min_bid'],"noempty","
			Your Bid -".$this->nullmessage);
		$this->Assign("inv_id",$_POST['inv_id'],"noempty",
			"Form has some Error Please logout and login again -".$this->nullmessage);




		$this->PerformValidation('index.php?do=tradewindow&trade_id='.$_POST['inv_id']);
	}

	//Validates Other Bid inputs of an Invoice
	function updatebidnow()
	{

		$this->Assign("min_bid",$_POST['min_bid'],"noempty","
			Your Bid -".$this->nullmessage);
		$this->Assign("inv_id",$_POST['inv_id'],"noempty",
			"Form has some Error Please logout and login again -");

		$this->PerformValidation('index.php?do=tradewindow&trade_id='.$_POST['inv_id']);
	}




/* ------ INvestor Validation Function ------------------------------- */



	function validateAddInvestor()
	{
		if(!$this->isValidURL($_POST['org_website']) && $_POST['org_website']!='')
			$this->Assign("org_website","","noempty",$this->urlmessage);

        $this->Assign("org_organisationname",$_POST['org_organisationname'],"noempty",$this->nullmessage);
		$this->Assign("currency_id",$_POST['currency_id'],"noempty",$this->nullmessage);

		if($_POST['org_orgtype']=='0')
		{
		$this->Assign("org_orgtype","","noempty","".$this->nullmessage);
		}
		if($_POST['org_jurorg']=='0')
		{
		$this->Assign("org_jurorg","","noempty","".$this->nullmessage);
		}
		$this->Assign("org_pn",$_POST['org_country'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_pn",$_POST['org_area'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_pn",$_POST['org_pn'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_fx_pn",$_POST['org_fx_country'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_fx_pn",$_POST['org_fx_area'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("org_fx_pn",$_POST['org_fx_pn'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		if($_POST['busi_entity']=='0')
		{
		$this->Assign("busi_entity","","noempty","".$this->nullmessage);
		}
		if($_POST['juris_org']=='0')
		{
		$this->Assign("juris_org","","noempty","".$this->nullmessage);
		}

		$orgStatus = $_POST['org_bentitytype'];

		if($orgStatus != 11 && $orgStatus != 47 && $orgStatus != 48){
		$this->Assign("org_pcdetail",$_POST['org_pcdetail'],"noempty","".$this->nullmessage);
		}
		$this->Assign("org_form_year",$_POST['org_form_year'],"noempty","".$this->nullmessage);

		$this->Assign("orgcaddr1",$_POST['orgcaddr1'],"noempty","".$this->nullmessage);
		$this->Assign("orgc_city",$_POST['orgc_city'],"noempty",
			$this->nullmessage);

		if($_POST['orgc_country']=='0')
		{
			$this->Assign("orgc_country","","noempty","".$this->nullmessage);
		}


		$this->Assign("orgc_ph_pn",$_POST['orgc_ph_country'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgc_ph_pn",$_POST['orgc_ph_area'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgc_ph_pn",$_POST['orgc_ph_pn'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgc_fn_country",$_POST['orgc_fn_country'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgc_fn_country",$_POST['orgc_fn_area'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgc_fn_country",$_POST['orgc_fn_pn'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);

		if(!$this->isValidEmail($_POST['orgc_email']))
					$this->Assign("orgc_email","","noempty"," ".$this->nullmessage);

		$this->Assign("address_select", $_POST['address_select'],"noempty",
							"".$this->nullmessage);

		if($_POST["address_select"] !=''){

		$this->Assign("orgp_add1",$_POST['orgp_add1'],"noempty",
			" ".$this->nullmessage);

		$this->Assign("orgp_city",$_POST['orgp_city'],"noempty",
			$this->nullmessage);

		if($_POST['orgp_country']=='0')
		{
			$this->Assign("orgp_country","","noempty",
			$this->nullmessage);
		}

		$this->Assign("orgp_pn_country",$_POST['orgp_pn_country'],"noempty/nospecial''",
			" ".$this->nullmessage."/".
			"".$this->spcharmessage);

		$this->Assign("orgp_pn_country",$_POST['orgp_pn_country'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgp_pn_area",$_POST['orgp_pn_area'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgp_pn_pn",$_POST['orgp_pn_pn'],"noempty/nospecial' '/nostring",
			"".$this->nullmessage."/".
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgp_fx_pn",$_POST['orgp_fx_country'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgp_fx_pn",$_POST['orgp_fx_area'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);
		$this->Assign("orgp_fx_pn",$_POST['orgp_fx_pn'],"nospecial' '/nostring",
			"".$this->spcharmessage."/".$this->stringmessage);


		if(!$this->isValidEmail($_POST['orgp_email']))
			$this->Assign("orgp_email","","noempty",
				"".$this->nullmessage);
		}

			for($i=0; $i<count($_POST['orgb_addr1']); $i++)
			{


				$this->Assign("orgb_addr1".$i,$_POST['orgb_addr1'][$i],"noempty",
					$this->nullmessage);
				$this->Assign("orgb_city".$i,$_POST['orgb_city'][$i],"noempty",
					$this->nullmessage);
				$this->Assign("orgb_state".$i,$_POST['orgb_state'][$i],"nonumber",
				"".$this->numbermessage);

				/*$this->Assign("orgb_pc".$i,$_POST['orgb_pc'][$i],"nospecial' '",$this->spcharmessage);*/
				if($_POST['orgb_country'][$i]=='0')
				{
					$this->Assign("orgb_country".$i,"","noempty",$this->nullmessage);
				}
				$this->Assign("orgb_pn_pn".$i,$_POST['orgb_pn_country'][$i],"noempty/nospecial''",
					" ".$this->nullmessage."/".
					"".$this->spcharmessage);
				$this->Assign("orgb_pn_pn".$i,$_POST['orgb_pn_area'][$i],"noempty/nospecial''/nostring",
					"".$this->nullmessage."/".
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_pn_pn".$i,$_POST['orgb_pn_pn'][$i],"noempty/nospecial''/nostring",
					"".$this->nullmessage."/".
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_fn_pn".$i,$_POST['orgb_fn_country'][$i],"nospecial''/nostring",
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_fn_pn".$i,$_POST['orgb_fn_area'][$i],"nospecial''/nostring",
					"".$this->spcharmessage."/".$this->stringmessage);
				$this->Assign("orgb_fn_pn".$i,$_POST['orgb_fn_pn'][$i],"nospecial''/nostring",
					"".$this->spcharmessage."/".$this->stringmessage);


				if(!$this->isValidEmail($_POST['orgb_email'][$i]))
					$this->Assign("orgb_email".$i,"","noempty",
						"".$this->nullmessage);
			}

		if($_POST['bank_c_email'] !='')	{

			if(!$this->isValidEmail($_POST['bank_c_email']))
			$this->Assign("bank_c_email", "","noempty",
								"".$this->emailmessage);
		}


		$this->Assign("account_name", $_POST['account_name'],"noempty",
							"".$this->nullmessage);

		$this->Assign("account_no", $_POST['account_no'],"noempty",
							"".$this->nullmessage);

		$this->Assign("sort_code", $_POST['sort_code'],"noempty",
							"".$this->nullmessage);

		$this->PerformValidation('index.php?do=invapplication1');
	}


	function validateAddInvestorTwo()
	{

		for($i=0; $i<count($_POST['cp_fname']); $i++)
		{
			$this->Assign("cp_fname".$i,$_POST['cp_fname'][$i],"noempty",$this->nullmessage);
			$this->Assign("cp_lname".$i,$_POST['cp_lname'][$i],"noempty",$this->nullmessage);
			$this->Assign("cp_jtitle".$i,$_POST['cp_jtitle'][$i],"noempty/nonumber/nospecial' '",$this->nullmessage."/".
						$this->numbermessage."/".
						$this->spcharmessage);


			if(checkdate(intval($_POST['cp_dob_mon'][$i]),intval($_POST['cp_dob_date'][$i]),intval($_POST['cp_dob_year'][$i])))
			{
					$birth = $_POST['cp_dob_year'][$i].'-'.$_POST['cp_dob_mon'][$i].'-'.$_POST['cp_dob_date'][$i];
					$age = $this->determine_age($birth);
					if($age < 18)
						$this->Assign("cp_dob_year".$i,"","noempty","Age should be above 18");

			}
			else
			{
				$this->Assign("cp_dob_year".$i,"","noempty","Enter a valid date");
			}

			$this->Assign("cp_dob_year".$i,$_POST['cp_dob_mon'][$i],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("cp_dob_year".$i,$_POST['cp_dob_date'][$i],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("cp_dob_year".$i,$_POST['cp_dob_year'][$i],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);


			$this->Assign("cp_os_type".$i,$_POST['cp_os_type'][$i],"noempty",$this->nullmessage);

			if($_POST['cp_os_type'][$i] == '2')
			{
				$this->Assign("cp_per".$i,$_POST['cp_per'][$i],"noempty",$this->nullmessage);
				if($_POST['cp_per'][$i]>'100')
				{
					$this->Assign("cp_per".$i,"","noempty","Enter a valid percentage");
				}
			}

			$this->Assign("cp_ha_addr1".$i,$_POST['cp_ha_addr1'][$i],"noempty",
				$this->nullmessage);
			$this->Assign("cp_ha_city".$i,$_POST['cp_ha_city'][$i],"noempty",
				$this->nullmessage);

			$this->Assign("cp_ha_ph_pn".$i,$_POST['cp_ha_ph_country'][$i],"noempty/nospecial''",
				" ".$this->nullmessage."/".
				"".$this->spcharmessage);
			$this->Assign("cp_ha_ph_pn".$i,$_POST['cp_ha_ph_area'][$i],"noempty/nospecial''/nostring",
				"".$this->nullmessage."/".
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_ha_ph_pn".$i,$_POST['cp_ha_ph_pn'][$i],"noempty/nospecial''/nostring",
				"".$this->nullmessage."/".
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_ha_fn_pn".$i,$_POST['cp_ha_fn_country'][$i],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_ha_fn_pn".$i,$_POST['cp_ha_fn_area'][$i],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_ha_fn_pn".$i,$_POST['cp_ha_fn_pn'][$i],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);

			if(!$this->isValidEmail($_POST['cp_ha_email'][$i]))
				$this->Assign("cp_ha_email".$i,"","noempty",
					"".$this->nullmessage);


			$this->Assign("address_select", $_POST['address_select'],"noempty",
							"".$this->nullmessage);

			if($_POST["address_select"] !=''){

			$this->Assign("cp_wa_addr1",$_POST['cp_wa_addr1'],"noempty",
				$this->nullmessage);
			$this->Assign("cp_wa_city",$_POST['cp_wa_city'],"noempty",
				$this->nullmessage);

			$this->Assign("cp_wa_ph_pn",$_POST['cp_wa_ph_country'],"noempty/nospecial''",
				" ".$this->nullmessage."/".
				"".$this->spcharmessage);
			$this->Assign("cp_wa_ph_pn",$_POST['cp_wa_ph_area'],"noempty/nospecial''/nostring",
				"".$this->nullmessage."/".
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_ph_pn",$_POST['cp_wa_ph_pn'],"noempty/nospecial''/nostring",
				"".$this->nullmessage."/".
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_fn_pn",$_POST['cp_wa_fn_country'],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_fn_pn",$_POST['cp_wa_fn_area'],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);
			$this->Assign("cp_wa_fn_pn",$_POST['cp_wa_fn_pn'],"nospecial''/nostring",
				"".$this->spcharmessage."/".$this->stringmessage);

			if(!$this->isValidEmail($_POST['cp_wa_email']))
				$this->Assign("cp_wa_email","","noempty/nospecial' '",
					"".$this->nullmessage."/".
					"".$this->emailmessage);
			}
		}


			$this->Assign("sub_fname",$_POST['sub_fname'],"noempty",
				"".$this->nullmessage);
			$this->Assign("sub_lname",$_POST['sub_lname'],"noempty",
				"".$this->nullmessage);
			if(!checkdate(intval($_POST['sub_month']),intval($_POST['sub_date']),intval($_POST['sub_year'])))
			{
				$this->Assign("sub_year","","noempty","Enter a valid date");

			}

			$this->Assign("sub_year",$_POST['sub_date'],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("sub_year",$_POST['sub_month'],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);
			$this->Assign("sub_year",$_POST['sub_year'],"noempty/nostring/nospecial"," ".$this->nullmessage."/".$this->stringmessage."/".$this->spcharmessage);


			$this->Assign("sub_approvel",$_POST['sub_approvel'],"noempty","".$this->nullmessage);
					$this->Assign("terms",$_POST['terms'],"noempty",
						$this->nullmessage);

			$this->PerformValidation('index.php?do=invapplication2&id='.$_SESSION['organisation_id']);

	}

	function investorCompose()
	{

		if(!$this->isValidEmail($_POST['to_email']))
		{
			$this->Assign("to_email","","noempty",$this->emailmessage);

		}
		else
		{

			$sql="SELECT address_email FROM address_details WHERE address_email='".$_POST["to_email"]."'";
			$query = new Bin_Query();
			$query->executeQuery($sql);
			$cnt=count($query->records);
			if($cnt=='0')
			$this->Assign("to_email","","noempty","MailId is not available");

		}

		$this->Assign("subject",trim($_POST["subject"]),"noempty",$this->nullmessage);
		$this->Assign("message",trim($_POST["message"]),"noempty",$this->nullmessage);
		$this->PerformValidation('index.php?do=investorcompose');

	}



	function traderCompose()
	{

		if(!$this->isValidEmail($_POST['to_email']))
		{
			$this->Assign("to_email","","noempty",$this->emailmessage);

		}
		else
		{

			$sql="SELECT address_email FROM address_details WHERE address_email='".$_POST["to_email"]."'";
			$query = new Bin_Query();
			$query->executeQuery($sql);
			$cnt=count($query->records);
			if($cnt=='0')
			$this->Assign("to_email","","noempty","MailId is not available");

		}

		$this->Assign("subject",trim($_POST["subject"]),"noempty",$this->nullmessage);
		$this->Assign("message",trim($_POST["message"]),"noempty",$this->nullmessage);
		$this->PerformValidation('index.php?do=originatorcompose');

	}


	function saveMyProfile(){

		$this->Assign("email", $_POST["email"],"noempty",
						"".$this->nullmessage);

		$this->Assign("f_name", $_POST["f_name"],"noempty",$this->nullmessage);

		$this->Assign("l_name", $_POST["l_name"],"noempty",$this->nullmessage);

		$this->Assign("job", $_POST["job"],"noempty",$this->nullmessage);

		$this->Assign("org_name", $_POST["org_name"],"noempty",$this->nullmessage);

		$this->Assign("org_addr", $_POST["org_addr"],"noempty",$this->nullmessage);

// 		$this->Assign("org_addr1", $_POST["org_addr1"],"noempty/nostring/nospecial' '",
// 								"".$this->nullmessage.
// 								"/".$this->numbermessage.
// 								"/".$this->spcharmessage);

		$this->Assign("org_code", $_POST["org_code"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_state", $_POST["org_state"],"nospecial' '",
								"".$this->spcharmessage);
		$this->Assign("org_country", $_POST["org_country"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_country", $_POST["org_ph_country"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_area", $_POST["org_ph_area"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_ph_phone", $_POST["org_ph_phone"],"noempty/nostring/nospecial' '",
								"".$this->nullmessage.
								"/".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_m_country", $_POST["org_m_country"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_m_area", $_POST["org_m_area"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);
		$this->Assign("org_m_phone", $_POST["org_m_phone"],"nostring/nospecial' '",
								"".$this->numbermessage.
								"/".$this->spcharmessage);


		$this->PerformValidation('index.php?do=editmyprofile');
	}

	function saveMyInvQuestion(){

		$this->Assign("secret_quest", $_POST["secret_quest"],"noempty","".$this->nullmessage);
		$this->Assign("secret_answer", $_POST["secret_answer"],"noempty","".$this->nullmessage);

		$this->PerformValidation('index.php?do=editdetails');
	}

	function saveMyInvPassword(){
		$user_id = $_SESSION['user']['userid'];

		$this->Assign("oldpasswd", $_POST["oldpasswd"],"noempty","".$this->nullmessage);
		$this->Assign("passwd", $_POST["passwd"],"noempty","".$this->nullmessage);
		$this->Assign("retype", $_POST["retype"],"noempty","".$this->nullmessage);

		if($_POST["oldpasswd"] !='')
		{
			$query = new Bin_Query();
			$sql_user = "SELECT * FROM user_login WHERE user_id = '".$user_id."'
				AND user_password = '".trim(md5(base64_encode($_POST["oldpasswd"])))."'";
			$query->executeQuery($sql_user);
			$profile = $query->records;

			if(count($profile) == 0)
			{
				$message="Incorrect current password";
				$this->Assign("oldpasswd",'',"noempty",$message);
			}
		}


		if($_POST["passwd"] !='' && $_POST["retype"] !='')
		{
			if($_POST["passwd"] != $_POST["retype"])
			{
				$message="Incorrect password confirmation";
				$this->Assign("retype",'',"noempty",$message);
				$_POST["retype"]='';
			}
		}

		$this->PerformValidation('index.php?do=editdetails');

	}





/* ----------------------------------------- Predefined Validation Function ------------------------------- */

	function isValidEmail($email)
	{
		if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$", $email))
			return false;
		else
			return true;
	}

	function isValidURL($url)
	{
		//return preg_match('|[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);

		$domain = "http://".str_replace("http://","",$url);

		//check, if a valid url is provided
               if(!filter_var($domain, FILTER_VALIDATE_URL))
               {
                       return false;
               }

               //initialize curl
               $curlInit = curl_init($domain);
               curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
               curl_setopt($curlInit,CURLOPT_HEADER,true);
               curl_setopt($curlInit,CURLOPT_NOBODY,true);
               curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);

               //get answer
               $response = curl_exec($curlInit);

               curl_close($curlInit);

               if ($response) return true;

               return false;
	}

	function validateNumber($str)
	{
		$flag = 0;
		$str_array = str_split($str,1);
		foreach($str_array as $value)
		{
			if(!is_numeric($value))
			{
				$flag++;
			}
		}
		if($flag > 0)
			return true;
		else
			return false;
	}

	function loginValidate()
	{
        require_once ROOT_FOLDER.'/classes/Model/MUser.php';
        $userModel = new Model_MUser();

		$this->Assign("username",$_POST['username'],"noempty",$this->nullmessage);
		$this->Assign("password",$_POST['password'],"noempty",$this->nullmessage);

		if(isset($_POST['txtverify']))
			$this->Assign("txtverify",$_POST['txtverify'],"noempty",$this->nullmessage);

		$captcha = 0;
		if(trim($_POST['txtverify'])!='')
		{
			if(strcmp($_SESSION['security_code'],$_POST['txtverify'])!=0)
			{
			 	$message1='Incorrect Code';
				$this->Assign("txtverify","","noempty",$message1);
			}else{
				$captcha = 1;
			}
		}

		if(!empty($_POST["username"]) && !empty($_POST["password"]) && $captcha == 1  && !empty($_POST["txtverify"]))
		{
            $user = $userModel->getUserForLogin($_POST["username"]);

            if(!$user or $user['password'] != Bin_Security::hashPassword($_POST["password"])){
                $this->Assign("userlogin","","noempty","Invalid Username and | or Password");
            }else {
                $loginResult = $userModel->completeLogin($user);
                if ($loginResult !== true) {
                    $this->Assign("userlogin", "", "noempty", $loginResult);
                }else{
                    //Check password expiration
                    if($userModel->isPasswordExpired($user) && !$user['from_salesforce']){
                        header('Location: '.Bin_Request::getInstance()->oguiUrl('editpersonal').'&pe=1');
                    }
                }
            }
		}
		$this->PerformValidation('index.php?do=login');
	}


	function validateSignin()
	{
		$getUser = new Bin_Query();
		$this->Assign("username",trim($_POST["username"]),"noempty","User Name".$this->nullmessage);
		$this->Assign("password",trim($_POST["password"]),"noempty","Password".$this->nullmessage);

		if(!empty($_POST["username"]) && !empty($_POST["password"]))
		{
			$sql_user="SELECT * FROM temp_registration WHERE username ='".trim($_POST["username"])."'AND password = '".$_POST["password"]."' ";
    			$sql_user = "SELECT * FROM user_registration WHERE username = '".trim($_POST["username"])."'
			AND password = '".$_POST["password"]."' AND verified = '0' AND user_status='0'";
    			if($getUser->executeQuery($sql_user))
			{
    		     		$this->Assign("errmsg","","noempty","Your Account is not Verified");
			}
			else
			{
				$sql_user = "SELECT * FROM user_registration WHERE username = '".trim($_POST["username"])."'
				AND password = '".$_POST["password"]."' AND verified = '1' AND user_status='0'";
				if($getUser->executeQuery($sql_user))
				{
					$this->Assign("errmsg","","noempty","Your Account has been Suspended By Admin");
				}
				else
				{
					$sql_user = "SELECT * FROM user_registration WHERE username = '".trim($_POST["username"])."'
					AND password = '".$_POST["password"]."' AND verified = '1' AND user_status='1'";
					if(!$getUser->executeQuery($sql_user))
					{
						$this->Assign("errmsg","","noempty","Invalid Username and | or Password");
					}
					else
					{
						$_SESSION["user"] = array("username"=>trim($_POST["username"]),"userid"=>$getUser->records[0]["user_id"],"user"=>$getUser->records[0]['firstname']." ".$getUser->records[0]['lastname']);
					}
				}


			}

		}
		$this->PerformValidation('index.php?do=login');
	}
	function determine_age($birth_date)
	{
		$birth_date_time = strtotime($birth_date);
		$to_date = date('m/d/Y', $birth_date_time);

		list($birth_month, $birth_day, $birth_year) = explode('/', $to_date);

		$now = time();

		$current_year = date("Y");

		$this_year_birth_date = $birth_month.'/'.$birth_day.'/'.$current_year;
		$this_year_birth_date_timestamp = strtotime($this_year_birth_date);

		$years_old = $current_year - $birth_year;

		if($now < $this_year_birth_date_timestamp)
			$years_old = $years_old - 1;

		return $years_old;
	}

	function validatePayment(){

		$this->Assign("card_type", $_POST["card_type"],"noempty/nospecial' '",
						"".$this->nullmessage.
						"/".$this->spcharmessage);

		$this->Assign("number", $_POST["number"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("month", $_POST["month"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("year", $_POST["year"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);

		$this->Assign("cvv2", $_POST["cvv2"],"noempty/nostring/nospecial' '",
						"".$this->nullmessage.
						"/".$this->numbermessage.
						"/".$this->spcharmessage);
		$this->Assign("name", $_POST["name"],"noempty/nospecial' '",
						"".$this->nullmessage.
						"/".$this->spcharmessage);

		$this->PerformValidation('index.php?do=checkout');
	}

	function validateSpecialChar($element){

// -
		if(preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬]/', $element))
			return false;
		else
			return true;

	}


	function specialCharCheck($element){


		if(preg_match('/[\'^£$%@#?><>,|=+¬]/', $element)){

			return false;
		}
		else{
			return true;
		}

	}

    function validateReplaceDebtorDoc()
    {
        $qry=new Bin_Query();
        $sql="SELECT d.debtor_name,u.user_id FROM debtors_detail d ".
                "LEFT JOIN debtor_relation r ON r.debtor_id=d.debtor_id ".
                "LEFT JOIN user_login u ON u.user_id=r.trader_id ".
                "WHERE d.debtor_id='".$_REQUEST['id']."' LIMIT 1 ";
        $qry->executeQuery($sql);
        $debtor=$qry->records[0];

        /*
         * $qry=new Bin_Query();
         * $sql="SELECT filescv FROM debtors_detail WHERE debtor_id='".$_REQUEST['id']."' ";
         * $qry->executeQuery($sql);
         * $records=$qry->records[0]['filescv'];
         * if($records!='' && $_FILES['filecsv']['tmp_name']=='')
         * {
         *  $this->Assign('filecsv','',"noempty",''.$this->nullmessage);
         * }
         */


        $action='index.php?do=replacedebtordoc&id='.$_REQUEST['id'];
        $tmp='filecsv';

        require_once('classes/Lib/PHPExcel/IOFactory.php');
        require_once('classes/Lib/debtorHistoryFileAPI.php');

        if(empty($_POST['customMapping']))
        {
            if(empty($_FILES[$tmp]['tmp_name']))
            {
                $this->Assign($tmp,"","noempty","You must upload Debtor Experience File!");
                $this->PerformValidation($action);
                return;
            }

            if(debtorHistoryFileAPI::checkFileCount($_FILES)===false)
            {
                $this->Assign($tmp,'',"noempty","You can upload only ".
                        "a single Debtor Experience File!");
                $this->PerformValidation($action);
                return;
            }

            if(debtorHistoryFileAPI::checkFileSize($_FILES[$tmp]['size'])===false)
            {
                $this->Assign($tmp,"","noempty","The Debtor Experience File size ".
                        "should be less than 4MB");
                $this->PerformValidation($action);
                return;
            }

            if(debtorHistoryFileAPI::checkFileMime($_FILES[$tmp]['type'])===false)
            {
                $this->Assign($tmp,'',"noempty","The Debtor Experience File must be ".
                        "uploaded in either of the following formats: XLS, XLSX, CSV");
                $this->PerformValidation($action);
                return;
            }
            $fileName=$_FILES[$tmp]["tmp_name"];
        }
        else
            $fileName="";

        $debtHistFileObj=new debtorHistoryFileAPI($fileName);
        if(strlen($fileName)==0 && !empty($_SESSION['csvFileObject']))
        {
            $debtHistFileObj->setDataObject($_SESSION['csvFileObject']);
            $debtHistFileObj->setTypeMapping($_POST);
            $debtHistFileObj->parseWorkSheet();
            unset($_SESSION['csvFileObject']);
        }

        $errorsFound=$debtHistFileObj->getErrors();
        $undefTypes=$debtHistFileObj->getUndefinedTypes();

        if(count($undefTypes)>0 && strlen($errorsFound)==0)
        {
            $_SESSION['csvFileUndefinedTypes']=$undefTypes;
            $errorsFound=1;
        }
        else
            unset($_SESSION['csvFileUndefinedTypes']);


        if(strlen($errorsFound)>0)
        {
            if(empty($_SESSION['csvFileUndefinedTypes']))
            {
                $errorsFound=preg_replace("/".trim($nlChars)."$/","",trim($errorsFound));
                $message="Upload file may not be correctly formatted. ".
                        "Use the template link below, format the file correctly and then try again.  ".
                        "<br>".$errorsFound;
            }
            else
            {
                $message="Type clarification required. See above for details.";
                $_SESSION['csvFileObject']=$debtHistFileObj->getSerializedDataObject();
            }
            $this->Assign($tmp,'',"noempty",$message);
            unset($_SESSION['csvFileData']);
        }
        else
        {
            // * $_SESSION['csvFileName']=$file_name;
            $data=$debtHistFileObj->getData();
            array_shift($data);
            $_SESSION['csvFileData']=$data;
        }

        $this->PerformValidation($action);
    }

	function validateDebtorContactCreate()
	{
		$this->Assign("debtor_id",trim($_POST['debtor_id']), "noempty/nostring", $this->nullmessage."/".$this->numbermessage);

		if (!$this->isValidEmail($_POST['email'])){
			$this->Assign("email", "" ,"noempty", "Enter a valid email Address");
		}

		$this->PerformValidation("service");
	}

	function validateDebtorContactUpdate()
	{
		$this->Assign("id",trim($_POST['id']), "noempty/nostring", $this->nullmessage."/".$this->numbermessage);

		if (!$this->isValidEmail($_POST['email'])){
			$this->Assign("email", "" ,"noempty", "Enter a valid email Address");
		}

		$this->PerformValidation("service");
	}

	function saveOrpaValidate()
	{
        if (!empty($_REQUEST['orpa_id'])) {
            $action = 'index.php?do=edit_oetr&orpa_id=' . $_REQUEST['orpa_id'];
        } else {
            $action = 'index.php?do=create_oetr';
        }
        
        $this->Assign("ex_date",$_POST['ex_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
        $this->Assign("ex_date",$_POST['ex_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
        $this->Assign("ex_date",$_POST['ex_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
        
        
        if (strtotime($_POST['ex_year'].'-'.$_POST['ex_month'].'-'.$_POST['ex_date'])<strtotime(FIRST_TRADE_DATE))
        {
            $this->Assign("ex_date","","noempty","Expected Date should be greater than '".FIRST_TRADE_DATE."'");
        }
        if (!checkdate($_POST['ex_month'], $_POST['ex_date'], $_POST['ex_year'])) {
            $this->Assign("ex_date", "", "noempty", $this->invaliddatemessage);
        }
        
        $this->PerformValidation($action);
	}

	function saveUploadOrpaValidate()
	{
	    $db = Bin_Db::connect();

        $selectPoNumbers = "SELECT po_no FROM orpa_po";
        $result = $db->query($selectPoNumbers);
        $resultArray = $result ? $result->getResultArray() : array();
        $poNumbers = array();
        foreach ($resultArray as $res){
            $poNumbers[] = $res['po_no'];
        }

        foreach ($_POST['amount'] as $key => $amount) {
            $this->Assign("debtor_id_" . $key, $_POST['debtor_id'][$key], "noempty/nostring", $this->nullmessage . "/" . $this->numbermessage);
			$this->Assign("amount_".$key, $amount, "noempty/nostring", $this->nullmessage . "/" . $this->numbermessage);
            $this->Assign("po_" . $key, $_POST['po'][$key], "noempty", $this->nullmessage);
            $this->Assign("file_po_".$key, $_POST['file_po'][$key], "noempty", $this->nullmessage);
            if(in_array($_POST['po'][$key], $poNumbers)){
                $this->Assign("po_" . $key, '', "noempty", $this->uniquepomessage);
            }
            foreach ($_POST['po'] as $poKey => $val){
                if($key !== $poKey and $_POST['po'][$key] === $val and $val){
                    $this->Assign("po_" . $key, '', "noempty", $this->uniquepomessage);
                }
            }
        }

        $errors = $this->PerformValidation('service');
        exit(json_encode($errors));
	}

	function saveRevolvingOrpaValidate()
	{
        $modelUserOrpa = new Model_MUserOrpa();
        $poNumbers = $modelUserOrpa->getPoNumbersForDebtor($_POST['debtor_id'], false);

        $this->Assign("orpa_id", $_POST['orpa_id'], "noempty/nostring", $this->nullmessage . "/" . $this->numbermessage);
        $this->Assign("debtor_id", $_POST['debtor_id'], "noempty/nostring", $this->nullmessage . "/" . $this->numbermessage);
        $this->Assign("amount", $_POST['amount'], "noempty/nostring", $this->nullmessage . "/" . $this->numbermessage);
        $this->Assign("po", $_POST['po'], "noempty", $this->nullmessage);
        $this->Assign("file_po", $_POST['file_po'], "noempty", $this->nullmessage);
        if (in_array($_POST['po'], $poNumbers)) {
            $this->Assign("po", '', "noempty", $this->existpomessage);
        }
        
        
        $this->Assign("po_date",$_POST['po_year'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
        $this->Assign("po_date",$_POST['po_month'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
        $this->Assign("po_date",$_POST['po_date'],"noempty/nostring/nospecial","".$this->nullmessage."/".$this->numbermessage."/".$this->spcharmessage);
        
        if (strtotime($_POST['po_year'].'-'.$_POST['po_month'].'-'.$_POST['po_date'])<strtotime(FIRST_TRADE_DATE))
        {
            $this->Assign("po_date","","noempty","PO Date should be greater than '".FIRST_TRADE_DATE."'");
        }
        if (!checkdate($_POST['po_month'], $_POST['po_date'], $_POST['po_year'])) {
            $this->Assign("po_date", "", "noempty", $this->invaliddatemessage);
        }
        
        
        $errors = $this->PerformValidation('service');
        exit(json_encode($errors));
	}

    private function validatePostTradeDocuments($values){
        foreach ($values['document'] as $documentId=>$documentValues){
            if (!empty($documentValues['file']) or isset($documentValues['exist_document'])) {
                $this->Assign("document[$documentId][amount]", $documentValues['amount'], "noempty",
                    $this->nullmessage);
                $this->Assign("document[$documentId][amount]", $documentValues['amount'], "nostring",
                    $this->numbermessage);
            }
        }
        $this->PerformValidation('same_page');
    }

	private function validateIBANCode($code,$country) {
		include_once('admin/classes/Lib/iban_validation.php');

		if($country != null){
			$query=new Bin_Query();
			$query->executeQuery("SELECT country_value FROM country_mas WHERE country_id=".$country);
			$country=(count($query->records)>0)?$query->records[0]['country_value']:NULL;
		}
		
		$validator=new Iban_validation(array('country_code'=>$country));
		if(!$validator->isValid($code)) {
			$this->iban_message=$validator->getError();
			return false;
		}
		return true;
	}
}
?>