/**
  * Send a sms
  *
  * The most important method form the component. Send a sms.
  *
  */
 function DoSendSms()
 {
     //check global maxsms parameter before sending
     $sql = " /*com_byjg:dosendsms select global sms litmit */\r\n\t\t\t\tSELECT value FROM #__byjg_config WHERE name='maxsms' LIMIT 1";
     $this->db->setQuery($sql);
     //check result and output a message
     if ($this->db->query($sql) == false) {
         $this->errorHandler->Alert(JText::_('BYJG_SQLQUERY_ERROR'), $this->db->getErrorMsg());
     }
     $maxsms = $this->db->loadResult();
     if (!is_null($maxsms) && $maxsms > 0) {
         $limit = $maxsms;
         $sql = "SELECT COUNT(*) AS COUNTER FROM #__byjg_sendsms";
         $this->db->setQuery($sql);
         //check result and output a message
         if ($this->db->query($sql) == false) {
             $this->errorHandler->Alert(JText::_('BYJG_SQLQUERY_ERROR'), $this->db->getErrorMsg());
         }
         $row = $this->db->loadObject();
         if ($row->COUNTER >= $limit) {
             $this->errorHandler->Alert(JText::_('BYJG_GLOBAL_LIMIT_REACHED'));
         }
     }
     $msg = '';
     //get input parameters
     $sms_body = JRequest::getVar('sms_body', '');
     //dont check body, if we want to send a empty sms it is ok
     $sms_send = JRequest::getVar('sms_send', '');
     $from = $sms_send;
     $sms_ddd = JRequest::getVar('sms_ddd', '');
     $ad = JRequest::getVar('ad', '');
     if (strlen($sms_body) == 0) {
         $this->errorHandler->Alert(JText::_('BYJG_SMS_BODY_EMPTY'));
     }
     /*
     		 *  check sms sender
     		 	
       		if( strlen( $sms_send ) < 8 )
       		{
         		$this->errorHandler->Alert( JText::_( 'BYJG_INVALID_SENDER' ) );
       		}
     */
     $sms_recv = JRequest::getVar('sms_recv', '');
     $this->Filter($sms_recv);
     //check sms recv
     if (strlen($sms_recv) < 8) {
         $this->errorHandler->Alert(JText::_('BYJG_INVALID_RECIPIENT'));
         die;
     }
     //append advertisment to sms
     if (strlen($ad) > 0) {
         $bodyLen = strlen($sms_body);
         $adLen = strlen($ad);
         $len = $bodyLen + $adLen;
         if ($len > 160) {
             $sms_body = substr($sms_body, 0, 159 - strlen($ad));
             $sms_body .= "\n" . $ad;
         } else {
             $sms_body .= "\n" . $ad;
         }
     }
     //now check if the sms body is not longer that 160
     if (strlen($sms_body) > 160) {
         $sms_body = substr($sms_body, 0, 160);
     }
     //get the current sms provider
     //create provider factory
     $factory = new ProviderFactory();
     $provider = $factory->getActiveInstance();
     //check provider here
     if ($provider === false) {
         $this->errorHandler->Alert(JText::_('BYJG_NO_ACTIVE_PROVIDER'));
         die;
     }
     $errMsg = '';
     $arr = explode(";", $sms_recv);
     foreach ($arr as $recv) {
         $recv = trim($recv);
         //trim whitespaces
         if (strlen($recv) < 8) {
             continue;
         }
         //check user balance
         if ($this->user->balance() <= 0) {
             $this->errorHandler->Alert(JText::_('BYJG_NOT_SUFFICIENT_FUNDS'));
         }
         //trigger plugins if available
         $dispatcher = JDispatcher::getInstance();
         JPluginHelper::importPlugin('byjg');
         $data = array('message' => $sms_body, 'sender' => $sms_send, 'receiver' => $recv);
         $result = $dispatcher->trigger('onSendSms', $data);
         $abort = false;
         foreach ($result as $code) {
             if ($code == false) {
                 $abort = true;
                 break;
             }
         }
         //a plugin has returned false, so we cancel the send process
         if ($abort == true) {
             ByJGRedirect($this->CreateRedirectUrl(), JText::_('BYJG_PLUGIN_ABORT'));
         }
         /*
          * Chamada da funcao alterada por BYJG para atender ao Gateway ByJG
          *         alterado em 09.10.10
          * $ret = $provider->sendSMS( $sms_body, $sms_send, $recv, $msg );
          */
         $ret = $provider->sendSMS($sms_body, $sms_ddd, $recv, $sms_send, $msg);
         //sms sending failed
         if ($ret == false) {
             $errMsg .= JText::sprintf('BYJG_SEND_SMS_FAILED', $recv);
             $errMsg = $errMsg . ' (' . $msg . ').';
         } else {
             //dont forget to update the user balance
             $bal = (int) $this->user->balance();
             $bal--;
             if ($this->user->setBalance($bal) == false) {
                 $this->errorHandler->Alert(JText::_('BYJG_CHANGE_BALANCE_FAILED'));
             }
             //sendind was ok, so archive it
             $to = $sms_ddd . $recv;
             $text = $sms_body;
             $provider->archiveSMS($text, $from, $to);
             $errMsg .= JText::sprintf('BYJG_SEND_SMS_SUCCESSFULLY', $recv);
             $errMsg = $errMsg . ' (' . $msg . ').';
         }
     }
     ByJGRedirect($this->CreateRedirectUrl(), $errMsg);
 }
    /**
    * This function shows a provider selection panel before editing a provider
    *
    *  @param array $rows
    **/
    function showProviderSelectPanel(&$rows)
    {
        $option = JRequest::getCmd('option');
        ?>
        <form action="index.php" method="post" name="adminForm">
          <table class="adminheading">
		<tr>
	 	    <th class="edit" rowspan="2" nowrap="nowrap">Administrar Provedor<br /></th>
	       </tr>
	  </table>

	  <table class="adminlist">
	    <tr>
			<br />
			<div id="alerta" style="width: 85%; text-align: center; margin: 0 auto; border:#0B55C4 dotted 1px; background-color:#F6F6F6; padding: 5px;">
			<strong>IMPORTANTE:</strong> Este componente é distribuido gratuitamente. Pedimos apenas que ao criar sua conta nos provedores disponibilizados, 
			siga a <a href="index.php?option=com_byjg&amp;act=about" target="_self">orientação</a> na area da ajuda. Somente dessa maneira conseguiremos enxergar que o seu acesso ocorre pelo componente SMS BYJG e assim propiciar meios para que este componente possa continuar melhorando.
			</div>
			<br />&nbsp;Para adicionar ou substituir novos gateways, veja mais informa&ccedil;&otilde;es na se&ccedil;&atilde;o: "<a href="index.php?option=com_byjg&amp;act=about" target="_self">AJUDA - Gateways</a>".<br />
		</tr>
		<tr>
			<th width="5">#</th>
			<th width="5">
			<input type="checkbox" name="toggle" value="" onClick="checkAll(<?php 
        echo count($rows);
        ?>
);" />
			</th>
			<th class="title"><?php 
        echo JText::_('BYJG_PROVIDER');
        ?>
</th>
			<th class="title"><?php 
        echo JText::_('BYJG_ACTIV');
        ?>
</th>
	    </tr>
		<?php 
        $k = 0;
        $allow = false;
        for ($i = 0, $n = count($rows); $i < $n; $i++) {
            $row =& $rows[$i];
            ?>
			<tr>
			  <td></td>
			  <td><?php 
            echo JHTML::_('grid.id', $i, $row->id);
            ?>
</td>
			  <td>
			  <?php 
            echo $row->name;
            if ($row->name == 'ByJG') {
                $factory = new ProviderFactory();
                $provider = $factory->getActiveInstance();
                $msgBalance = '';
                $retornoBalance = $provider->recoverBalance($msgBalance);
                echo $retornoBalance;
            }
            ?>
			  </td>
			  <td>
			  	<?php 
            $status_provider = $row->active;
            if ($status_provider == 1) {
                ?>
						<img src="images/tick.png" width="16" height="16" border="0" alt="SMS Gateway Ativo"  title="SMS Gateway Ativo"/>
						<?php 
            } elseif ($status_provider == 0) {
                ?>
						<img src="images/publish_x.png" width="16" height="16" border="0" alt="SMS Gateway Inativo" title="SMS Gateway Inativo"/>
						<?php 
            }
            ?>
			  </td>
			</tr>
			<?php 
        }
        ?>
	  </table>

	  <input type="hidden" name="option" value="<?php 
        echo $option;
        ?>
" />
		<input type="hidden" name="act" value="provider" />
		<input type="hidden" name="task" value="configure" />
		<input type="hidden" name="boxchecked" value="0" />
		<input type="hidden" name="hidemainmenu" value="0" />
		</form>
		<table style="width: 100%;">
	<tr>
		<td style="text-align: center;">
			<div id="assinatura">
				<div style="float:left; width: 100%; text-align: center;">
					<br /><img src="http://www.byjg.com.br/imagens/logo-byjg-joomla.png" alt="SMS BYJG - ByJG Tecnologia e Sistemas" title="SMS BYJG - ByJG Tecnologia e Sistemas" width="250" height="35" />
				</div>
			</div>
		</td>
	</tr>
</table>
        <?php 
    }